*****************************************************************************/
package test.splat.service;
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.FileWriter;
import java.io.IOException;
+import java.sql.SQLException;
+import java.util.ArrayList;
import java.util.Date;
+import java.util.HashMap;
import java.util.List;
+import java.util.Map;
+import java.util.Set;
+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.KnowledgeElement;
+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;
+import org.splat.dal.bo.som.Document.Properties;
+import org.splat.dal.dao.som.Database;
+import org.splat.dal.dao.som.ScenarioDAO;
import org.splat.kernel.InvalidPropertyException;
+import org.splat.kernel.MismatchException;
import org.splat.kernel.MissedPropertyException;
import org.splat.kernel.MultiplyDefinedException;
+import org.splat.kernel.NotApplicableException;
import org.splat.log.AppLogger;
-import org.splat.service.DocumentService;
import org.splat.service.DocumentTypeService;
-import org.splat.service.ProjectElementService;
+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;
import org.splat.service.dto.StepDTO;
-import org.splat.som.Step;
+import org.splat.service.technical.ProjectSettingsService;
+import org.splat.service.technical.RepositoryService;
+import org.splat.service.technical.ProjectSettingsService.Step;
import org.springframework.beans.factory.annotation.Autowired;
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>
*
private transient ScenarioService _scenarioService;
/**
- * The DocumentService. Later injected by Spring.
+ * The RepositoryService. Later injected by Spring.
*/
@Autowired
- @Qualifier("documentService")
- private transient DocumentService _documentService;
+ @Qualifier("repositoryService")
+ private transient RepositoryService _repositoryService;
+
+ /**
+ * The Scenario DAO. Later injected by Spring.
+ */
+ @Autowired
+ @Qualifier("scenarioDAO")
+ private transient ScenarioDAO _scenarioDAO;
/**
* The PublicationService. Later injected by Spring.
private transient StepService _stepService;
/**
- * The ProjectElementService. Later injected by Spring.
+ * The SimulationContextService. Later injected by Spring.
*/
@Autowired
- @Qualifier("projectElementService")
- private transient ProjectElementService _projectElementService;
+ @Qualifier("simulationContextService")
+ private transient SimulationContextService _simulationContextService;
+
+ /**
+ * The ProjectSettingsService. Later injected by Spring.
+ */
+ @Autowired
+ @Qualifier("projectSettings")
+ private transient ProjectSettingsService _projectSettings;
/**
* The DocumentTypeService. Later injected by Spring.
@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>
- * <i>Create a scenario try to get an info for it.</i><BR>
+ * <i>Create a scenario and try to get an info for it.</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>
* 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
*/
- @Test
+ @Test(groups = { "checkout", "sevice", "functional", "business" })
public void testGetScenarioInfo() throws InvalidPropertyException,
- MissedPropertyException, MultiplyDefinedException, IOException {
+ MissedPropertyException, MultiplyDefinedException, IOException,
+ 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);
Assert.assertNotNull(steps, "List of steps must not be null.");
Assert.assertTrue(steps.size() > 0, "No steps are read.");
+ List<Step> projSteps = _projectSettings.getStepsOf(Scenario.class);
+ Assert.assertEquals(steps.size(), projSteps.size(),
+ "Not all steps are listed.");
+ int docIndex = 0;
+ for (StepDTO step : steps) {
+ LOG.debug("check the step " + step.getNumber() + ":\n" + step);
+ Assert.assertNotNull(step, "Step DTO must not be null.");
+ Assert.assertNotNull(step.getKey(), "Step name must not be null.");
+ Assert.assertFalse(step.getKey().isEmpty(),
+ "Step name must not empty.");
+ Assert.assertTrue(step.getNumber() > 0,
+ "Step number must be positive integer.");
+ Assert.assertNotNull(step.getDocs(),
+ "Step documents list must not be null.");
+
+ Step aProjStep = null;
+ for (Step projStep : projSteps) {
+ if (projStep.getNumber() == step.getNumber()) {
+ aProjStep = projStep;
+ break;
+ }
+ }
+
+ List<DocumentType> dtypes = _documentTypeService
+ .selectTypesOf(aProjStep);
+ for (DocumentType dtype : dtypes) {
+ Assert.assertTrue(step.getDocs().size() > 0,
+ "Step documents list must not be empty.");
+ String docName = "document" + docIndex;
+ for (DocumentDTO doc : step.getDocs()) {
+ if (docName.equals(doc.getTitle())) {
+ Assert.assertTrue(doc.getId() > 0,
+ "Document id must be positive integer.");
+ Assert.assertEquals(doc.getTitle(), docName);
+ Assert.assertNotNull(doc.getFiles(),
+ "Document files list must not be null.");
+ Assert
+ .assertTrue(doc.getFiles().size() > 1,
+ "Document must have more then 1 attached file.");
+
+ for (FileDTO file : doc.getFiles()) {
+ Assert.assertNotNull(file.getPath(),
+ "File path must not be null.");
+ Assert.assertFalse(file.getPath().isEmpty(),
+ "File path must not be empty.");
+ /*
+ * <mappings> <document type="geometry"> <import format="brep"/> <!-- Result Shape --> </document> <document
+ * type="model"> <import format="med"/> <!-- Result mesh without input parameters --> </document> <document
+ * type="loads"> <import format="c3m"/> <!-- Input data created interactively --> </document> <document
+ * type="results"> <import format="med"/> <!-- Calculation results source file --> </document> </mappings>
+ */
+ // Check state and processing instruction
+ String fileFormat = file.getPath().substring(
+ file.getPath().lastIndexOf('.') + 1);
+ /*
+ * if (_projectSettings.doImport(dtype.getName(), fileFormat)) { Assert.assertTrue(file.isResult(), "The file
+ * must be a result file."); } else { Assert.assertFalse(file.isResult(), "The file must be a source file."); }
+ */if ((docIndex % 2) == 0) { // New
+ Assert.assertEquals(file.getState(), 'Y',
+ "File state must be actual ('Y').");
+ if (_projectSettings.doImport(dtype.getName(),
+ fileFormat)) {
+ Assert.assertEquals(file.getProcessing(),
+ "file-import",
+ "File must be imported.");
+ } else {
+ Assert.assertEquals(file.getProcessing(),
+ "file-download",
+ "File must be downloaded.");
+ }
+ } else { // Outdated
+ Assert.assertEquals(file.getState(), 'O',
+ "File state must be outdated ('O').");
+ Assert
+ .assertEquals(file.getProcessing(),
+ "file-download",
+ "Outdated document should not be imported but downloaded.");
+ }
+ }
+ }
+ }
+ docIndex++;
+ }
+ }
+
// Call DAO's get method for a not existing id.
try {
steps = _scenarioService.getScenarioInfo(-1L);
LOG.debug("Expected exception is thrown: "
+ e.getClass().getSimpleName() + ": " + e.getMessage());
}
+ rollbackNestedTransaction();
LOG.debug(">>>>> END testGetScenarioInfo()");
}
/**
- * Create a transient KnowledgeElement for tests.
+ * 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>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>
+ * </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>
*
- * @return a transient KnowledgeElement
+ * @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 = { "checkin", "sevice", "functional", "business" })
+ public void testCheckin() throws InvalidPropertyException,
+ MissedPropertyException, MultiplyDefinedException, IOException,
+ 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());
+ getHibernateTemplate().flush();
+ long scenarioId = createScenario();
+ Scenario aScen = _scenarioDAO.get(scenarioId);
+ User user = aScen.getAuthor();
+ long userId = user.getIndex();
+
+
+ // ////////////////////////////////////////////////////////
+ // 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",
+ userId, step, stepsToCheckin);
+ createDocDTOForModule(stepToCheckin, "SMESH", "med", userId, step,
+ stepsToCheckin);
+ }
+ // 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.");
+ // Check that new document versions are created for checked in documents
+ for (StepDTO step : stepsToCheckin) {
+ for (DocumentDTO docDTO : step.getDocs()) {
+ 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();
+ if (prevDoc != null) {
+ found = (prevDoc.getIndex() == docDTO.getId());
+ if (found) { // Found next published version of the checked in document
+ newPub = pub;
+ break;
+ }
+ }
+ if (pub.value().getIndex() == docDTO.getId()) {
+ // Document version was not changed, old document is still published
+ curDoc = pub.value();
+ break;
+ }
+ }
+ 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.");
+ // 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);
+ }
+ }
+ // 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.");
+ }
+ }
+ } 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");
+ LOG.debug("Source format: " + curDoc.getFormat() + ", new format: " + newFormat);
+ }
+
+
+ } 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 = (pub.value().getTitle().startsWith(pub
+ .value().getType().getName()));
+ if (found) { // Found next published version of the checked in document
+ 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()
+ .getDefaultUses();
+ // 2. Find documents of used types in the current study step and previous study steps
+ for (Publication pub : aScen.getDocums()) {
+ if ((pub.getStep().getNumber() <= step.getNumber())
+ && (!pub.isOutdated())
+ && usedTypes.contains(pub.value().getType())) {
+ // 3. Check that there is uses relation to the found document
+ // if it is not outdated.
+ checkUsesRelation(newPub, pub);
+ }
+ }
+
+ // Check that files are moved correctly
+ checkFiles(docDTO, newPub);
+ }
+ }
+ }
+
+ // ///////////////////////////////////////////////////////////
+ // Call checkin method for a not existing id.
+ try {
+ _scenarioService.checkin(-1, userId, stepsToCheckin);
+ Assert
+ .fail("Check in for scenario with not existing id must be failed.");
+ } catch (Exception e) {
+ 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()");
+ }
+
+ /**
+ * Check if there is uses relation from the newPub to pub.
+ *
+ * @param newPub
+ * the new publication
+ * @param pub
+ * the publication to be used
+ */
+ private void checkUsesRelation(final Publication newPub,
+ final Publication pub) {
+ boolean uses = false;
+ boolean usesExist = false;
+ for (Publication usesPub : newPub.getRelations(UsesRelation.class)) {
+ usesExist = true;
+ uses = (usesPub.equals(pub));
+ if (uses) {
+ break;
+ }
+ }
+ Assert.assertTrue(usesExist && uses, "The created document "
+ + newPub.value().getTitle() + "("
+ + newPub.value().getType().getName() + ")"
+ + " has no uses relation to the document "
+ + pub.value().getTitle() + "("
+ + pub.value().getType().getName() + ")");
+ }
+
+ /**
+ * Check that files are moved correctly.
+ *
+ * @param docDTO
+ * checked in document DTO
+ * @param newPub
+ * the created document publication
+ */
+ private void checkFiles(final DocumentDTO docDTO, final Publication newPub) {
+ // Check that original files are deleted
+ for (int j = 0; j < docDTO.getFiles().size(); j++) {
+ FileDTO fileDTO = docDTO.getFiles().get(j);
+ Assert.assertFalse(new File(fileDTO.getPath()).exists(), "File"
+ + fileDTO.getPath()
+ + " was not removed from downloads directory.");
+ String format = fileDTO.getPath().substring(
+ fileDTO.getPath().lastIndexOf('.') + 1);
+ }
+ // TODO: Check file by its internal content
+ Assert.assertTrue(newPub.getSourceFile().exists(), "File "
+ + newPub.getSourceFile().asFile().getAbsolutePath()
+ + " for the document " + docDTO.getTitle()
+ + " was not created.");
+ }
+
+ /**
+ * Prepare a document with a file for check-in.
+ *
+ * @param stepTo
+ * step DTO with data for check-in
+ * @param module
+ * SALOME module name
+ * @param format
+ * file extension
+ * @param userId
+ * download directory
+ * @param stepFrom
+ * checked out stepDTO
+ * @param stepsToCheckin
+ * DTO for check-in
+ * @throws IOException
+ * if file creation failed
+ * @return step DTO with data prepared for check-in (stepTo or new if stepTo is null)
+ */
+ private StepDTO createDocDTOForModule(final StepDTO stepTo,
+ final String module, final String format, final long userId,
+ final StepDTO stepFrom, final List<StepDTO> stepsToCheckin)
+ throws IOException {
+ StepDTO stepToCheckin = stepTo;
+ if (stepToCheckin == null) {
+ stepToCheckin = new StepDTO();
+ }
+ if (module.equals(stepFrom.getModule())) {
+ stepsToCheckin.add(stepToCheckin);
+ stepToCheckin.setNumber(stepFrom.getNumber());
+ for (DocumentDTO doc : stepFrom.getDocs()) {
+ if (doc.getFiles().get(0).getState() != 'O') {
+ DocumentDTO docToCheckin = stepToCheckin.addDoc(
+ doc.getId(), doc.getTitle());
+ for (FileDTO file : doc.getFiles()) {
+ if (file.getPath().endsWith(format)
+ || (file.getPath().endsWith("py") && (format
+ .equals("brep") || format
+ .equals("med")))) {
+ // Create a file in the download directory
+ docToCheckin.addFile(createDownloadedFile(userId,
+ doc.getTitle() + "_result", format));
+ }
+ }
+ }
+ }
+ // Prepare new data
+ stepToCheckin.addDoc(0, "newdoc" + stepFrom.getNumber()).addFile(
+ createDownloadedFile(userId, "newdoc"
+ + stepFrom.getNumber(), "brep"));
+ }
+ return stepToCheckin;
+ }
+
+ /**
+ * Create a file in the user's repository downloads directory.
+ *
+ * @param userId
+ * user id
+ * @param name
+ * file name
+ * @param format
+ * file extension
+ * @return created file DTO
+ * @throws IOException
+ * if file creation failed
+ */
+ private FileDTO createDownloadedFile(final long userId, final String name,
+ final String format) throws IOException {
+ // Create a file in the download directory
+ 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 " + fname + " file for checkin at "
+ + new Date());
+ fw.close();
+ return new FileDTO(filePath);
+ }
+
+ /**
+ * Get path to the user's downloads directory. The directory is created if it is not exist yet.
+ *
+ * @param userId
+ * user id
+ * @return absolute path to downloads directory followed by slash
+ */
+ private String getDownloadPath(final long userId) {
+ // Prepare download directory
+ File tmpDir = _repositoryService.getDownloadDirectory(userId);
+ if (!tmpDir.exists()) {
+ Assert.assertTrue(tmpDir.mkdir(),
+ "Can't create temporary directory: "
+ + tmpDir.getAbsolutePath());
+ }
+
+ return tmpDir.getAbsolutePath() + "/";
+ }
+
+ /**
+ * Create a persistent scenario for tests.
+ *
+ * @return a persistent scenario
* @throws InvalidPropertyException
* if an invalid property is used when creating objects
* @throws MultiplyDefinedException
* if a mandatory property is not defined for an object to be created
* @throws IOException
* if document creation is failed
+ * @throws SQLException
+ * if project settings loading is failed
*/
private long createScenario() throws InvalidPropertyException,
- MissedPropertyException, MultiplyDefinedException, IOException {
+ MissedPropertyException, MultiplyDefinedException, IOException,
+ SQLException {
// Create a scenario for tests
HibernateTemplate ht = getHibernateTemplate();
+ Database.getInstance().reset();
+ _projectSettings.getAllSteps().clear(); // Clear config to be able to load it again
+ // Load workflow customization
+ try {
+ _projectSettings.configure(ClassLoader.getSystemResource(
+ "test/som.xml").getPath());
+ } catch (FileNotFoundException e) {
+ Assert.fail("Can't find som.xml: ", e);
+ }
+ List<Step> steps = _projectSettings.getStepsOf(Scenario.class);
+ Assert.assertTrue(steps.size() > 0, "No steps are created.");
+
// Create a test user
User.Properties uprop = new User.Properties();
uprop.setUsername("TST_Username").setName("TST_SimanUnitTestsUser")
"noreply@salome-platform.org");
uprop.disableCheck();
User anAuthor = new User(uprop);
- ht.update(anAuthor);
+ ht.saveOrUpdate(anAuthor);
// Create a test study
Study.Properties stprops = new Study.Properties().setReference(
// Create a test scenario
Scenario.Properties sprops = new Scenario.Properties().setTitle(
- "TST_Study").setManager(anAuthor).setOwnerStudy(aStudy);
+ "TST_Scenario").setManager(anAuthor).setOwnerStudy(aStudy);
Scenario aScenario = new Scenario(sprops);
aStudy.getScenariiList().add(aScenario);
ht.saveOrUpdate(anAuthor);
- ht.update(aStudy);
+ ht.saveOrUpdate(aStudy);
ht.saveOrUpdate(aScenario);
+ // Create documents for each scenario step
Document.Properties dprop = new Document.Properties().setAuthor(
anAuthor).setDate(new Date());
- Step[] steps = _projectElementService.getSteps(aScenario);
- Assert.assertTrue(steps.length > 0, "No steps are created.");
int i = 0;
+ Publication usedPub = null;
+ Map<Long, Long> usedMap = new HashMap<Long, Long>();
for (Step step : steps) {
- List<DocumentType> dtypes = _documentTypeService.selectTypesOf(step
- .getStep());
- dprop.setName("document" + i++).setType(dtypes.get(0));
- // Create a document published in the scenario
- Publication pub = _stepService.createDocument(step, dprop);
- // Attach a file
- _publicationService.attach(pub, "brep"); // TODO: test for different formats
+ LOG.debug("Create scenario step: " + i);
+
+ org.splat.som.Step aScStep = new org.splat.som.Step(step, aScenario);
+ List<DocumentType> dtypes = _documentTypeService
+ .selectTypesOf(step);
+ for (DocumentType dtype : dtypes) {
+ // Create a document published in the scenario
+ // document<i>: document type[0] - first type used on the step
+ // <source-file>.brep
+ // <attached-file>.med
+ dprop.setName("document" + i++).setType(dtype);
+/* if (step.getNumber() > 3) {
+ dprop.setFormat("med");
+ } else {
+*/ dprop.setFormat("py");
+// }
+ dprop.setLocalPath(dprop.getName() + "." + dprop.getFormat());
+ Publication pub = createDoc(aScenario, aScStep, dprop, "med",
+ false);
+ if (usedPub != null) {
+ pub.addDependency(usedPub);
+ ht.saveOrUpdate(pub.value());
+
+ usedMap.put(pub.getIndex(), usedPub.getIndex());
+ }
+ usedPub = pub;
+
+ // Create another document with outdated publication
+ dprop.setName("document" + i++).setType(dtype).setFormat("py");
+ dprop.setLocalPath(dprop.getName() + "." + dprop.getFormat());
+ createDoc(aScenario, aScStep, dprop, "med", true);
+
+ }
+ if (dtypes.size() <= 0) {
+ LOG.debug("No document types are found for scenario step " + i);
+ }
+ }
+
+ // Check that the scenario and its documents have been created correctly.
+
+ Assert.assertNotNull(ht.find("from Document"),
+ "No documents in the database.");
+ Assert.assertTrue(ht.find("from Document").size() > 0,
+ "No documents in the database.");
+
+ Assert.assertNotNull(ht.find("from Publication where owner="
+ + aScenario.getIndex()), "No publications in the database.");
+ Assert.assertTrue(
+ ht.find("from Publication where owner=" + aScenario.getIndex())
+ .size() > 0, "No publications in the database.");
+
+ for (Publication p : (List<Publication>) ht
+ .find("from Publication where owner=" + aScenario.getIndex())) {
+ LOG.debug("Publication found: [id=" + p.getIndex() + ", owner="
+ + p.getOwner().getIndex() + ", doc=" + p.value().getIndex()
+ + "]");
+ Assert.assertEquals(p.getOwner().getIndex(), aScenario.getIndex(),
+ "The publication was not attached to the scenario.");
+ }
+
+ // Remove the scenario from the current hibernate session.
+ ht.evict(aScenario);
+ // Check that the scenario is created in the database.
+ Scenario aScen = ht.load(Scenario.class, aScenario.getIndex());
+ Assert.assertNotNull(aScen, "Scenario was not saved in the database.");
+ Assert.assertTrue(aScen.getDocums().size() > 0,
+ "No publications in the scenario.");
+
+ Assert.assertTrue(i > 0,
+ "More then one document must be in the database");
+
+ // Check created uses relations
+ Assert
+ .assertTrue(usedMap.size() > 0,
+ "Uses relations must be created.");
+ boolean foundAny = false;
+ for (Long usingId : usedMap.keySet()) {
+ for (Publication pub : aScen.getDocums()) {
+ if (pub.getIndex() == usingId) {
+ boolean found = false;
+ for (Publication used : aScen.getDocums()) {
+ found = (used.getIndex() == usedMap.get(usingId));
+ if (found) {
+ break;
+ }
+ }
+ Assert.assertTrue(found,
+ "Uses relation was not created in the database.");
+ foundAny = foundAny || found;
+ }
+ }
}
+ Assert.assertTrue(foundAny,
+ "No Uses relation was created in the database.");
return aScenario.getIndex();
}
/**
- * Check that given objects are equal.
+ * Create a document published in the scenario. <BR>
+ * document:<BR>
+ * document type[0] - first type used on the step <BR>
+ * <source-file>.brep <BR>
+ * <attached-file>.med
+ *
+ * @param aScenario
+ * the scenario to add the document to
+ * @param aScStep
+ * scenario step where the document to be published
+ * @param dprop
+ * document properties
+ * @param attachedFileExt
+ * extension of the secon attached (exported) file
+ * @param isOutdated
+ * outdated document flag
+ * @return the publication of the created document
+ * @throws IOException
+ * @throws MultiplyDefinedException
+ * @throws InvalidPropertyException
+ * @throws MissedPropertyException
+ */
+ private Publication createDoc(final Scenario aScenario,
+ final org.splat.som.Step aScStep, final Properties dprop,
+ final String attachedFileExt, final boolean isOutdated)
+ throws MissedPropertyException, InvalidPropertyException,
+ MultiplyDefinedException, IOException {
+ // Create a document published in the scenario
+ // 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.");
+ Assert.assertEquals(pub.getOwner().getIndex(), aScenario.getIndex(),
+ "The publication was not attached to the scenario.");
+
+ if (isOutdated) {
+ pub.setIsnew('O');
+ }
+ aScenario.add(pub);
+ HibernateTemplate ht = getHibernateTemplate();
+ 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>
*
- * @param anActual
- * the object to check
- * @param anExpected
- * the expected object
- */
- private void compareObjects(final KnowledgeElement anActual,
- final KnowledgeElement anExpected) {
- Assert.assertNotNull(anActual,
- "Created object is not found in the database.");
- Assert.assertEquals(anActual.getAuthor(), anExpected.getAuthor(),
- "Knowledge Element author is not saved.");
- Assert.assertEquals(anActual.getDate(), anExpected.getDate(),
- "Knowledge Element date is not saved.");
+ * <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
- .assertEquals(anActual.getOwnerScenario(), anExpected
- .getOwnerScenario(),
- "Knowledge Element scenario is not saved.");
- Assert.assertEquals(anActual.getProgressState(), anExpected
- .getProgressState(), "Knowledge Element state is not saved.");
- Assert.assertEquals(anActual.getTitle(), anExpected.getTitle(),
- "Knowledge Element title is not saved.");
- Assert.assertEquals(anActual.getType(), anExpected.getType(),
- "Knowledge Element type is not saved.");
- Assert.assertEquals(anActual.getValue(), anExpected.getValue(),
- "Knowledge Element value is not saved.");
- Assert.assertEquals(anActual.getIndex(), anExpected.getIndex(),
- "Knowledge Element index is not saved.");
+ .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()");
}
}