Salome HOME
Unit test for checkin is ammended for testing the case with empty input list of steps.
[tools/siman.git] / Workspace / Siman-Common / src / test / splat / service / TestScenarioService.java
index d064e2fd3c00cb497ff4bdd0622cb685f7817ada..0710f118397850642d4b5d67357577c276e421ae 100644 (file)
@@ -24,8 +24,11 @@ import org.splat.dal.bo.kernel.Relation;
 import org.splat.dal.bo.kernel.User;
 import org.splat.dal.bo.som.Document;
 import org.splat.dal.bo.som.DocumentType;
+import org.splat.dal.bo.som.KnowledgeElementType;
 import org.splat.dal.bo.som.Publication;
 import org.splat.dal.bo.som.Scenario;
+import org.splat.dal.bo.som.SimulationContext;
+import org.splat.dal.bo.som.SimulationContextType;
 import org.splat.dal.bo.som.Study;
 import org.splat.dal.bo.som.UsedByRelation;
 import org.splat.dal.bo.som.UsesRelation;
@@ -39,8 +42,10 @@ import org.splat.kernel.MultiplyDefinedException;
 import org.splat.kernel.NotApplicableException;
 import org.splat.log.AppLogger;
 import org.splat.service.DocumentTypeService;
+import org.splat.service.KnowledgeElementTypeService;
 import org.splat.service.PublicationService;
 import org.splat.service.ScenarioService;
+import org.splat.service.SimulationContextService;
 import org.splat.service.StepService;
 import org.splat.service.dto.DocumentDTO;
 import org.splat.service.dto.FileDTO;
@@ -53,11 +58,12 @@ import org.springframework.beans.factory.annotation.Qualifier;
 import org.springframework.orm.hibernate3.HibernateTemplate;
 import org.testng.Assert;
 import org.testng.annotations.Test;
+import org.testng.reporters.Files;
 
 import test.splat.common.BaseTest;
 
 /**
- * Test class for KnowledgeElementDAO.
+ * Test class for ScenarioService.
  * 
  * @author <a href="mailto:roman.kozlov@opencascade.com">Roman Kozlov (RKV)</a>
  * 
@@ -105,6 +111,13 @@ public class TestScenarioService extends BaseTest {
        @Qualifier("stepService")
        private transient StepService _stepService;
 
+       /**
+        * The SimulationContextService. Later injected by Spring.
+        */
+       @Autowired
+       @Qualifier("simulationContextService")
+       private transient SimulationContextService _simulationContextService;
+
        /**
         * The ProjectSettingsService. Later injected by Spring.
         */
@@ -119,6 +132,13 @@ public class TestScenarioService extends BaseTest {
        @Qualifier("documentTypeService")
        private transient DocumentTypeService _documentTypeService;
 
+       /**
+        * The KnowledgeElementTypeService. Later injected by Spring.
+        */
+       @Autowired
+       @Qualifier("knowledgeElementTypeService")
+       private transient KnowledgeElementTypeService _knowledgeElementTypeService;
+
        /**
         * Test of getting a scenario content for building siman-salome.conf.<BR>
         * <B>Description :</B> <BR>
@@ -157,7 +177,7 @@ public class TestScenarioService extends BaseTest {
                        SQLException {
                LOG.debug(">>>>> BEGIN testGetScenarioInfo()");
                startNestedTransaction();
-               
+
                long scenarioId = createScenario();
                // Call DAO's create method for a good transient knowledge element.
                List<StepDTO> steps = _scenarioService.getScenarioInfo(scenarioId);
@@ -274,7 +294,9 @@ public class TestScenarioService extends BaseTest {
         * <li>presentation of the previous version is removed</li>
         * <li>uses relations are copied correctly</li>
         * <li>files are moved correctly</li>
+        * <li>formats of files are new if they are according to the document's type on the study step</li>
         * <li>new documents are created for new data</li>
+        * <li>new documents have correctly generated names</li>
         * <li>uses relations are created correctly</li>
         * <li>files are moved correctly</li>
         * </ul>
@@ -318,7 +340,7 @@ public class TestScenarioService extends BaseTest {
                        SQLException, MismatchException, NotApplicableException {
                LOG.debug(">>>>> BEGIN testCheckin()");
                startNestedTransaction();
-               
+
                _projectSettings.getAllSteps().clear(); // Clear config to be able to load it again
                _projectSettings.configure(ClassLoader
                                .getSystemResource("test/som.xml").getPath());
@@ -328,16 +350,42 @@ public class TestScenarioService extends BaseTest {
                User user = aScen.getAuthor();
                long userId = user.getIndex();
 
+               
                // ////////////////////////////////////////////////////////
-               // Call checkin method for good prepared transient data.
+               // Call checkin method for empty list of modules.
 
                // Simulate checkout
                List<StepDTO> steps = _scenarioService.getScenarioInfo(scenarioId);
                _scenarioService.checkout(aScen, user);
+               _scenarioDAO.flush();
+               // Check that scenario is no more marked as checked out
+               aScen = _scenarioDAO.get(scenarioId);
+               Assert.assertTrue(aScen.isCheckedout(),
+                               "Scenario is not marked as checked out after checkout.");
 
                // Prepare test data for checkin
                // Checkin only two first steps (geom and mesh)
                List<StepDTO> stepsToCheckin = new ArrayList<StepDTO>();
+               // Do test checkin
+               _scenarioService.checkin(scenarioId, userId, stepsToCheckin);
+
+               _scenarioDAO.flush();
+               // Check that scenario is no more marked as checked out
+               aScen = _scenarioDAO.get(scenarioId);
+               Assert.assertFalse(aScen.isCheckedout(),
+                               "Scenario is still marked as checked out after checkin.");
+               
+               
+               
+               // ////////////////////////////////////////////////////////
+               // Call checkin method for good prepared transient data.
+
+               // Simulate checkout
+               steps = _scenarioService.getScenarioInfo(scenarioId);
+               _scenarioService.checkout(aScen, user);
+
+               // Prepare test data for checkin
+               // Checkin only two first steps (geom and mesh)
                for (StepDTO step : steps) {
                        // Prepare GEOM: checkin actual brep
                        StepDTO stepToCheckin = createDocDTOForModule(null, "GEOM", "brep",
@@ -348,6 +396,7 @@ public class TestScenarioService extends BaseTest {
                // Do test checkin
                _scenarioService.checkin(scenarioId, userId, stepsToCheckin);
 
+               _scenarioDAO.flush();
                // Check that scenario is no more marked as checked out
                aScen = _scenarioDAO.get(scenarioId);
                Assert.assertFalse(aScen.isCheckedout(),
@@ -359,6 +408,7 @@ public class TestScenarioService extends BaseTest {
                                if ((docDTO.getId() != 0) && (docDTO.getId() != null)) {
                                        boolean found = false;
                                        Document prevDoc = null;
+                                       Document curDoc = null;
                                        Publication newPub = null;
                                        for (Publication pub : aScen.getDocums()) {
                                                prevDoc = pub.value().getPreviousVersion();
@@ -369,75 +419,130 @@ public class TestScenarioService extends BaseTest {
                                                                break;
                                                        }
                                                }
+                                               if (pub.value().getIndex() == docDTO.getId()) {
+                                                       // Document version was not changed, old document is still published
+                                                       curDoc = pub.value();
+                                                       break;
+                                               }
                                        }
-                                       Assert.assertTrue(found,
-                                                       "New version of the existing checked in document \""
+                                       Assert.assertTrue(found || (curDoc != null),
+                                                       "New version or new attached file of the existing checked in document \""
                                                                        + docDTO.getTitle() + "\" (id="
                                                                        + docDTO.getId()
                                                                        + ") is not found in the scenario.");
-                                       // Check that presentation of the previous version is removed
-                                       Assert.assertFalse(aScen.publishes(prevDoc));
-                                       checkFiles(docDTO, newPub);
-                                       // Check that uses relations are copied correctly
-
-                                       // 1. Get all uses relations of the previous document version
-                                       for (Relation rel : prevDoc
-                                                       .getRelations(UsesRelation.class)) {
-                                               Document used = ((UsesRelation) rel).getTo();
-                                               // 2.1. Get the latest version of the document published in this scenario
-                                               Publication toBeUsed = aScen.getPublication(used);
-                                               if (toBeUsed == null) {
-                                                       // Find the latest published version
-                                                       for (Publication lastPub : aScen.getDocums()) {
-                                                               if ((lastPub.value().getPreviousVersion() != null)
-                                                                               && (lastPub.value()
-                                                                                               .getPreviousVersion()
-                                                                                               .getIndex() == used.getIndex())) {
-                                                                       toBeUsed = lastPub;
-                                                                       break;
+                                       // If previous version is found then the format must be the same
+                                       String newFormat = docDTO.getFiles().get(0).getPath()
+                                                       .substring(
+                                                                       docDTO.getFiles().get(0).getPath()
+                                                                                       .lastIndexOf('.') + 1);
+                                       if (found) {
+                                               Assert.assertEquals(prevDoc.getFormat(), newFormat,
+                                                               "Formats of versions must be same");
+                                               Assert.assertFalse(aScen.publishes(prevDoc));
+                                               // Check that presentation of the previous version is removed
+                                               checkFiles(docDTO, newPub);
+                                               
+                                               // Formats of files are new if they are according to the document's type on the study step
+                                               if ("py".equals(prevDoc.getFormat())
+                                                               && "geometry".equals(prevDoc.getType().getName())) {
+                                                       Assert.assertEquals(newPub.value().getFormat(), "brep");
+                                                       Assert.assertEquals(newPub.getSourceFile().getFormat(),
+                                                                       "brep");
+                                                       Assert.assertEquals(newPub.getSourceFile()
+                                                                       .getRelativePath().substring(
+                                                                                       newPub.getSourceFile()
+                                                                                                       .getRelativePath().lastIndexOf(
+                                                                                                                       '.') + 1), "brep");
+                                               }
+
+                                               // Check that uses relations are copied correctly
+
+                                               // 1. Get all uses relations of the previous document version
+                                               for (Relation rel : prevDoc
+                                                               .getRelations(UsesRelation.class)) {
+                                                       Document used = ((UsesRelation) rel).getTo();
+                                                       // 2.1. Get the latest version of the document published in this scenario
+                                                       Publication toBeUsed = aScen.getPublication(used);
+                                                       if (toBeUsed == null) {
+                                                               // Find the latest published version
+                                                               for (Publication lastPub : aScen.getDocums()) {
+                                                                       if ((lastPub.value().getPreviousVersion() != null)
+                                                                                       && (lastPub.value()
+                                                                                                       .getPreviousVersion()
+                                                                                                       .getIndex() == used.getIndex())) {
+                                                                               toBeUsed = lastPub;
+                                                                               break;
+                                                                       }
                                                                }
                                                        }
+                                                       if ((toBeUsed != null) && (!toBeUsed.isOutdated())) {
+                                                               // 2.2. For each used document check that its latest not outdated version
+                                                               // is used by the new checked in document version.
+                                                               checkUsesRelation(newPub, toBeUsed);
+                                                       }
                                                }
-                                               if ((toBeUsed != null) && (!toBeUsed.isOutdated())) {
-                                                       // 2.2. For each used document check that its latest not outdated version
-                                                       // is used by the new checked in document version.
-                                                       checkUsesRelation(newPub, toBeUsed);
-                                               }
-                                       }
-                                       // 1. Get all usedBy relations of the previous document version
-                                       for (Relation rel : prevDoc
-                                                       .getRelations(UsedByRelation.class)) {
-                                               Document using = ((UsedByRelation) rel).getTo();
-                                               // Check that not checked in dependent documents became outdated
-                                               Publication usingPub = aScen.getPublication(using);
-                                               if (usingPub != null) { // if the document using the old version is still published
-                                                       Assert.assertTrue(usingPub.isOutdated(),
-                                                                       "Not checked in dependent document "
-                                                                                       + using.getTitle() + " ("
-                                                                                       + using.getType().getName()
-                                                                                       + ") must become outdated.");
-                                                       caseFound = true;
+                                               // 1. Get all usedBy relations of the previous document version
+                                               for (Relation rel : prevDoc
+                                                               .getRelations(UsedByRelation.class)) {
+                                                       Document using = ((UsedByRelation) rel).getTo();
+                                                       // Check that not checked in dependent documents became outdated
+                                                       Publication usingPub = aScen.getPublication(using);
+                                                       if (usingPub != null) { // if the document using the old version is still published
+                                                               Assert.assertTrue(usingPub.isOutdated(),
+                                                                               "Not checked in dependent document "
+                                                                                               + using.getTitle() + " ("
+                                                                                               + using.getType().getName()
+                                                                                               + ") must become outdated.");
+                                                               caseFound = true;
+                                                       }
                                                }
+                                       } else {
+                                               // Otherwise the new file format must differ from the previous one
+                                               // and the new file must be attached to the same document
+                                               org.splat.dal.bo.som.File attFile = curDoc
+                                                               .getAttachedFile(newFormat);
+                                               Assert.assertNotNull(attFile, "File "
+                                                               + docDTO.getFiles().get(0).getPath()
+                                                               + " must be attached to the document "
+                                                               + docDTO.getTitle() + "#" + docDTO.getId());
+                                               Assert.assertTrue(attFile.asFile().exists(), "File "
+                                                               + docDTO.getFiles().get(0).getPath()
+                                                               + " attached to the document "
+                                                               + docDTO.getTitle() + "#" + docDTO.getId() + " doesn't exist");
                                        }
 
+
                                } else {
                                        // Check that new documents are created for new data
                                        boolean found = false;
                                        Publication newPub = null;
                                        for (Publication pub : aScen.getDocums()) {
                                                if (pub.value().getPreviousVersion() == null) {
-                                                       found = (docDTO.getTitle().equals(pub.value()
-                                                                       .getTitle()));
+                                                       found = (pub.value().getTitle().startsWith(pub
+                                                                       .value().getType().getName()));
                                                        if (found) { // Found next published version of the checked in document
-                                                               newPub = pub;
-                                                               break;
+                                                               String fcontent = Files.readFile(pub
+                                                                               .getSourceFile().asFile());
+                                                               found = fcontent.contains(docDTO.getTitle());
+                                                               if (found) {
+                                                                       LOG
+                                                                                       .debug("Found new document with generated title: "
+                                                                                                       + pub.value().getTitle());
+                                                                       newPub = pub;
+                                                                       break;
+                                                               }
                                                        }
                                                }
                                        }
                                        Assert.assertTrue(found,
                                                        "New document is not created for checked in document \""
                                                                        + docDTO.getTitle() + "\".");
+
                                        // Check that uses relations are created correctly
+                                       Assert.assertTrue(newPub.value().getTitle().startsWith(
+                                                       newPub.value().getType().getName() + "_"),
+                                                       "Document title newPub.value().getTitle() must start with "
+                                                                       + newPub.value().getType().getName() + "_");
 
                                        // 1. Find the document type used by this document type
                                        Set<DocumentType> usedTypes = newPub.value().getType()
@@ -471,7 +576,11 @@ public class TestScenarioService extends BaseTest {
                        LOG.debug("Expected exception is thrown: "
                                        + e.getClass().getSimpleName() + ": " + e.getMessage());
                }
-               
+
+               // Test checkin with empty list of steps
+               stepsToCheckin.clear();
+               _scenarioService.checkin(scenarioId, userId, stepsToCheckin);
+
                rollbackNestedTransaction();
                LOG.debug(">>>>> END testCheckin()");
        }
@@ -521,7 +630,7 @@ public class TestScenarioService extends BaseTest {
                        String format = fileDTO.getPath().substring(
                                        fileDTO.getPath().lastIndexOf('.') + 1);
                }
-               // TODO:Check file by its internal content
+               // TODO: Check file by its internal content
                Assert.assertTrue(newPub.getSourceFile().exists(), "File "
                                + newPub.getSourceFile().asFile().getAbsolutePath()
                                + " for the document " + docDTO.getTitle()
@@ -563,7 +672,9 @@ public class TestScenarioService extends BaseTest {
                                        DocumentDTO docToCheckin = stepToCheckin.addDoc(
                                                        doc.getId(), doc.getTitle());
                                        for (FileDTO file : doc.getFiles()) {
-                                               if (file.getPath().endsWith(format)) {
+                                               if (file.getPath().endsWith(format)
+                                                               || (file.getPath().endsWith("py") && format
+                                                                               .equals("brep"))) {
                                                        // Create a file in the download directory
                                                        docToCheckin.addFile(createDownloadedFile(userId,
                                                                        doc.getTitle() + "_result", format));
@@ -595,10 +706,27 @@ public class TestScenarioService extends BaseTest {
        private FileDTO createDownloadedFile(final long userId, final String name,
                        final String format) throws IOException {
                // Create a file in the download directory
-               String filePath = getDownloadPath(userId) + name + "." + format;
+               return createDownloadedFile(userId, name + "." + format);
+       }
+
+       /**
+        * Create a file in the user's repository downloads directory.
+        * 
+        * @param userId
+        *            user id
+        * @param fname
+        *            file name
+        * @return created file DTO
+        * @throws IOException
+        *             if file creation failed
+        */
+       private FileDTO createDownloadedFile(final long userId, final String fname)
+                       throws IOException {
+               // Create a file in the download directory
+               String filePath = getDownloadPath(userId) + fname;
                FileWriter fw = new FileWriter(filePath);
-               fw.write("Simulation of " + name + "." + format
-                               + " file for checkin at " + new Date());
+               fw.write("Simulation of " + fname + " file for checkin at "
+                               + new Date());
                fw.close();
                return new FileDTO(filePath);
        }
@@ -701,8 +829,9 @@ public class TestScenarioService extends BaseTest {
                                if (step.getNumber() > 3) {
                                        dprop.setFormat("med");
                                } else {
-                                       dprop.setFormat("brep");
+                                       dprop.setFormat("py");
                                }
+                               dprop.setLocalPath(dprop.getName() + "." + dprop.getFormat());
                                Publication pub = createDoc(aScenario, aScStep, dprop, "med",
                                                false);
                                if (usedPub != null) {
@@ -714,8 +843,8 @@ public class TestScenarioService extends BaseTest {
                                usedPub = pub;
 
                                // Create another document with outdated publication
-                               dprop.setName("document" + i++).setType(dtype)
-                                               .setFormat("brep");
+                               dprop.setName("document" + i++).setType(dtype).setFormat("py");
+                               dprop.setLocalPath(dprop.getName() + "." + dprop.getFormat());
                                createDoc(aScenario, aScStep, dprop, "med", true);
 
                        }
@@ -816,6 +945,8 @@ public class TestScenarioService extends BaseTest {
                // document<i>: document type[0] - first type used on the step
                // <source-file>.brep
                // <attached-file>.med
+               createDownloadedFile(aScenario.getAuthor().getIndex(), dprop
+                               .getLocalPath());
                Publication pub = _stepService.createDocument(aScStep, dprop);
                Assert.assertNotNull(pub.getOwner(),
                                "The publication must be attached to the scenario.");
@@ -830,9 +961,121 @@ public class TestScenarioService extends BaseTest {
                ht.saveOrUpdate(pub);
 
                // Attach a file
+               createDownloadedFile(aScenario.getAuthor().getIndex(), dprop
+                               .getLocalPath().substring(0,
+                                               dprop.getLocalPath().lastIndexOf(".") - 1),
+                               attachedFileExt);
                ht.save(pub.value());
                ht.saveOrUpdate(_publicationService.attach(pub, attachedFileExt));
 
                return pub;
        }
+
+       /**
+        * Test check-in scenario operation to be performed after SALOME session.<BR>
+        * <B>Description :</B> <BR>
+        * <i>Create a scenario and try to check-in it with some simulated SALOME results data.<BR>
+        * After check-in verify following points:
+        * <ul>
+        * <li>scenario is no more marked as checked out</li>
+        * <li>new document versions are created for checked in documents</li>
+        * <li>presentation of the previous version is removed</li>
+        * <li>uses relations are copied correctly</li>
+        * <li>files are moved correctly</li>
+        * <li>new documents are created for new data</li>
+        * <li>uses relations are created correctly</li>
+        * <li>files are moved correctly</li>
+        * </ul>
+        * </i><BR>
+        * <B>Action : </B><BR>
+        * <i>1. call the method for an existing scenario id.</i><BR>
+        * <i>2. call the method for a not existing scenario id.</i><BR>
+        * <B>Test data : </B><BR>
+        * <i>no input parameters</i><BR>
+        * <i>no input parameters</i><BR>
+        * 
+        * <B>Outcome results:</B><BR>
+        * <i>
+        * <ul>
+        * <li>New version of existing documents must be created and new documents must be imported for documents with zero id. Correct
+        * relations must be created.<BR>
+        * </li>
+        * <li>Exception is thrown<BR>
+        * </li>
+        * </ul>
+        * </i>
+        * 
+        * @throws InvalidPropertyException
+        *             if an invalid property is used when creating objects
+        * @throws MultiplyDefinedException
+        *             when trying to create an object with already existing id
+        * @throws MissedPropertyException
+        *             if a mandatory property is not defined for an object to be created
+        * @throws IOException
+        *             if scenario creation is failed
+        * @throws SQLException
+        *             if scenario creation is failed
+        * @throws NotApplicableException
+        *             if checkin failed
+        * @throws MismatchException
+        *             if checkin failed
+        */
+       @Test(groups = { "study", "sevice", "functional", "business" })
+       public void testCreateStudy() throws InvalidPropertyException,
+                       MissedPropertyException, MultiplyDefinedException, IOException,
+                       SQLException, MismatchException, NotApplicableException {
+               LOG.debug(">>>>> BEGIN testCreateStudy()");
+               startNestedTransaction();
+
+               Database.getInstance().reset();
+               _projectSettings.getAllSteps().clear(); // Clear config to be able to load it again
+               _projectSettings.configure(ClassLoader
+                               .getSystemResource("test/som.xml").getPath());
+
+               // Create a test user
+               User.Properties uprop = new User.Properties();
+               uprop.setUsername("TST_Username").setName("TST_SimanUnitTestsUser")
+                               .setFirstName("TST_FirstName").setDisplayName("TST_test.user")
+                               .addRole("TST_user").setMailAddress(
+                                               "noreply@salome-platform.org");
+               uprop.disableCheck();
+               User anAuthor = new User(uprop);
+
+               getHibernateTemplate().saveOrUpdate(anAuthor);
+               KnowledgeElementType ucase = _knowledgeElementTypeService
+                               .selectType("usecase");
+               Assert.assertNotNull(ucase,
+                               "Knowledge type 'usecase' must be created in the database.");
+               SimulationContextType prodtype = _simulationContextService
+                               .selectType("product");
+               Assert
+                               .assertNotNull(prodtype,
+                                               "Simulation context type 'product' must be created in the database.");
+
+               // Create admin
+               uprop.clear();
+               uprop.setUsername("TST_Admin").setName("TST_SimanUnitTestsAdmin")
+                               .setFirstName("TST_AdminFirstName").setDisplayName(
+                                               "TST_test.admin").addRole("TST_user,sysadmin")
+                               .setMailAddress("noreply@salome-platform.org");
+               uprop.disableCheck();
+
+               getHibernateTemplate().saveOrUpdate(new User(uprop));
+               getHibernateTemplate().flush();
+
+               Study.Properties sprop = new Study.Properties();
+               sprop.setTitle("Test study creation").setManager(anAuthor);
+               Scenario.Properties oprop = new Scenario.Properties();
+               oprop.setTitle("Test scenario for the created study");
+
+               // Addition of the entered project context
+               SimulationContext.Properties cprop = new SimulationContext.Properties();
+               // Input of new project context
+               cprop.setType(_simulationContextService.selectType("product"))
+                               .setValue("Test Simulation Context: Product");
+               Study study = _scenarioService.createStudy(sprop, oprop, cprop);
+
+               rollbackNestedTransaction();
+               LOG.debug(">>>>> END testCreateStudy()");
+       }
 }