diff --git a/CellDesigner-plugin/src/test/java/lcsb/mapviewer/cdplugin/CdPluginFunctions.java b/CellDesigner-plugin/src/test/java/lcsb/mapviewer/cdplugin/CdPluginFunctions.java index f426805aebbb074372adb584168f929bc3cc8e2e..e1b62ea3aab0e0b5d1e1aabad2172847ab39a633 100644 --- a/CellDesigner-plugin/src/test/java/lcsb/mapviewer/cdplugin/CdPluginFunctions.java +++ b/CellDesigner-plugin/src/test/java/lcsb/mapviewer/cdplugin/CdPluginFunctions.java @@ -3,8 +3,7 @@ package lcsb.mapviewer.cdplugin; import java.util.List; import org.apache.logging.log4j.core.LogEvent; -import org.junit.After; -import org.junit.Before; +import org.junit.*; import org.mockito.Mockito; import jp.sbi.celldesigner.plugin.PluginListOf; @@ -12,9 +11,13 @@ import jp.sbi.celldesigner.plugin.PluginReaction; import jp.sbi.celldesigner.plugin.PluginSpecies; import jp.sbi.celldesigner.plugin.PluginSpeciesAlias; import lcsb.mapviewer.common.MinervaLoggerAppender; +import lcsb.mapviewer.common.UnitTestFailedWatcher; public class CdPluginFunctions { + @Rule + public UnitTestFailedWatcher unitTestFailedWatcher = new UnitTestFailedWatcher(); + String rdfString = "<rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\" xmlns:dc=\"http://purl.org/dc/elements/1.1/\" xmlns:dcterms=\"http://purl.org/dc/terms/\" xmlns:vCard=\"http://www.w3.org/2001/vcard-rdf/3.0#\" xmlns:bqbiol=\"http://biomodels.net/biology-qualifiers/\" xmlns:bqmodel=\"http://biomodels.net/model-qualifiers/\">\n" + "<rdf:Description rdf:about=\"#s3\">\n" + diff --git a/CellDesigner-plugin/src/test/java/lcsb/mapviewer/cdplugin/copypaste/CopyPasteAbstractActionTest.java b/CellDesigner-plugin/src/test/java/lcsb/mapviewer/cdplugin/copypaste/CopyPasteAbstractActionTest.java index 193fa63642653bca05a885e130bcdb34b1b6ce36..4dd70714c5ed18f59d6667dcdba23c0d459dfb02 100644 --- a/CellDesigner-plugin/src/test/java/lcsb/mapviewer/cdplugin/copypaste/CopyPasteAbstractActionTest.java +++ b/CellDesigner-plugin/src/test/java/lcsb/mapviewer/cdplugin/copypaste/CopyPasteAbstractActionTest.java @@ -1,22 +1,18 @@ package lcsb.mapviewer.cdplugin.copypaste; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +import static org.junit.Assert.*; import java.util.Set; -import org.apache.logging.log4j.*; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.junit.*; +import lcsb.mapviewer.cdplugin.CdPluginFunctions; import lcsb.mapviewer.common.Pair; -import lcsb.mapviewer.model.map.MiriamData; -import lcsb.mapviewer.model.map.MiriamRelationType; -import lcsb.mapviewer.model.map.MiriamType; +import lcsb.mapviewer.model.map.*; -public class CopyPasteAbstractActionTest { +public class CopyPasteAbstractActionTest extends CdPluginFunctions { Logger logger = LogManager.getLogger(CopyPasteAbstractActionTest.class); @Before @@ -29,102 +25,70 @@ public class CopyPasteAbstractActionTest { @Test public void testPaste() throws Exception { - try { - CopyPasteAbstractAction pa = new PasteAction(); - String clipboardString = "[MIRIAM]\t" + MiriamRelationType.BQ_BIOL_IS.getStringRepresentation() + "\t" - + MiriamType.CHEBI.getUris().get(0) - + "\tCHEBI:12345\nasd"; - Pair<Set<MiriamData>, String> res = pa.getAnnotationDataFromClipboardString(clipboardString); - assertNotNull(res); - assertNotNull(res.getLeft()); - assertEquals(1, res.getLeft().size()); - assertNotNull(res.getRight()); - assertEquals("asd", res.getRight()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + CopyPasteAbstractAction pa = new PasteAction(); + String clipboardString = "[MIRIAM]\t" + MiriamRelationType.BQ_BIOL_IS.getStringRepresentation() + "\t" + + MiriamType.CHEBI.getUris().get(0) + + "\tCHEBI:12345\nasd"; + Pair<Set<MiriamData>, String> res = pa.getAnnotationDataFromClipboardString(clipboardString); + assertNotNull(res); + assertNotNull(res.getLeft()); + assertEquals(1, res.getLeft().size()); + assertNotNull(res.getRight()); + assertEquals("asd", res.getRight()); } @Test public void testCopyPaste() throws Exception { - try { - CopyPasteAbstractAction pa = new PasteAction(); - String annString = "<rdf:RDF xmlns:bqbiol=\"http://biomodels.net/biology-qualifiers/\" " - + "xmlns:bqmodel=\"http://biomodels.net/model-qualifiers/\" " - + "xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\">\n" - + "<rdf:Description rdf:about=\"#s1\">" + "<bqmodel:is>" + "<rdf:Bag>" - + "<rdf:li rdf:resource=\"urn:miriam:hgnc:SNCA\"/>" + "</rdf:Bag>" - + "</bqmodel:is>" + "</rdf:Description>" + "</rdf:RDF>"; - - String str = pa.getCopyString(annString, "notes"); - - Pair<Set<MiriamData>, String> res = pa.getAnnotationDataFromClipboardString(str); - assertNotNull(res); - assertNotNull(res.getLeft()); - assertEquals(1, res.getLeft().size()); - assertNotNull(res.getRight()); - assertEquals("notes", res.getRight()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + CopyPasteAbstractAction pa = new PasteAction(); + String annString = "<rdf:RDF xmlns:bqbiol=\"http://biomodels.net/biology-qualifiers/\" " + + "xmlns:bqmodel=\"http://biomodels.net/model-qualifiers/\" " + + "xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\">\n" + + "<rdf:Description rdf:about=\"#s1\">" + "<bqmodel:is>" + "<rdf:Bag>" + + "<rdf:li rdf:resource=\"urn:miriam:hgnc:SNCA\"/>" + "</rdf:Bag>" + + "</bqmodel:is>" + "</rdf:Description>" + "</rdf:RDF>"; + + String str = pa.getCopyString(annString, "notes"); + + Pair<Set<MiriamData>, String> res = pa.getAnnotationDataFromClipboardString(str); + assertNotNull(res); + assertNotNull(res.getLeft()); + assertEquals(1, res.getLeft().size()); + assertNotNull(res.getRight()); + assertEquals("notes", res.getRight()); } @Test public void testSerializeMiriam() throws Exception { - try { - CopyPasteAbstractAction pa = new PasteAction(); - MiriamData md = new MiriamData(MiriamType.CHEBI, "CH:12"); - - String string = pa.serialize(md); - MiriamData md2 = pa.deserialize(string); - assertEquals(md, md2); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + CopyPasteAbstractAction pa = new PasteAction(); + MiriamData md = new MiriamData(MiriamType.CHEBI, "CH:12"); + + String string = pa.serialize(md); + MiriamData md2 = pa.deserialize(string); + assertEquals(md, md2); } @Test public void testDeserializeMiriam() throws Exception { - try { - CopyPasteAbstractAction pa = new PasteAction(); - - MiriamData md = pa.deserialize("ASDASDAS"); - assertNull(md); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + CopyPasteAbstractAction pa = new PasteAction(); + + MiriamData md = pa.deserialize("ASDASDAS"); + assertNull(md); } @Test public void testDeserializeMiriam2() throws Exception { - try { - CopyPasteAbstractAction pa = new PasteAction(); - - MiriamData md = pa.deserialize(null); - assertNull(md); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + CopyPasteAbstractAction pa = new PasteAction(); + + MiriamData md = pa.deserialize(null); + assertNull(md); } @Test public void testDeserializeMiriam3() throws Exception { - try { - CopyPasteAbstractAction pa = new PasteAction(); - - MiriamData md = pa.deserialize("[MIRIAM]\tinvalid\ttype\tresource"); - assertNull(md); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + CopyPasteAbstractAction pa = new PasteAction(); + + MiriamData md = pa.deserialize("[MIRIAM]\tinvalid\ttype\tresource"); + assertNull(md); } } diff --git a/annotation/src/test/java/lcsb/mapviewer/annotation/AnnotationTestFunctions.java b/annotation/src/test/java/lcsb/mapviewer/annotation/AnnotationTestFunctions.java index f5e381170ab4b2be845a00772d0e5597d56b427c..85396c4660f6ee25d79d7b5572b5e1185e74180a 100644 --- a/annotation/src/test/java/lcsb/mapviewer/annotation/AnnotationTestFunctions.java +++ b/annotation/src/test/java/lcsb/mapviewer/annotation/AnnotationTestFunctions.java @@ -30,9 +30,7 @@ import javax.xml.transform.stream.StreamResult; import org.apache.logging.log4j.*; import org.apache.logging.log4j.core.LogEvent; - -import org.junit.After; -import org.junit.Before; +import org.junit.*; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; @@ -48,6 +46,7 @@ import org.xml.sax.SAXException; import lcsb.mapviewer.annotation.cache.PermanentDatabaseLevelCacheInterface; import lcsb.mapviewer.common.MinervaLoggerAppender; +import lcsb.mapviewer.common.UnitTestFailedWatcher; import lcsb.mapviewer.common.exception.InvalidXmlSchemaException; import lcsb.mapviewer.converter.ConverterParams; import lcsb.mapviewer.converter.model.celldesigner.CellDesignerXmlParser; @@ -60,6 +59,9 @@ import lcsb.mapviewer.persist.dao.cache.CacheTypeDao; @RunWith(SpringJUnit4ClassRunner.class) public abstract class AnnotationTestFunctions extends AbstractTransactionalJUnit4SpringContextTests { + @Rule + public UnitTestFailedWatcher unitTestFailedWatcher = new UnitTestFailedWatcher(); + @Autowired protected PermanentDatabaseLevelCacheInterface cache; diff --git a/annotation/src/test/java/lcsb/mapviewer/annotation/cache/ApplicationLevelCacheTest.java b/annotation/src/test/java/lcsb/mapviewer/annotation/cache/ApplicationLevelCacheTest.java index 6b47b3b017db97ef481d18a19ecaca03a55c887d..3d41364949a66125c64de1681b39832f8aa8e15d 100644 --- a/annotation/src/test/java/lcsb/mapviewer/annotation/cache/ApplicationLevelCacheTest.java +++ b/annotation/src/test/java/lcsb/mapviewer/annotation/cache/ApplicationLevelCacheTest.java @@ -1,14 +1,10 @@ package lcsb.mapviewer.annotation.cache; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import org.apache.logging.log4j.*; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import static org.junit.Assert.*; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.junit.*; import org.w3c.dom.Node; import lcsb.mapviewer.annotation.AnnotationTestFunctions; @@ -18,104 +14,89 @@ import lcsb.mapviewer.model.cache.CacheType; public class ApplicationLevelCacheTest extends AnnotationTestFunctions { - Logger logger = LogManager.getLogger(ApplicationLevelCacheTest.class); - - boolean status; - - @Before - public void setUp() throws Exception { - status = Configuration.isApplicationCacheOn(); - } - - @After - public void tearDown() throws Exception { - Configuration.setApplicationCacheOn(status); - } - - @Test - public void testApplicationCacheByQuery() { - try { - CacheType type = cacheTypeDao.getByClassName(PubmedParser.class.getCanonicalName()); - String xml = "<hello/>"; - String query = "blabla"; - Node sourceNode = getNodeFromXmlString(xml); - ApplicationLevelCache cache = ApplicationLevelCache.getInstance(); - cache.clearCache(); - - Node node = cache.getXmlNodeByQuery(query, type); - assertNull(node); - - cache.setCachedQuery(query, type, sourceNode); - node = cache.getXmlNodeByQuery(query, type); - assertNotNull(node); - - cache.clearCache(); - node = cache.getXmlNodeByQuery(query, type); - assertNull(node); - - } catch (Exception e) { - e.printStackTrace(); - fail("Unknown exception"); - } - } - - @Test - public void testApplicationCacheOff() { - boolean value = Configuration.isApplicationCacheOn(); - - try { - Configuration.setApplicationCacheOn(false); - assertNull(ApplicationLevelCache.getInstance()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } finally { - Configuration.setApplicationCacheOn(value); - } - } - - @Test - public void testSetInvalidValue() { - try { - ApplicationLevelCache cache = ApplicationLevelCache.getInstance(); - cache.setCachedQuery("bla", null, new Object()); - } catch (CacheException e) { - assertTrue(e.getMessage().contains("Unknown object type")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testClearCacheWhenMemoryUsageIsHigh() throws Exception { - Double oldVal = Configuration.getMemorySaturationRatioTriggerClean(); - try { - CacheType type = new CacheType(); - type.setId(-13); - ApplicationLevelCache cache = ApplicationLevelCache.getInstance(); - cache.setCachedQuery("bla", type, "test"); - - assertNotNull(cache.getStringByQuery("bla", type)); - // fill cache with some dumb data - for (int i = 0; i < ApplicationLevelCache.MIN_CACHED_VALUES_BEFORE_CLEAN; i++) { - cache.setCachedQuery("bla" + i, type, "test"); - } - assertNotNull(cache.getStringByQuery("bla", type)); - - Configuration.setMemorySaturationRatioTriggerClean(0.0); - cache.performMemoryBalance(); - assertNull(cache.getStringByQuery("bla", type)); - - } catch (CacheException e) { - assertTrue(e.getMessage().contains("Unknown object type")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } finally { - // restore old value - Configuration.setMemorySaturationRatioTriggerClean(oldVal); - } - } + Logger logger = LogManager.getLogger(ApplicationLevelCacheTest.class); + + boolean status; + + @Before + public void setUp() throws Exception { + status = Configuration.isApplicationCacheOn(); + } + + @After + public void tearDown() throws Exception { + Configuration.setApplicationCacheOn(status); + } + + @Test + public void testApplicationCacheByQuery() throws Exception { + CacheType type = cacheTypeDao.getByClassName(PubmedParser.class.getCanonicalName()); + String xml = "<hello/>"; + String query = "blabla"; + Node sourceNode = getNodeFromXmlString(xml); + ApplicationLevelCache cache = ApplicationLevelCache.getInstance(); + cache.clearCache(); + + Node node = cache.getXmlNodeByQuery(query, type); + assertNull(node); + + cache.setCachedQuery(query, type, sourceNode); + node = cache.getXmlNodeByQuery(query, type); + assertNotNull(node); + + cache.clearCache(); + node = cache.getXmlNodeByQuery(query, type); + assertNull(node); + } + + @Test + public void testApplicationCacheOff() { + boolean value = Configuration.isApplicationCacheOn(); + + try { + Configuration.setApplicationCacheOn(false); + assertNull(ApplicationLevelCache.getInstance()); + } finally { + Configuration.setApplicationCacheOn(value); + } + } + + @Test + public void testSetInvalidValue() { + try { + ApplicationLevelCache cache = ApplicationLevelCache.getInstance(); + cache.setCachedQuery("bla", null, new Object()); + } catch (CacheException e) { + assertTrue(e.getMessage().contains("Unknown object type")); + } + } + + @Test + public void testClearCacheWhenMemoryUsageIsHigh() throws Exception { + Double oldVal = Configuration.getMemorySaturationRatioTriggerClean(); + try { + CacheType type = new CacheType(); + type.setId(-13); + ApplicationLevelCache cache = ApplicationLevelCache.getInstance(); + cache.setCachedQuery("bla", type, "test"); + + assertNotNull(cache.getStringByQuery("bla", type)); + // fill cache with some dumb data + for (int i = 0; i < ApplicationLevelCache.MIN_CACHED_VALUES_BEFORE_CLEAN; i++) { + cache.setCachedQuery("bla" + i, type, "test"); + } + assertNotNull(cache.getStringByQuery("bla", type)); + + Configuration.setMemorySaturationRatioTriggerClean(0.0); + cache.performMemoryBalance(); + assertNull(cache.getStringByQuery("bla", type)); + + } catch (CacheException e) { + assertTrue(e.getMessage().contains("Unknown object type")); + } finally { + // restore old value + Configuration.setMemorySaturationRatioTriggerClean(oldVal); + } + } } diff --git a/annotation/src/test/java/lcsb/mapviewer/annotation/cache/BigFileCacheTest.java b/annotation/src/test/java/lcsb/mapviewer/annotation/cache/BigFileCacheTest.java index 43b78c5c54b9e65e5024ba4868f1f337cdfe1771..0e0b7f53056da2cabc2d4707b3b796c7e3dfaefe 100644 --- a/annotation/src/test/java/lcsb/mapviewer/annotation/cache/BigFileCacheTest.java +++ b/annotation/src/test/java/lcsb/mapviewer/annotation/cache/BigFileCacheTest.java @@ -1,31 +1,17 @@ package lcsb.mapviewer.annotation.cache; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.anyString; -import static org.mockito.Mockito.when; - -import java.io.File; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.PrintWriter; +import static org.junit.Assert.*; +import static org.mockito.ArgumentMatchers.*; +import static org.mockito.Mockito.*; + +import java.io.*; import java.net.URISyntaxException; -import java.util.concurrent.Callable; -import java.util.concurrent.Executors; -import java.util.concurrent.Future; -import java.util.concurrent.ThreadFactory; - -import org.apache.commons.net.ftp.FTPClient; -import org.apache.commons.net.ftp.FTPFile; -import org.apache.commons.net.ftp.FTPReply; -import org.apache.logging.log4j.*; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import java.util.concurrent.*; + +import org.apache.commons.net.ftp.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.junit.*; import org.mockito.Mockito; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; @@ -61,49 +47,43 @@ public class BigFileCacheTest extends AnnotationTestFunctions { @Test public void testDownloadFile() throws Exception { - try { - bigFileCache.downloadFile(ftpUrl, false, null); - String localFile = bigFileCache.getAbsolutePathForFile(ftpUrl); - assertTrue(bigFileCache.isCached(ftpUrl)); - assertTrue(bigFileCache.isLocalFileUpToDate(ftpUrl)); - File f = new File(localFile); - assertTrue(f.exists()); - String content = super.readFile(localFile); - assertTrue(content.contains(ftpUrlPartContent)); - - int warnigsCount = getWarnings().size(); - // when we try to download file that is already downloaded there should be - // a warning - bigFileCache.downloadFile(ftpUrl, false, null); - assertEquals(warnigsCount + 1, getWarnings().size()); - - // however when due to some reason the file will be removed from file - // system - f.delete(); - // the file should be downloaded again - bigFileCache.downloadFile(ftpUrl, false, null); - // additional warning about it - assertEquals(warnigsCount + 2, getWarnings().size()); - - localFile = bigFileCache.getAbsolutePathForFile(ftpUrl); - f = new File(localFile); - assertTrue(f.exists()); - - // when we are trying to update file that is up to date then we will have - // a warning about it (but file shouldn't be changed) - bigFileCache.updateFile(ftpUrl, false); - assertEquals(warnigsCount + 3, getWarnings().size()); - - bigFileCache.removeFile(ftpUrl); - - assertNull(bigFileCache.getAbsolutePathForFile(ftpUrl)); - - assertFalse(f.exists()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + bigFileCache.downloadFile(ftpUrl, false, null); + String localFile = bigFileCache.getAbsolutePathForFile(ftpUrl); + assertTrue(bigFileCache.isCached(ftpUrl)); + assertTrue(bigFileCache.isLocalFileUpToDate(ftpUrl)); + File f = new File(localFile); + assertTrue(f.exists()); + String content = super.readFile(localFile); + assertTrue(content.contains(ftpUrlPartContent)); + + int warnigsCount = getWarnings().size(); + // when we try to download file that is already downloaded there should be + // a warning + bigFileCache.downloadFile(ftpUrl, false, null); + assertEquals(warnigsCount + 1, getWarnings().size()); + + // however when due to some reason the file will be removed from file + // system + f.delete(); + // the file should be downloaded again + bigFileCache.downloadFile(ftpUrl, false, null); + // additional warning about it + assertEquals(warnigsCount + 2, getWarnings().size()); + + localFile = bigFileCache.getAbsolutePathForFile(ftpUrl); + f = new File(localFile); + assertTrue(f.exists()); + + // when we are trying to update file that is up to date then we will have + // a warning about it (but file shouldn't be changed) + bigFileCache.updateFile(ftpUrl, false); + assertEquals(warnigsCount + 3, getWarnings().size()); + + bigFileCache.removeFile(ftpUrl); + + assertNull(bigFileCache.getAbsolutePathForFile(ftpUrl)); + + assertFalse(f.exists()); } @Test @@ -113,47 +93,32 @@ public class BigFileCacheTest extends AnnotationTestFunctions { } catch (URISyntaxException e) { assertTrue(e.getMessage().contains("Unknown protocol for url")); - } catch (Exception e) { - e.printStackTrace(); - throw e; } } @Test public void testDownloadAsyncFileFromHttp() throws Exception { - try { - bigFileCache.downloadFile(httpUrl, true, null); - waitForDownload(); - String localFile = bigFileCache.getAbsolutePathForFile(httpUrl); - assertTrue(bigFileCache.isLocalFileUpToDate(httpUrl)); - File f = new File(localFile); - assertTrue(f.exists()); - String content = super.readFile(localFile); - assertTrue(content.contains("Google")); - bigFileCache.removeFile(httpUrl); - - assertNull(bigFileCache.getAbsolutePathForFile(httpUrl)); - - assertFalse(f.exists()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + bigFileCache.downloadFile(httpUrl, true, null); + waitForDownload(); + String localFile = bigFileCache.getAbsolutePathForFile(httpUrl); + assertTrue(bigFileCache.isLocalFileUpToDate(httpUrl)); + File f = new File(localFile); + assertTrue(f.exists()); + String content = super.readFile(localFile); + assertTrue(content.contains("Google")); + bigFileCache.removeFile(httpUrl); + + assertNull(bigFileCache.getAbsolutePathForFile(httpUrl)); + + assertFalse(f.exists()); } - @Test + @Test(expected = IOException.class) public void testSavingToInvalidDirectory() throws Exception { try { String url = httpUrl + "?invalid"; Configuration.setWebAppDir("/dev/random/xxx"); bigFileCache.downloadFile(url, false, null); - fail("Exception expected"); - } catch (IOException e) { - - } catch (Exception e) { - e.printStackTrace(); - throw e; } finally { Configuration.setWebAppDir("./"); } @@ -166,52 +131,32 @@ public class BigFileCacheTest extends AnnotationTestFunctions { } } - @Test + @Test(expected = FileNotFoundException.class) public void testIsLocalHttpFileUpToDateWhenMissing() throws Exception { - try { - bigFileCache.isLocalFileUpToDate(httpUrl + "?some_get_param"); - fail("Exception expected"); - } catch (FileNotFoundException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + bigFileCache.isLocalFileUpToDate(httpUrl + "?some_get_param"); } - @Test + @Test(expected = FileNotFoundException.class) public void testIsLocalHttpFileUpToDateWhenFileRemovedManually() throws Exception { - try { - bigFileCache.downloadFile(httpUrl, false, new IProgressUpdater() { - @Override - public void setProgress(double progress) { - } - }); - new File(bigFileCache.getAbsolutePathForFile(httpUrl)).delete(); - try { - bigFileCache.isLocalFileUpToDate(httpUrl); - fail("Exception expected"); - } catch (FileNotFoundException e) { + bigFileCache.downloadFile(httpUrl, false, new IProgressUpdater() { + @Override + public void setProgress(double progress) { } + }); + new File(bigFileCache.getAbsolutePathForFile(httpUrl)).delete(); + try { + bigFileCache.isLocalFileUpToDate(httpUrl); + } finally { bigFileCache.removeFile(httpUrl); - } catch (Exception e) { - e.printStackTrace(); - throw e; } } - @Test + @Test(expected = FileNotFoundException.class) public void testIsLocalFtpFileUpToDateWhenMissing() throws Exception { - try { - bigFileCache.isLocalFileUpToDate(ftpUrl); - fail("Exception expected"); - } catch (FileNotFoundException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + bigFileCache.isLocalFileUpToDate(ftpUrl); } - @Test + @Test(expected = IOException.class) public void testRefreshCacheQueryWhenFtpConnectionFails() throws Exception { try { @@ -237,19 +182,13 @@ public class BigFileCacheTest extends AnnotationTestFunctions { bigFileCache.setFtpClientFactory(factory); bigFileCache.isLocalFileUpToDate(ftpUrl); - fail("Exception expected"); - } catch (IOException e) { - assertTrue(e.getMessage().contains("FTP server refused connection")); - } catch (Exception e) { - e.printStackTrace(); - throw e; } finally { bigFileCache.setFtpClientFactory(new FtpClientFactory()); bigFileCache.removeFile(ftpUrl); } } - @Test + @Test(expected = IOException.class) public void testDownloadWhenFtpConnectionFails() throws Exception { try { FTPClient mockClient = Mockito.mock(FTPClient.class); @@ -265,20 +204,13 @@ public class BigFileCacheTest extends AnnotationTestFunctions { bigFileCache.setFtpClientFactory(factory); bigFileCache.downloadFile(ftpUrl, false, null); - - fail("Exception expected"); - } catch (IOException e) { - assertTrue(e.getMessage().contains("FTP server refused connection")); - } catch (Exception e) { - e.printStackTrace(); - throw e; } finally { bigFileCache.setFtpClientFactory(new FtpClientFactory()); bigFileCache.removeFile(ftpUrl); } } - @Test + @Test(expected = InvalidStateException.class) public void testDownloadHttpWhenDownloadFails() throws Exception { ConfigurationDao configurationDao = bigFileCache.getConfigurationDao(); @@ -288,313 +220,251 @@ public class BigFileCacheTest extends AnnotationTestFunctions { when(mockDao.getValueByType(any())).thenThrow(new RuntimeException()); bigFileCache.setConfigurationDao(mockDao); bigFileCache.downloadFile(httpUrl, false, null); - - fail("Exception expected"); - } catch (InvalidStateException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; } finally { bigFileCache.setConfigurationDao(configurationDao); } } - @Test + @Test(expected = FileNotFoundException.class) public void testDownloadedFileRemovedException() throws Exception { - try { - String url = ftpUrl; - bigFileCache.downloadFile(url, false, new IProgressUpdater() { - @Override - public void setProgress(double progress) { - } - }); - String localFile = bigFileCache.getAbsolutePathForFile(url); - File f = new File(localFile); - assertTrue(f.exists()); - f.delete(); - - try { - bigFileCache.getAbsolutePathForFile(url); - fail("Exception expected"); - } catch (FileNotFoundException e) { - + String url = ftpUrl; + bigFileCache.downloadFile(url, false, new IProgressUpdater() { + @Override + public void setProgress(double progress) { } - try { - bigFileCache.isLocalFileUpToDate(url); - fail("Exception expected"); - } catch (FileNotFoundException e) { + }); + String localFile = bigFileCache.getAbsolutePathForFile(url); + File f = new File(localFile); + assertTrue(f.exists()); + f.delete(); + try { + bigFileCache.getAbsolutePathForFile(url); + } finally { + bigFileCache.removeFile(url); + assertNull(bigFileCache.getAbsolutePathForFile(url)); + assertFalse(f.exists()); + } + } + + @Test(expected = FileNotFoundException.class) + public void testDownloadedFileRemovedException2() throws Exception { + String url = ftpUrl; + bigFileCache.downloadFile(url, false, new IProgressUpdater() { + @Override + public void setProgress(double progress) { } + }); + String localFile = bigFileCache.getAbsolutePathForFile(url); + File f = new File(localFile); + assertTrue(f.exists()); + f.delete(); + try { + bigFileCache.isLocalFileUpToDate(url); + } finally { bigFileCache.removeFile(url); - assertNull(bigFileCache.getAbsolutePathForFile(url)); - assertFalse(f.exists()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; } } - @Test + @Test(expected = FileNotFoundException.class) public void testGetPathForFileBeingDownloaded() throws Exception { - try { - String url = ftpUrl; - BigFileCache bigFileCacheUnderTest = new BigFileCache(null, null, null); - BigFileEntryDao mockDao = Mockito.mock(BigFileEntryDao.class); - BigFileEntry entry = new BigFileEntry(); - when(mockDao.getByUrl(anyString())).thenReturn(entry); - - bigFileCacheUnderTest.setBigFileEntryDao(mockDao); - try { - bigFileCacheUnderTest.getAbsolutePathForFile(url); - fail("Exception expected"); - } catch (FileNotFoundException e) { - assertTrue(e.getMessage().contains("File is not complete")); - } - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String url = ftpUrl; + BigFileCache bigFileCacheUnderTest = new BigFileCache(null, null, null); + BigFileEntryDao mockDao = Mockito.mock(BigFileEntryDao.class); + BigFileEntry entry = new BigFileEntry(); + when(mockDao.getByUrl(anyString())).thenReturn(entry); + + bigFileCacheUnderTest.setBigFileEntryDao(mockDao); + bigFileCacheUnderTest.getAbsolutePathForFile(url); } @Test public void testUpdateFile() throws Exception { - try { - bigFileCache.downloadFile(ftpUrl, false, new IProgressUpdater() { - @Override - public void setProgress(double progress) { - } - }); - String localFile = bigFileCache.getAbsolutePathForFile(ftpUrl); - File f = new File(localFile); - f.delete(); - PrintWriter out = new PrintWriter(localFile); - out.println("tesxt"); - out.close(); + bigFileCache.downloadFile(ftpUrl, false, new IProgressUpdater() { + @Override + public void setProgress(double progress) { + } + }); + String localFile = bigFileCache.getAbsolutePathForFile(ftpUrl); + File f = new File(localFile); + f.delete(); + PrintWriter out = new PrintWriter(localFile); + out.println("tesxt"); + out.close(); - String content = super.readFile(localFile); - assertFalse(content.contains(ftpUrlPartContent)); + String content = super.readFile(localFile); + assertFalse(content.contains(ftpUrlPartContent)); - assertFalse(bigFileCache.isLocalFileUpToDate(ftpUrl)); - bigFileCache.updateFile(ftpUrl, false); + assertFalse(bigFileCache.isLocalFileUpToDate(ftpUrl)); + bigFileCache.updateFile(ftpUrl, false); - localFile = bigFileCache.getAbsolutePathForFile(ftpUrl); + localFile = bigFileCache.getAbsolutePathForFile(ftpUrl); - content = super.readFile(localFile); - assertTrue(content.contains(ftpUrlPartContent)); + content = super.readFile(localFile); + assertTrue(content.contains(ftpUrlPartContent)); - // now try update asynchronously - f = new File(localFile); - f.delete(); - out = new PrintWriter(localFile); - out.println("tesxt"); - out.close(); + // now try update asynchronously + f = new File(localFile); + f.delete(); + out = new PrintWriter(localFile); + out.println("tesxt"); + out.close(); - assertFalse(bigFileCache.isLocalFileUpToDate(ftpUrl)); - bigFileCache.updateFile(ftpUrl, true); + assertFalse(bigFileCache.isLocalFileUpToDate(ftpUrl)); + bigFileCache.updateFile(ftpUrl, true); - waitForDownload(); + waitForDownload(); - assertTrue(bigFileCache.isLocalFileUpToDate(ftpUrl)); + assertTrue(bigFileCache.isLocalFileUpToDate(ftpUrl)); - // check when connection fails - f = new File(localFile); - f.delete(); - out = new PrintWriter(localFile); - out.println("tesxt"); - out.close(); - - FTPClient mockClient = Mockito.mock(FTPClient.class); - Mockito.doAnswer(new Answer<Integer>() { + // check when connection fails + f = new File(localFile); + f.delete(); + out = new PrintWriter(localFile); + out.println("tesxt"); + out.close(); - // first answer (for checking if the file should be updated) - @Override - public Integer answer(InvocationOnMock invocation) throws Throwable { - return FTPReply.COMMAND_OK; - } - }).doAnswer(new Answer<Integer>() { - // second answer (for downloading) - @Override - public Integer answer(InvocationOnMock invocation) throws Throwable { - return FTPReply.REQUEST_DENIED; - } - }).when(mockClient).getReplyCode(); - - Mockito.doAnswer(new Answer<FTPFile[]>() { - - @Override - public FTPFile[] answer(InvocationOnMock invocation) throws Throwable { - return new FTPFile[] {}; - } - }).when(mockClient).listFiles(anyString()); - - FtpClientFactory factory = Mockito.mock(FtpClientFactory.class); - when(factory.createFtpClient()).thenReturn(mockClient); + FTPClient mockClient = Mockito.mock(FTPClient.class); + Mockito.doAnswer(new Answer<Integer>() { - bigFileCache.setFtpClientFactory(factory); - try { - bigFileCache.updateFile(ftpUrl, false); - fail("Exception expected"); - } catch (IOException e) { - assertTrue(e.getMessage().contains("FTP server refused connection")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } finally { - bigFileCache.setFtpClientFactory(new FtpClientFactory()); + // first answer (for checking if the file should be updated) + @Override + public Integer answer(InvocationOnMock invocation) throws Throwable { + return FTPReply.COMMAND_OK; } + }).doAnswer(new Answer<Integer>() { + // second answer (for downloading) + @Override + public Integer answer(InvocationOnMock invocation) throws Throwable { + return FTPReply.REQUEST_DENIED; + } + }).when(mockClient).getReplyCode(); - bigFileCache.removeFile(ftpUrl); + Mockito.doAnswer(new Answer<FTPFile[]>() { - assertNull(bigFileCache.getAbsolutePathForFile(ftpUrl)); + @Override + public FTPFile[] answer(InvocationOnMock invocation) throws Throwable { + return new FTPFile[] {}; + } + }).when(mockClient).listFiles(anyString()); - assertFalse(f.exists()); + FtpClientFactory factory = Mockito.mock(FtpClientFactory.class); + when(factory.createFtpClient()).thenReturn(mockClient); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testGetRemoteHttpFileSizeForInvalidUrl() throws Exception { + bigFileCache.setFtpClientFactory(factory); try { - bigFileCache.getRemoteHttpFileSize("invalidurl"); + bigFileCache.updateFile(ftpUrl, false); fail("Exception expected"); } catch (IOException e) { - + assertTrue(e.getMessage().contains("FTP server refused connection")); } catch (Exception e) { e.printStackTrace(); throw e; + } finally { + bigFileCache.setFtpClientFactory(new FtpClientFactory()); } + + bigFileCache.removeFile(ftpUrl); + + assertNull(bigFileCache.getAbsolutePathForFile(ftpUrl)); + + assertFalse(f.exists()); + } + + @Test(expected = IOException.class) + public void testGetRemoteHttpFileSizeForInvalidUrl() throws Exception { + bigFileCache.getRemoteHttpFileSize("invalidurl"); } @Test public void testRemoveFileThatDoesntExist() throws Exception { - try { - bigFileCache.removeFile("unexisting file"); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + bigFileCache.removeFile("unexisting file"); } - @Test + @Test(expected = URISyntaxException.class) public void testIsLocalFileUpToDateForInvalidURI() throws Exception { - try { - bigFileCache.isLocalFileUpToDate("unexistingFileProtocol://bla"); - fail("Exception expected"); - } catch (URISyntaxException e) { - assertTrue(e.getMessage().contains("Unknown protocol")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + bigFileCache.isLocalFileUpToDate("unexistingFileProtocol://bla"); } @Test public void testGetDomainName() throws Exception { - try { - String domain = bigFileCache.getDomainName("http://www.eskago.pl/radio/eska-rock"); - assertEquals("eskago.pl", domain); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String domain = bigFileCache.getDomainName("http://www.eskago.pl/radio/eska-rock"); + assertEquals("eskago.pl", domain); } - @Test + @Test(expected = InvalidStateException.class) public void testExecuteProblematicTask() throws Exception { - try { - Future<?> task = Executors.newScheduledThreadPool(10, new ThreadFactory() { - @Override - public Thread newThread(Runnable r) { - Thread t = new Thread(r); - t.setDaemon(true); - return t; - } - }).submit(new Callable<Void>() { - @Override - public Void call() throws Exception { - throw new Exception(); - } - }); - bigFileCache.executeTask(task); - fail("Exception expected"); - } catch (InvalidStateException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Future<?> task = Executors.newScheduledThreadPool(10, new ThreadFactory() { + @Override + public Thread newThread(Runnable r) { + Thread t = new Thread(r); + t.setDaemon(true); + return t; + } + }).submit(new Callable<Void>() { + @Override + public Void call() throws Exception { + throw new Exception(); + } + }); + bigFileCache.executeTask(task); } - @Test + @Test(expected = URISyntaxException.class) public void testExecuteProblematicTask2() throws Exception { - try { - Future<?> task = Executors.newScheduledThreadPool(10, new ThreadFactory() { - @Override - public Thread newThread(Runnable r) { - Thread t = new Thread(r); - t.setDaemon(true); - return t; - } - }).submit(new Callable<Void>() { - @Override - public Void call() throws Exception { - throw new URISyntaxException("", ""); - } - }); - bigFileCache.executeTask(task); - fail("Exception expected"); - } catch (URISyntaxException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Future<?> task = Executors.newScheduledThreadPool(10, new ThreadFactory() { + @Override + public Thread newThread(Runnable r) { + Thread t = new Thread(r); + t.setDaemon(true); + return t; + } + }).submit(new Callable<Void>() { + @Override + public Void call() throws Exception { + throw new URISyntaxException("", ""); + } + }); + bigFileCache.executeTask(task); } @Test public void testExecuteInterruptedTask() throws Exception { - try { - Future<?> task = Executors.newScheduledThreadPool(10, new ThreadFactory() { - @Override - public Thread newThread(Runnable r) { - Thread t = new Thread(r); - t.setDaemon(true); - return t; - } - }).submit(new Callable<Void>() { - @Override - public Void call() throws Exception { - Thread.sleep(100); - return null; - } - }); - Thread t = new Thread(new Runnable() { - @Override - public void run() { - try { - bigFileCache.executeTask(task); - } catch (Exception e) { - logger.fatal(e, e); - } + Future<?> task = Executors.newScheduledThreadPool(10, new ThreadFactory() { + @Override + public Thread newThread(Runnable r) { + Thread t = new Thread(r); + t.setDaemon(true); + return t; + } + }).submit(new Callable<Void>() { + @Override + public Void call() throws Exception { + Thread.sleep(100); + return null; + } + }); + Thread t = new Thread(new Runnable() { + @Override + public void run() { + try { + bigFileCache.executeTask(task); + } catch (Exception e) { + logger.fatal(e, e); } - }); + } + }); - t.start(); - // interrupt thread - t.interrupt(); - t.join(); + t.start(); + // interrupt thread + t.interrupt(); + t.join(); - assertEquals(1, getErrors().size()); - assertEquals(0, getFatals().size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(1, getErrors().size()); + assertEquals(0, getFatals().size()); } } diff --git a/annotation/src/test/java/lcsb/mapviewer/annotation/cache/CachableInterfaceTest.java b/annotation/src/test/java/lcsb/mapviewer/annotation/cache/CachableInterfaceTest.java index 16ae5883a8ff2e5fe3cb2c28391a0851864713c0..eb6f03d3edd91eafb0e5ba889c52fea0e3a0a732 100644 --- a/annotation/src/test/java/lcsb/mapviewer/annotation/cache/CachableInterfaceTest.java +++ b/annotation/src/test/java/lcsb/mapviewer/annotation/cache/CachableInterfaceTest.java @@ -1,13 +1,12 @@ package lcsb.mapviewer.annotation.cache; import static org.junit.Assert.*; -import static org.mockito.Matchers.anyString; -import static org.mockito.Mockito.when; +import static org.mockito.ArgumentMatchers.*; +import static org.mockito.Mockito.*; -import org.apache.logging.log4j.*; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.junit.*; import org.mockito.Mockito; import org.w3c.dom.Node; @@ -15,121 +14,83 @@ import lcsb.mapviewer.annotation.AnnotationTestFunctions; import lcsb.mapviewer.model.cache.CacheType; import lcsb.mapviewer.persist.dao.cache.CacheTypeDao; - public class CachableInterfaceTest extends AnnotationTestFunctions { - Logger logger = LogManager.getLogger(CachableInterfaceTest.class); - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testGetWebPage() throws Exception { - try { - CachableInterfaceMock ci = new CachableInterfaceMock(CachableInterface.class); - String result = ci.getWebPageContent("http://www.drugbank.ca/biodb/polypeptides/P21728"); - assertNotNull(result); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testGetWebPage2() throws Exception { - try { - CachableInterfaceMock ci = new CachableInterfaceMock(CachableInterface.class); - String result = ci.getWebPageContent("http://www.drugbank.ca/drugs/DB00091"); - assertNotNull(result); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testGetWebPageGetCache() throws Exception { - try { - CachableInterfaceMock ci = new CachableInterfaceMock(CachableInterface.class); - - CacheTypeDao mock = Mockito.mock(CacheTypeDao.class); - when(mock.getByClassName(anyString())).thenReturn(new CacheType()); - ci.setCacheTypeDao(mock); - ci.setCache(new GeneralCache(null)); - - String cacheKey = "https://www.google.com/"; - String result = ci.getWebPageContent(cacheKey); - assertNotNull(result); - String cacheValue = ci.getCacheValue(cacheKey); - assertTrue(result.equals(cacheValue)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testSetNode() throws Exception { - try { - CachableInterfaceMock ci = new CachableInterfaceMock(CachableInterface.class); - - CacheTypeDao mock = Mockito.mock(CacheTypeDao.class); - when(mock.getByClassName(anyString())).thenReturn(new CacheType()); - ci.setCacheTypeDao(mock); - - String xml = "<xml><child/></xml>"; - ci.setCache(new GeneralCache(null)); - ci.setCacheNode("id", super.getNodeFromXmlString(xml)); - - Node node = ci.getCacheNode("id"); - assertNotNull(node); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testNewLinesGetWebPage() throws Exception { - try { - CachableInterfaceMock ci = new CachableInterfaceMock(CachableInterface.class); - ci.setCache(null); - String result = ci.getWebPageContent("http://google.com/"); - assertNotNull(result); - assertTrue(result.contains("\n")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testCleanHtml() throws Exception { - try { - CachableInterfaceMock ci = new CachableInterfaceMock(CachableInterface.class); - String res = ci.cleanHtml("blabla <invalid_tag"); - assertEquals("blabla ",res); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testCleanHtml2() throws Exception { - try { - CachableInterfaceMock ci = new CachableInterfaceMock(CachableInterface.class); - String res = ci.cleanHtml("blabla <valid_tag> etc"); - assertEquals("blabla etc",res); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } + Logger logger = LogManager.getLogger(CachableInterfaceTest.class); + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testGetWebPage() throws Exception { + CachableInterfaceMock ci = new CachableInterfaceMock(CachableInterface.class); + String result = ci.getWebPageContent("http://www.drugbank.ca/biodb/polypeptides/P21728"); + assertNotNull(result); + } + + @Test + public void testGetWebPage2() throws Exception { + CachableInterfaceMock ci = new CachableInterfaceMock(CachableInterface.class); + String result = ci.getWebPageContent("http://www.drugbank.ca/drugs/DB00091"); + assertNotNull(result); + } + + @Test + public void testGetWebPageGetCache() throws Exception { + CachableInterfaceMock ci = new CachableInterfaceMock(CachableInterface.class); + + CacheTypeDao mock = Mockito.mock(CacheTypeDao.class); + when(mock.getByClassName(anyString())).thenReturn(new CacheType()); + ci.setCacheTypeDao(mock); + ci.setCache(new GeneralCache(null)); + + String cacheKey = "https://www.google.com/"; + String result = ci.getWebPageContent(cacheKey); + assertNotNull(result); + String cacheValue = ci.getCacheValue(cacheKey); + assertTrue(result.equals(cacheValue)); + } + + @Test + public void testSetNode() throws Exception { + CachableInterfaceMock ci = new CachableInterfaceMock(CachableInterface.class); + + CacheTypeDao mock = Mockito.mock(CacheTypeDao.class); + when(mock.getByClassName(anyString())).thenReturn(new CacheType()); + ci.setCacheTypeDao(mock); + + String xml = "<xml><child/></xml>"; + ci.setCache(new GeneralCache(null)); + ci.setCacheNode("id", super.getNodeFromXmlString(xml)); + + Node node = ci.getCacheNode("id"); + assertNotNull(node); + } + + @Test + public void testNewLinesGetWebPage() throws Exception { + CachableInterfaceMock ci = new CachableInterfaceMock(CachableInterface.class); + ci.setCache(null); + String result = ci.getWebPageContent("http://google.com/"); + assertNotNull(result); + assertTrue(result.contains("\n")); + } + @Test + public void testCleanHtml() throws Exception { + CachableInterfaceMock ci = new CachableInterfaceMock(CachableInterface.class); + String res = ci.cleanHtml("blabla <invalid_tag"); + assertEquals("blabla ", res); + } + @Test + public void testCleanHtml2() throws Exception { + CachableInterfaceMock ci = new CachableInterfaceMock(CachableInterface.class); + String res = ci.cleanHtml("blabla <valid_tag> etc"); + assertEquals("blabla etc", res); + } } diff --git a/annotation/src/test/java/lcsb/mapviewer/annotation/cache/GeneralCacheTest.java b/annotation/src/test/java/lcsb/mapviewer/annotation/cache/GeneralCacheTest.java index 6f758e78328c3e900221333418c6a1c37925a2d6..6f44000671bfaee844063ad910bc4ccb2d06cc37 100644 --- a/annotation/src/test/java/lcsb/mapviewer/annotation/cache/GeneralCacheTest.java +++ b/annotation/src/test/java/lcsb/mapviewer/annotation/cache/GeneralCacheTest.java @@ -1,15 +1,10 @@ package lcsb.mapviewer.annotation.cache; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import org.apache.logging.log4j.*; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.Test; +import static org.junit.Assert.*; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.junit.*; import org.springframework.beans.factory.annotation.Autowired; import lcsb.mapviewer.annotation.AnnotationTestFunctions; @@ -17,121 +12,78 @@ import lcsb.mapviewer.common.exception.InvalidArgumentException; import lcsb.mapviewer.model.cache.CacheType; public class GeneralCacheTest extends AnnotationTestFunctions { - Logger logger = LogManager.getLogger(GeneralCacheTest.class); - - GeneralCache cache = new GeneralCache(null); - - @Autowired - PermanentDatabaseLevelCacheInterface databaseLevelCache; - - @AfterClass - public static void tearDownAfterClass() throws Exception { - } - - @Before - public void setUp() throws Exception { - cache.setCache2(databaseLevelCache); - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testClear() { - QueryCacheInterface origianlCache = cache.getCache2(); - try { - CacheType type = new CacheType(); - type.setId(-1); - cache.setCache2(ApplicationLevelCache.getInstance()); - ApplicationLevelCache.getInstance().setCachedQuery("str", type, "val"); - assertNotNull(cache.getStringByQuery("str", type)); - cache.clearCache(); - assertNull(cache.getStringByQuery("str", type)); - } finally { - cache.setCache2(origianlCache); - } - } - - @Test - public void testGetXmlNodeByQueryForInvalidType() { - try { - cache.getXmlNodeByQuery("str", null); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - assertTrue(e.getMessage().contains("Cache type cannot be null")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testSetCachedQueryForInvalidType() { - try { - cache.setCachedQuery("str", null, null); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - assertTrue(e.getMessage().contains("Cache type cannot be null")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testRemoveByQueryForInvalidType() { - try { - cache.removeByQuery("str", null); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - assertTrue(e.getMessage().contains("Cache type cannot be null")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testInvalidateByQueryForInvalidType() { - try { - cache.invalidateByQuery("str", null); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - assertTrue(e.getMessage().contains("Cache type cannot be null")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - @Test - public void testGetStringByQueryForInvalidType() { - try { - cache.getStringByQuery("str", null); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - assertTrue(e.getMessage().contains("Cache type cannot be null")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - - @Test - public void testRemoveByQuery() { - try { - CacheType type = new CacheType(); - cache.setCachedQuery("str", type, "val"); - assertNotNull(cache.getStringByQuery("str", type)); - cache.removeByQuery("str", type); - assertNull(cache.getStringByQuery("str", type)); - } catch (InvalidArgumentException e) { - assertTrue(e.getMessage().contains("Cache type cannot be null")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } + Logger logger = LogManager.getLogger(GeneralCacheTest.class); + + GeneralCache cache = new GeneralCache(null); + + @Autowired + PermanentDatabaseLevelCacheInterface databaseLevelCache; + + @AfterClass + public static void tearDownAfterClass() throws Exception { + } + + @Before + public void setUp() throws Exception { + cache.setCache2(databaseLevelCache); + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testClear() { + QueryCacheInterface origianlCache = cache.getCache2(); + try { + CacheType type = new CacheType(); + type.setId(-1); + cache.setCache2(ApplicationLevelCache.getInstance()); + ApplicationLevelCache.getInstance().setCachedQuery("str", type, "val"); + assertNotNull(cache.getStringByQuery("str", type)); + cache.clearCache(); + assertNull(cache.getStringByQuery("str", type)); + } finally { + cache.setCache2(origianlCache); + } + } + + @Test(expected = InvalidArgumentException.class) + public void testGetXmlNodeByQueryForInvalidType() { + cache.getXmlNodeByQuery("str", null); + } + + @Test(expected = InvalidArgumentException.class) + public void testSetCachedQueryForInvalidType() { + cache.setCachedQuery("str", null, null); + } + + @Test(expected = InvalidArgumentException.class) + public void testRemoveByQueryForInvalidType() { + cache.removeByQuery("str", null); + } + + @Test(expected = InvalidArgumentException.class) + public void testInvalidateByQueryForInvalidType() { + cache.invalidateByQuery("str", null); + } + + @Test(expected = InvalidArgumentException.class) + public void testGetStringByQueryForInvalidType() { + cache.getStringByQuery("str", null); + } + + @Test + public void testRemoveByQuery() { + try { + CacheType type = new CacheType(); + cache.setCachedQuery("str", type, "val"); + assertNotNull(cache.getStringByQuery("str", type)); + cache.removeByQuery("str", type); + assertNull(cache.getStringByQuery("str", type)); + } catch (InvalidArgumentException e) { + assertTrue(e.getMessage().contains("Cache type cannot be null")); + } + } } diff --git a/annotation/src/test/java/lcsb/mapviewer/annotation/cache/GeneralCacheWithExclusionTest.java b/annotation/src/test/java/lcsb/mapviewer/annotation/cache/GeneralCacheWithExclusionTest.java index b728f586286ee7277a2294b0cdcc67b6fe800e25..57a077c6758a1032e018286e6fd5bbf9f9c3e12d 100644 --- a/annotation/src/test/java/lcsb/mapviewer/annotation/cache/GeneralCacheWithExclusionTest.java +++ b/annotation/src/test/java/lcsb/mapviewer/annotation/cache/GeneralCacheWithExclusionTest.java @@ -1,133 +1,110 @@ package lcsb.mapviewer.annotation.cache; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; -import org.apache.logging.log4j.*; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.Test; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.junit.*; import lcsb.mapviewer.annotation.AnnotationTestFunctions; import lcsb.mapviewer.common.exception.InvalidArgumentException; import lcsb.mapviewer.model.cache.CacheType; public class GeneralCacheWithExclusionTest extends AnnotationTestFunctions { - Logger logger = LogManager.getLogger(GeneralCacheWithExclusionTest.class); - - @AfterClass - public static void tearDownAfterClass() throws Exception { - } - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testConstructorWithInvalidParams() { - try { - new GeneralCacheWithExclusion(null, 1); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - assertTrue(e.getMessage().contains("Cache passed as argument cannot be null")); - } - } - - @Test - public void testExclusion() throws Exception { - try { - CacheType type = new CacheType(); - GeneralCache cache = new GeneralCache(null); - cache.setCache2(ApplicationLevelCache.getInstance()); - GeneralCacheWithExclusion cacheWithExclusion = new GeneralCacheWithExclusion(cache, 2); - - cacheWithExclusion.setCachedQuery("str", type, super.getNodeFromXmlString("<val/>")); - - // after two tries we should get the data that was set - assertNull(cacheWithExclusion.getXmlNodeByQuery("str", type)); - assertNull(cacheWithExclusion.getXmlNodeByQuery("str", type)); - assertNotNull(cacheWithExclusion.getXmlNodeByQuery("str", type)); - - } catch (InvalidArgumentException e) { - assertTrue(e.getMessage().contains("Cache passed as argument cannot be null")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testClear() throws Exception { - try { - CacheType type = new CacheType(); - GeneralCache cache = new GeneralCache(null); - cache.setCache2(ApplicationLevelCache.getInstance()); - GeneralCacheWithExclusion cacheWithExclusion = new GeneralCacheWithExclusion(cache, 0); - - cacheWithExclusion.setCachedQuery("str", type, super.getNodeFromXmlString("<val/>")); - - assertNotNull(cacheWithExclusion.getXmlNodeByQuery("str", type)); - cacheWithExclusion.clearCache(); - - assertNull(cacheWithExclusion.getXmlNodeByQuery("str", type)); - - } catch (InvalidArgumentException e) { - assertTrue(e.getMessage().contains("Cache passed as argument cannot be null")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testRemove() throws Exception { - try { - CacheType type = new CacheType(); - GeneralCache cache = new GeneralCache(null); - cache.setCache2(ApplicationLevelCache.getInstance()); - GeneralCacheWithExclusion cacheWithExclusion = new GeneralCacheWithExclusion(cache, 0); - - cacheWithExclusion.setCachedQuery("str", type, super.getNodeFromXmlString("<val/>")); - - - assertNotNull(cacheWithExclusion.getXmlNodeByQuery("str", type)); - cacheWithExclusion.removeByQuery("str", type); - - assertNull(cacheWithExclusion.getXmlNodeByQuery("str", type)); - - } catch (InvalidArgumentException e) { - assertTrue(e.getMessage().contains("Cache passed as argument cannot be null")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testInvalidate() throws Exception { - try { - CacheType type = new CacheType(); - GeneralCache cache = new GeneralCache(null); - cache.setCache2(ApplicationLevelCache.getInstance()); - GeneralCacheWithExclusion cacheWithExclusion = new GeneralCacheWithExclusion(cache, 0); - - cacheWithExclusion.setCachedQuery("str", type, super.getNodeFromXmlString("<val/>")); - cacheWithExclusion.invalidateByQuery("str", type); - - assertNull(cacheWithExclusion.getXmlNodeByQuery("str", type)); - } catch (InvalidArgumentException e) { - assertTrue(e.getMessage().contains("Cache passed as argument cannot be null")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } + Logger logger = LogManager.getLogger(GeneralCacheWithExclusionTest.class); + + @AfterClass + public static void tearDownAfterClass() throws Exception { + } + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test(expected = InvalidArgumentException.class) + public void testConstructorWithInvalidParams() { + new GeneralCacheWithExclusion(null, 1); + } + + @Test + public void testExclusion() throws Exception { + try { + CacheType type = new CacheType(); + GeneralCache cache = new GeneralCache(null); + cache.setCache2(ApplicationLevelCache.getInstance()); + GeneralCacheWithExclusion cacheWithExclusion = new GeneralCacheWithExclusion(cache, 2); + + cacheWithExclusion.setCachedQuery("str", type, super.getNodeFromXmlString("<val/>")); + + // after two tries we should get the data that was set + assertNull(cacheWithExclusion.getXmlNodeByQuery("str", type)); + assertNull(cacheWithExclusion.getXmlNodeByQuery("str", type)); + assertNotNull(cacheWithExclusion.getXmlNodeByQuery("str", type)); + + } catch (InvalidArgumentException e) { + assertTrue(e.getMessage().contains("Cache passed as argument cannot be null")); + } + } + + @Test + public void testClear() throws Exception { + try { + CacheType type = new CacheType(); + GeneralCache cache = new GeneralCache(null); + cache.setCache2(ApplicationLevelCache.getInstance()); + GeneralCacheWithExclusion cacheWithExclusion = new GeneralCacheWithExclusion(cache, 0); + + cacheWithExclusion.setCachedQuery("str", type, super.getNodeFromXmlString("<val/>")); + + assertNotNull(cacheWithExclusion.getXmlNodeByQuery("str", type)); + cacheWithExclusion.clearCache(); + + assertNull(cacheWithExclusion.getXmlNodeByQuery("str", type)); + + } catch (InvalidArgumentException e) { + assertTrue(e.getMessage().contains("Cache passed as argument cannot be null")); + } + } + + @Test + public void testRemove() throws Exception { + try { + CacheType type = new CacheType(); + GeneralCache cache = new GeneralCache(null); + cache.setCache2(ApplicationLevelCache.getInstance()); + GeneralCacheWithExclusion cacheWithExclusion = new GeneralCacheWithExclusion(cache, 0); + + cacheWithExclusion.setCachedQuery("str", type, super.getNodeFromXmlString("<val/>")); + + assertNotNull(cacheWithExclusion.getXmlNodeByQuery("str", type)); + cacheWithExclusion.removeByQuery("str", type); + + assertNull(cacheWithExclusion.getXmlNodeByQuery("str", type)); + + } catch (InvalidArgumentException e) { + assertTrue(e.getMessage().contains("Cache passed as argument cannot be null")); + } + } + + @Test + public void testInvalidate() throws Exception { + try { + CacheType type = new CacheType(); + GeneralCache cache = new GeneralCache(null); + cache.setCache2(ApplicationLevelCache.getInstance()); + GeneralCacheWithExclusion cacheWithExclusion = new GeneralCacheWithExclusion(cache, 0); + + cacheWithExclusion.setCachedQuery("str", type, super.getNodeFromXmlString("<val/>")); + cacheWithExclusion.invalidateByQuery("str", type); + + assertNull(cacheWithExclusion.getXmlNodeByQuery("str", type)); + } catch (InvalidArgumentException e) { + assertTrue(e.getMessage().contains("Cache passed as argument cannot be null")); + } + } } diff --git a/annotation/src/test/java/lcsb/mapviewer/annotation/cache/PermanentDatabaseLevelCacheTest.java b/annotation/src/test/java/lcsb/mapviewer/annotation/cache/PermanentDatabaseLevelCacheTest.java index 1daf157577189f16914a4080c98b62b003f40a58..a20da355c6920d394ad2020cfec5c99572a9b3c6 100644 --- a/annotation/src/test/java/lcsb/mapviewer/annotation/cache/PermanentDatabaseLevelCacheTest.java +++ b/annotation/src/test/java/lcsb/mapviewer/annotation/cache/PermanentDatabaseLevelCacheTest.java @@ -1,20 +1,14 @@ package lcsb.mapviewer.annotation.cache; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; -import static org.mockito.Mockito.when; +import static org.junit.Assert.*; +import static org.mockito.Mockito.*; import java.util.Calendar; import org.apache.commons.lang3.mutable.MutableBoolean; -import org.apache.logging.log4j.*; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.junit.*; import org.mockito.Mockito; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; @@ -48,139 +42,108 @@ public class PermanentDatabaseLevelCacheTest extends AnnotationTestFunctions { @Test public void testByQuery() throws Exception { - try { - String xml = "<hello/>"; - String query = "blabla"; - - String xml2 = "<hello23/>"; + String xml = "<hello/>"; + String query = "blabla"; - CacheType type = cacheTypeDao.getByClassName(PubmedParser.class.getCanonicalName()); + String xml2 = "<hello23/>"; - Node sourceNode = getNodeFromXmlString(xml); - Node sourceNode2 = getNodeFromXmlString(xml2); - cache.removeByQuery(query, type); + CacheType type = cacheTypeDao.getByClassName(PubmedParser.class.getCanonicalName()); - Node node = cache.getXmlNodeByQuery(query, type); - assertNull(node); + Node sourceNode = getNodeFromXmlString(xml); + Node sourceNode2 = getNodeFromXmlString(xml2); + cache.removeByQuery(query, type); - cache.setCachedQuery(query, type, sourceNode); - node = cache.getXmlNodeByQuery(query, type); - assertNotNull(node); - assertEquals("hello", node.getNodeName()); + Node node = cache.getXmlNodeByQuery(query, type); + assertNull(node); - cache.setCachedQuery(query, type, sourceNode2); - node = cache.getXmlNodeByQuery(query, type); - assertNotNull(node); - assertEquals("hello23", node.getNodeName()); + cache.setCachedQuery(query, type, sourceNode); + node = cache.getXmlNodeByQuery(query, type); + assertNotNull(node); + assertEquals("hello", node.getNodeName()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + cache.setCachedQuery(query, type, sourceNode2); + node = cache.getXmlNodeByQuery(query, type); + assertNotNull(node); + assertEquals("hello23", node.getNodeName()); } - @Test + @Test(expected = CacheException.class) public void testSetInvalidQuery() { - try { - String query = "blabla"; - Object object = new Object(); - - CacheType type = cacheTypeDao.getByClassName(PubmedParser.class.getCanonicalName()); + String query = "blabla"; + Object object = new Object(); - cache.setCachedQuery(query, type, object); - fail("Exception expected"); + CacheType type = cacheTypeDao.getByClassName(PubmedParser.class.getCanonicalName()); - } catch (CacheException e) { - assertTrue(e.getMessage().contains("Unknown object type")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + cache.setCachedQuery(query, type, object); } @Test public void testGetInvalidXmlNode() { - try { - String query = "blabla"; - String object = "hello"; + String query = "blabla"; + String object = "hello"; - CacheType type = cacheTypeDao.getByClassName(PubmedParser.class.getCanonicalName()); + CacheType type = cacheTypeDao.getByClassName(PubmedParser.class.getCanonicalName()); - cache.setCachedQuery(query, type, object); - assertNull(cache.getXmlNodeByQuery(query, type)); + cache.setCachedQuery(query, type, object); + assertNull(cache.getXmlNodeByQuery(query, type)); - assertEquals(2, getWarnings().size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(2, getWarnings().size()); } @Test(timeout = 15000) public void testRefresh() throws Exception { - try { - CacheType invalidType = cacheTypeDao.getByClassName(MockCacheInterface.class.getCanonicalName()); - - String query = "test query"; - String val = "halo"; - dbUtils.createSessionForCurrentThread(); - cache.setCachedQuery(query, invalidType, val); - String res = cache.getStringByQuery(query, invalidType); - dbUtils.closeSessionForCurrentThread(); - assertNotNull(res); - // for the first time value should be the same (it's not valid but cache - // wasn't updated) - assertEquals(val, res); - // sleep a bit to wait for the second thread - permanentDatabaseLevelCache.waitToFinishTasks(); - // for the second time it should change - dbUtils.createSessionForCurrentThread(); - res = cache.getStringByQuery(query, invalidType); - dbUtils.closeSessionForCurrentThread(); - assertNotNull(res); - assertFalse(val.equals(res)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + CacheType invalidType = cacheTypeDao.getByClassName(MockCacheInterface.class.getCanonicalName()); + + String query = "test query"; + String val = "halo"; + dbUtils.createSessionForCurrentThread(); + cache.setCachedQuery(query, invalidType, val); + String res = cache.getStringByQuery(query, invalidType); + dbUtils.closeSessionForCurrentThread(); + assertNotNull(res); + // for the first time value should be the same (it's not valid but cache + // wasn't updated) + assertEquals(val, res); + // sleep a bit to wait for the second thread + permanentDatabaseLevelCache.waitToFinishTasks(); + // for the second time it should change + dbUtils.createSessionForCurrentThread(); + res = cache.getStringByQuery(query, invalidType); + dbUtils.closeSessionForCurrentThread(); + assertNotNull(res); + assertFalse(val.equals(res)); } @Test public void testRefreshNode() throws Exception { - try { - CacheType invalidType = cacheTypeDao.getByClassName(MockCacheInterface.class.getCanonicalName()); - - String query = "test query"; - String val = "<node><subnode>halo</subnode></node>"; - Node node = getNodeFromXmlString(val); - dbUtils.createSessionForCurrentThread(); - cache.setCachedQuery(query, invalidType, node); - Node res = cache.getXmlNodeByQuery(query, invalidType); - dbUtils.closeSessionForCurrentThread(); - - assertNotNull(res); - // sleep a bit to wait for the second thread - int counter = dbUtils.getSessionCounter(); - // wait until the other sql session finish - do { - Thread.sleep(100); - counter = dbUtils.getSessionCounter(); - } while (counter > 0); - Thread.sleep(1000); - // for the second time it should change - dbUtils.createSessionForCurrentThread(); - Node res2 = cache.getXmlNodeByQuery(query, invalidType); - dbUtils.closeSessionForCurrentThread(); - assertNotNull(res2); - - String strRes = nodeToString(res); - String strRes2 = nodeToString(res2); - assertFalse(strRes.equals(strRes2)); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + CacheType invalidType = cacheTypeDao.getByClassName(MockCacheInterface.class.getCanonicalName()); + + String query = "test query"; + String val = "<node><subnode>halo</subnode></node>"; + Node node = getNodeFromXmlString(val); + dbUtils.createSessionForCurrentThread(); + cache.setCachedQuery(query, invalidType, node); + Node res = cache.getXmlNodeByQuery(query, invalidType); + dbUtils.closeSessionForCurrentThread(); + + assertNotNull(res); + // sleep a bit to wait for the second thread + int counter = dbUtils.getSessionCounter(); + // wait until the other sql session finish + do { + Thread.sleep(100); + counter = dbUtils.getSessionCounter(); + } while (counter > 0); + Thread.sleep(1000); + // for the second time it should change + dbUtils.createSessionForCurrentThread(); + Node res2 = cache.getXmlNodeByQuery(query, invalidType); + dbUtils.closeSessionForCurrentThread(); + assertNotNull(res2); + + String strRes = nodeToString(res); + String strRes2 = nodeToString(res2); + assertFalse(strRes.equals(strRes2)); } @Test @@ -215,10 +178,6 @@ public class PermanentDatabaseLevelCacheTest extends AnnotationTestFunctions { // check if we have information in the logs about interruption (this is // not normal situaion) assertEquals(1, getErrors().size()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; } finally { cache.setCacheQueryDao(cacheQueryDao); } @@ -238,12 +197,8 @@ public class PermanentDatabaseLevelCacheTest extends AnnotationTestFunctions { cache.invalidateByQuery(query, invalidType); // check if we have information in the logs about interruption (this is - // not normal situaion) + // not normal situation) assertEquals(1, getErrors().size()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; } finally { cache.setCacheQueryDao(cacheQueryDao); } @@ -271,10 +226,6 @@ public class PermanentDatabaseLevelCacheTest extends AnnotationTestFunctions { cache.clearCache(); assertTrue(cleared.getValue()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; } finally { cache.setCacheQueryDao(cacheQueryDao); } @@ -304,12 +255,8 @@ public class PermanentDatabaseLevelCacheTest extends AnnotationTestFunctions { cache.invalidateByQuery(query, invalidType); cache.waitToFinishTasks(); - - assertEquals(1, getFatals().size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; + assertEquals(1, getFatals().size()); } finally { cache.setCacheQueryDao(cacheQueryDao); } @@ -340,12 +287,8 @@ public class PermanentDatabaseLevelCacheTest extends AnnotationTestFunctions { cache.invalidateByQuery(query, invalidType); cache.waitToFinishTasks(); - - assertEquals(1, getFatals().size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; + assertEquals(1, getFatals().size()); } finally { cache.setCacheQueryDao(cacheQueryDao); } @@ -376,10 +319,6 @@ public class PermanentDatabaseLevelCacheTest extends AnnotationTestFunctions { permanentDatabaseLevelCache.waitToFinishTasks(); assertEquals(1, getErrors().size()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; } finally { cache.setCacheQueryDao(cacheQueryDao); } @@ -411,10 +350,6 @@ public class PermanentDatabaseLevelCacheTest extends AnnotationTestFunctions { permanentDatabaseLevelCache.waitToFinishTasks(); assertEquals(0, getErrors().size()); assertEquals(0, getFatals().size()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; } finally { cache.setCacheQueryDao(cacheQueryDao); } @@ -448,10 +383,6 @@ public class PermanentDatabaseLevelCacheTest extends AnnotationTestFunctions { permanentDatabaseLevelCache.waitToFinishTasks(); assertEquals(1, getErrors().size()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; } finally { MockCacheInterface.exceptionToThrow = null; cache.setCacheQueryDao(cacheQueryDao); @@ -488,10 +419,6 @@ public class PermanentDatabaseLevelCacheTest extends AnnotationTestFunctions { // errors are not caught assertEquals(0, getErrors().size()); assertEquals(0, getFatals().size()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; } finally { MockCacheInterface.errorToThrow = null; cache.setCacheQueryDao(cacheQueryDao); diff --git a/annotation/src/test/java/lcsb/mapviewer/annotation/cache/WebPageDownloaderTest.java b/annotation/src/test/java/lcsb/mapviewer/annotation/cache/WebPageDownloaderTest.java index 65c6fb5f676007d9de9699e8b584c1d856d60346..ab41debd389d072b891f4133f3664b8bf1669a5b 100644 --- a/annotation/src/test/java/lcsb/mapviewer/annotation/cache/WebPageDownloaderTest.java +++ b/annotation/src/test/java/lcsb/mapviewer/annotation/cache/WebPageDownloaderTest.java @@ -1,98 +1,83 @@ package lcsb.mapviewer.annotation.cache; -import static org.junit.Assert.fail; -import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.*; import java.io.IOException; import java.net.HttpURLConnection; import java.net.UnknownHostException; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.mockito.Mockito; public class WebPageDownloaderTest { - @AfterClass - public static void tearDownAfterClass() throws Exception { - } + @AfterClass + public static void tearDownAfterClass() throws Exception { + } - @Before - public void setUp() throws Exception { - } + @Before + public void setUp() throws Exception { + } - @After - public void tearDown() throws Exception { - } + @After + public void tearDown() throws Exception { + } - @Test - public void testConnectionProblems() { - WebPageDownloader downloader = new WebPageDownloader() { - @Override - public HttpURLConnection openConnection(String url) throws IOException { - HttpURLConnection result = Mockito.mock(HttpURLConnection.class); - Mockito.doReturn(HttpURLConnection.HTTP_INTERNAL_ERROR).when(result).getResponseCode(); - Mockito.doThrow(new IOException()).when(result).getInputStream(); - return result; - } - }; - try { - downloader.getFromNetwork("https://www.google.pl/?gws_rd=ssl"); - fail("Exceptio expected"); - } catch (IOException e) { - } - } + @Test(expected = IOException.class) + public void testConnectionProblems() throws IOException { + WebPageDownloader downloader = new WebPageDownloader() { + @Override + public HttpURLConnection openConnection(String url) throws IOException { + HttpURLConnection result = Mockito.mock(HttpURLConnection.class); + Mockito.doReturn(HttpURLConnection.HTTP_INTERNAL_ERROR).when(result).getResponseCode(); + Mockito.doThrow(new IOException()).when(result).getInputStream(); + return result; + } + }; + downloader.getFromNetwork("https://www.google.pl/?gws_rd=ssl"); + } - @Test - public void testConnectionProblems2() { - WebPageDownloader downloader = new WebPageDownloader() { - @Override - public HttpURLConnection openConnection(String url) throws IOException { - HttpURLConnection result = Mockito.mock(HttpURLConnection.class); - Mockito.doReturn(HttpURLConnection.HTTP_OK).when(result).getResponseCode(); - Mockito.doThrow(new UnknownHostException()).when(result).getInputStream(); - return result; - } - }; - try { - downloader.getFromNetwork("https://www.google.pl/?gws_rd=ssl"); - fail("Exceptio expected"); - } catch (IOException e) { - } - } - - @Test - public void testSend1() { - WebPageDownloader downloader = new WebPageDownloader(); - try { - String result = downloader.getFromNetwork("https://www.google.com/"); - assertNotNull("GET request to Google should return non-null result", result); - } catch (IOException e) { - } - } - - @Test - public void testPost1() { - WebPageDownloader downloader = new WebPageDownloader(); - try { - String result = downloader.getFromNetwork("https://www.ebi.ac.uk/pdbe/api/mappings/best_structures/", "POST", "P29373"); - assertNotNull("POST request to Uniprot should return non-null result", result); - } catch (IOException e) { - } - - } - - @Test - public void testInvalidHttpRequestType() { - WebPageDownloader downloader = new WebPageDownloader(); - try { - downloader.getFromNetwork("https://www.ebi.ac.uk/pdbe/api/mappings/best_structures/", "XXX", "P29373"); - fail("Invalid request exception expected"); - } catch (IOException e) { - } - - } + @Test(expected = IOException.class) + public void testConnectionProblems2() throws IOException { + WebPageDownloader downloader = new WebPageDownloader() { + @Override + public HttpURLConnection openConnection(String url) throws IOException { + HttpURLConnection result = Mockito.mock(HttpURLConnection.class); + Mockito.doReturn(HttpURLConnection.HTTP_OK).when(result).getResponseCode(); + Mockito.doThrow(new UnknownHostException()).when(result).getInputStream(); + return result; + } + }; + downloader.getFromNetwork("https://www.google.pl/?gws_rd=ssl"); + } + + @Test + public void testSend1() { + WebPageDownloader downloader = new WebPageDownloader(); + try { + String result = downloader.getFromNetwork("https://www.google.com/"); + assertNotNull("GET request to Google should return non-null result", result); + } catch (IOException e) { + } + } + + @Test + public void testPost1() { + WebPageDownloader downloader = new WebPageDownloader(); + try { + String result = downloader.getFromNetwork("https://www.ebi.ac.uk/pdbe/api/mappings/best_structures/", "POST", + "P29373"); + assertNotNull("POST request to Uniprot should return non-null result", result); + } catch (IOException e) { + } + + } + + @Test(expected = IOException.class) + public void testInvalidHttpRequestType() throws IOException { + WebPageDownloader downloader = new WebPageDownloader(); + downloader.getFromNetwork("https://www.ebi.ac.uk/pdbe/api/mappings/best_structures/", "XXX", "P29373"); + + } } diff --git a/annotation/src/test/java/lcsb/mapviewer/annotation/data/ArticleTest.java b/annotation/src/test/java/lcsb/mapviewer/annotation/data/ArticleTest.java index 0b5bb7a5c0810d5c44ef035027cc74b73027b7c2..48d0eef61941f9e848ac4c3047aa2d5199ea4134 100644 --- a/annotation/src/test/java/lcsb/mapviewer/annotation/data/ArticleTest.java +++ b/annotation/src/test/java/lcsb/mapviewer/annotation/data/ArticleTest.java @@ -1,27 +1,22 @@ package lcsb.mapviewer.annotation.data; import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; -public class ArticleTest { +import lcsb.mapviewer.annotation.AnnotationTestFunctions; - @Before - public void setUp() throws Exception { - } +public class ArticleTest extends AnnotationTestFunctions { - @After - public void tearDown() throws Exception { - } + @Before + public void setUp() throws Exception { + } - @Test - public void testSerialization() { - try { - SerializationUtils.serialize(new Article()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } + @After + public void tearDown() throws Exception { + } + + @Test + public void testSerialization() { + SerializationUtils.serialize(new Article()); + } } diff --git a/annotation/src/test/java/lcsb/mapviewer/annotation/data/ChebiRelationTest.java b/annotation/src/test/java/lcsb/mapviewer/annotation/data/ChebiRelationTest.java index c7403c372c9ae584de68398b6650f4587e7980d3..82459bf549320daa02ec7e6d47e0af520a80db15 100644 --- a/annotation/src/test/java/lcsb/mapviewer/annotation/data/ChebiRelationTest.java +++ b/annotation/src/test/java/lcsb/mapviewer/annotation/data/ChebiRelationTest.java @@ -1,27 +1,22 @@ package lcsb.mapviewer.annotation.data; import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; -public class ChebiRelationTest { +import lcsb.mapviewer.annotation.AnnotationTestFunctions; - @Before - public void setUp() throws Exception { - } +public class ChebiRelationTest extends AnnotationTestFunctions { - @After - public void tearDown() throws Exception { - } + @Before + public void setUp() throws Exception { + } - @Test - public void testSerialization() { - try { - SerializationUtils.serialize(new ChebiRelation()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } + @After + public void tearDown() throws Exception { + } + + @Test + public void testSerialization() { + SerializationUtils.serialize(new ChebiRelation()); + } } diff --git a/annotation/src/test/java/lcsb/mapviewer/annotation/data/ChebiTest.java b/annotation/src/test/java/lcsb/mapviewer/annotation/data/ChebiTest.java index 12a9762e88276c4ea8644ed24d06506b5f271314..66427fec89729b3e218e3cf542d05bc9ec8bc790 100644 --- a/annotation/src/test/java/lcsb/mapviewer/annotation/data/ChebiTest.java +++ b/annotation/src/test/java/lcsb/mapviewer/annotation/data/ChebiTest.java @@ -1,69 +1,53 @@ package lcsb.mapviewer.annotation.data; -import static org.junit.Assert.assertEquals; +import static org.junit.Assert.*; import java.util.ArrayList; import java.util.List; import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; +import lcsb.mapviewer.annotation.AnnotationTestFunctions; import uk.ac.ebi.chebi.webapps.chebiWS.model.Entity; import uk.ac.ebi.chebi.webapps.chebiWS.model.OntologyDataItem; -public class ChebiTest { - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testSerialization() { - try { - SerializationUtils.serialize(new Chebi()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testGetters() { - try { - List<ChebiRelation> incomingChebi = new ArrayList<>(); - List<ChebiRelation> outgoingChebi = new ArrayList<>(); - List<String> synonyms = new ArrayList<>(); - Chebi chebi = new Chebi(); - chebi.setIncomingChebi(incomingChebi); - chebi.setOutgoingChebi(outgoingChebi); - chebi.setSynonyms(synonyms); - - assertEquals(incomingChebi, chebi.getIncomingChebi()); - assertEquals(outgoingChebi, chebi.getOutgoingChebi()); - assertEquals(synonyms, chebi.getSynonyms()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testConstructor() { - try { - Entity entity = new Entity(); - entity.getOntologyChildren().add(new OntologyDataItem()); - entity.setChebiAsciiName(""); - Chebi chebi = new Chebi(entity); - assertEquals(1, chebi.getOutgoingChebi().size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } +public class ChebiTest extends AnnotationTestFunctions { + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testSerialization() { + SerializationUtils.serialize(new Chebi()); + } + + @Test + public void testGetters() { + List<ChebiRelation> incomingChebi = new ArrayList<>(); + List<ChebiRelation> outgoingChebi = new ArrayList<>(); + List<String> synonyms = new ArrayList<>(); + Chebi chebi = new Chebi(); + chebi.setIncomingChebi(incomingChebi); + chebi.setOutgoingChebi(outgoingChebi); + chebi.setSynonyms(synonyms); + + assertEquals(incomingChebi, chebi.getIncomingChebi()); + assertEquals(outgoingChebi, chebi.getOutgoingChebi()); + assertEquals(synonyms, chebi.getSynonyms()); + } + + @Test + public void testConstructor() { + Entity entity = new Entity(); + entity.getOntologyChildren().add(new OntologyDataItem()); + entity.setChebiAsciiName(""); + Chebi chebi = new Chebi(entity); + assertEquals(1, chebi.getOutgoingChebi().size()); + } } diff --git a/annotation/src/test/java/lcsb/mapviewer/annotation/data/DrugTest.java b/annotation/src/test/java/lcsb/mapviewer/annotation/data/DrugTest.java index b4afe6785c2fd5f6e2b75756bbf2d94c57512360..f834d639f87480c69d221654bdcf27f85914326c 100644 --- a/annotation/src/test/java/lcsb/mapviewer/annotation/data/DrugTest.java +++ b/annotation/src/test/java/lcsb/mapviewer/annotation/data/DrugTest.java @@ -1,17 +1,12 @@ package lcsb.mapviewer.annotation.data; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.junit.Assert.*; import java.util.ArrayList; import java.util.List; import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import lcsb.mapviewer.annotation.AnnotationTestFunctions; import lcsb.mapviewer.annotation.services.TaxonomyBackend; @@ -20,99 +15,69 @@ import lcsb.mapviewer.model.map.MiriamType; public class DrugTest extends AnnotationTestFunctions { - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testSerialization() { - try { - SerializationUtils.serialize(new Drug()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testConstructor() { - try { - Drug d = new Drug(); - d.setDescription("x"); - Drug copy = new Drug(d); - assertEquals("x", copy.getDescription()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testConstructor2() { - try { - Drug d = new Drug(null); - assertNull(d.getName()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testToString() { - try { - Drug d = new Drug(); - d.addSynonym("Synonym"); - d.addBrandName("bname"); - d.addSource(new MiriamData(MiriamType.DRUGBANK, "xxx")); - Target target = new Target(); - target.setSource(new MiriamData()); - target.addReference(TaxonomyBackend.HUMAN_TAXONOMY); - d.addTarget(target); - - assertTrue(d.toString().contains("Synonym")); - assertFalse(d.toString().contains("bname")); - assertTrue(d.toString().contains("xxx")); - assertTrue(d.toString().contains(TaxonomyBackend.HUMAN_TAXONOMY.getResource())); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testAddSynonym() { - try { - Drug d = new Drug(); - d.addSynonym("Synonym"); - d.addSynonym("Synonym"); - - assertEquals(1, d.getSynonyms().size()); - assertEquals(1, getWarnings().size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testGetters() { - try { - Drug d = new Drug(); - List<Target> targets = new ArrayList<>(); - List<MiriamData> sources = new ArrayList<>(); - d.setTargets(targets); - d.setSources(sources); - - assertEquals(targets, d.getTargets()); - assertEquals(sources, d.getSources()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testSerialization() { + SerializationUtils.serialize(new Drug()); + } + + @Test + public void testConstructor() { + Drug d = new Drug(); + d.setDescription("x"); + Drug copy = new Drug(d); + assertEquals("x", copy.getDescription()); + } + + @Test + public void testConstructor2() { + Drug d = new Drug(null); + assertNull(d.getName()); + } + + @Test + public void testToString() { + Drug d = new Drug(); + d.addSynonym("Synonym"); + d.addBrandName("bname"); + d.addSource(new MiriamData(MiriamType.DRUGBANK, "xxx")); + Target target = new Target(); + target.setSource(new MiriamData()); + target.addReference(TaxonomyBackend.HUMAN_TAXONOMY); + d.addTarget(target); + + assertTrue(d.toString().contains("Synonym")); + assertFalse(d.toString().contains("bname")); + assertTrue(d.toString().contains("xxx")); + assertTrue(d.toString().contains(TaxonomyBackend.HUMAN_TAXONOMY.getResource())); + } + + @Test + public void testAddSynonym() { + Drug d = new Drug(); + d.addSynonym("Synonym"); + d.addSynonym("Synonym"); + + assertEquals(1, d.getSynonyms().size()); + assertEquals(1, getWarnings().size()); + } + + @Test + public void testGetters() { + Drug d = new Drug(); + List<Target> targets = new ArrayList<>(); + List<MiriamData> sources = new ArrayList<>(); + d.setTargets(targets); + d.setSources(sources); + + assertEquals(targets, d.getTargets()); + assertEquals(sources, d.getSources()); + } } diff --git a/annotation/src/test/java/lcsb/mapviewer/annotation/data/GoTest.java b/annotation/src/test/java/lcsb/mapviewer/annotation/data/GoTest.java index ba33f5bc6c7c491089ce5a4c2ba60f3a9cf35879..70deda84287404b22184eb56ec774df4fb18d75f 100644 --- a/annotation/src/test/java/lcsb/mapviewer/annotation/data/GoTest.java +++ b/annotation/src/test/java/lcsb/mapviewer/annotation/data/GoTest.java @@ -1,28 +1,22 @@ package lcsb.mapviewer.annotation.data; import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; -public class GoTest { +import lcsb.mapviewer.annotation.AnnotationTestFunctions; - @Before - public void setUp() throws Exception { - } +public class GoTest extends AnnotationTestFunctions { - @After - public void tearDown() throws Exception { - } + @Before + public void setUp() throws Exception { + } + @After + public void tearDown() throws Exception { + } - @Test - public void testSerialization() { - try { - SerializationUtils.serialize(new Go()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } + @Test + public void testSerialization() { + SerializationUtils.serialize(new Go()); + } } diff --git a/annotation/src/test/java/lcsb/mapviewer/annotation/data/MeSHTest.java b/annotation/src/test/java/lcsb/mapviewer/annotation/data/MeSHTest.java index d499ed1b2ffe9416f29851a308e42e589d6154c8..5a99ef7c1ee395f4a0622355f46a29f653f95ec3 100644 --- a/annotation/src/test/java/lcsb/mapviewer/annotation/data/MeSHTest.java +++ b/annotation/src/test/java/lcsb/mapviewer/annotation/data/MeSHTest.java @@ -1,90 +1,67 @@ package lcsb.mapviewer.annotation.data; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.Assert.*; import java.util.ArrayList; import java.util.List; import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.Test; - -public class MeSHTest { - - @AfterClass - public static void tearDownAfterClass() throws Exception { - } - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testSerialization() { - try { - SerializationUtils.serialize(new MeSH("is", "name", "desc", new ArrayList<>())); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testGetters() { - try { - MeSH mesh = new MeSH(); - List<String> synonyms = new ArrayList<>(); - - mesh.setSynonyms(synonyms); - - assertEquals(synonyms, mesh.getSynonyms()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testToString() { - try { - MeSH mesh = new MeSH("is", "nam3e", "des3c", new ArrayList<>()); - - String serial = mesh.toString(); - - assertTrue(serial.contains("is")); - assertTrue(serial.contains("nam3e")); - assertTrue(serial.contains("des3c")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testSynonymsToString() { - try { - MeSH mesh = new MeSH(); - - assertEquals("", mesh.getSynonymsString()); - - mesh.getSynonyms().add("synon"); - assertEquals("synon", mesh.getSynonymsString()); - - mesh.getSynonyms().add("bla"); - mesh.getSynonyms().add("qwe"); - assertEquals("synon,bla,qwe", mesh.getSynonymsString()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } +import org.junit.*; + +import lcsb.mapviewer.annotation.AnnotationTestFunctions; + +public class MeSHTest extends AnnotationTestFunctions { + + @AfterClass + public static void tearDownAfterClass() throws Exception { + } + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testSerialization() { + SerializationUtils.serialize(new MeSH("is", "name", "desc", new ArrayList<>())); + } + + @Test + public void testGetters() { + MeSH mesh = new MeSH(); + List<String> synonyms = new ArrayList<>(); + + mesh.setSynonyms(synonyms); + + assertEquals(synonyms, mesh.getSynonyms()); + } + + @Test + public void testToString() { + MeSH mesh = new MeSH("is", "nam3e", "des3c", new ArrayList<>()); + + String serial = mesh.toString(); + + assertTrue(serial.contains("is")); + assertTrue(serial.contains("nam3e")); + assertTrue(serial.contains("des3c")); + } + + @Test + public void testSynonymsToString() { + MeSH mesh = new MeSH(); + + assertEquals("", mesh.getSynonymsString()); + + mesh.getSynonyms().add("synon"); + assertEquals("synon", mesh.getSynonymsString()); + + mesh.getSynonyms().add("bla"); + mesh.getSynonyms().add("qwe"); + assertEquals("synon,bla,qwe", mesh.getSynonymsString()); + } } diff --git a/annotation/src/test/java/lcsb/mapviewer/annotation/data/TargetTest.java b/annotation/src/test/java/lcsb/mapviewer/annotation/data/TargetTest.java index 633ff9d56de6812748a7c94b9550ac8871458e94..c1f4d752acf0b2e6687374097cd2f44dacf9b01c 100644 --- a/annotation/src/test/java/lcsb/mapviewer/annotation/data/TargetTest.java +++ b/annotation/src/test/java/lcsb/mapviewer/annotation/data/TargetTest.java @@ -1,65 +1,44 @@ package lcsb.mapviewer.annotation.data; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import java.util.ArrayList; import java.util.List; import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; +import lcsb.mapviewer.annotation.AnnotationTestFunctions; import lcsb.mapviewer.common.exception.InvalidArgumentException; import lcsb.mapviewer.model.map.MiriamData; -public class TargetTest { +public class TargetTest extends AnnotationTestFunctions { - @Before - public void setUp() throws Exception { - } + @Before + public void setUp() throws Exception { + } - @After - public void tearDown() throws Exception { - } + @After + public void tearDown() throws Exception { + } - @Test - public void testSerialization() { - try { - SerializationUtils.serialize(new Target()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } + @Test + public void testSerialization() { + SerializationUtils.serialize(new Target()); + } - @Test - public void testGetters() { - try { - List<MiriamData> genes = new ArrayList<>(); - Target target = new Target(); - target.setGenes(genes); + @Test + public void testGetters() { + List<MiriamData> genes = new ArrayList<>(); + Target target = new Target(); + target.setGenes(genes); - assertEquals(genes, target.getGenes()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } + assertEquals(genes, target.getGenes()); + } - @Test - public void testAddInvalidGene() { - try { - Target target = new Target(); - target.addGene(null); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - assertTrue(e.getMessage().contains("Cannot add null element")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } + @Test(expected = InvalidArgumentException.class) + public void testAddInvalidGene() { + Target target = new Target(); + target.addGene(null); + } } diff --git a/annotation/src/test/java/lcsb/mapviewer/annotation/services/ChEMBLParserTest.java b/annotation/src/test/java/lcsb/mapviewer/annotation/services/ChEMBLParserTest.java index 95306e0c7791553ffd644e8f6a204a985623909f..ab6a62d96ff2e1c1aab1adfa0b59adf5fab749f8 100644 --- a/annotation/src/test/java/lcsb/mapviewer/annotation/services/ChEMBLParserTest.java +++ b/annotation/src/test/java/lcsb/mapviewer/annotation/services/ChEMBLParserTest.java @@ -1,44 +1,25 @@ package lcsb.mapviewer.annotation.services; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.ArgumentMatchers.nullable; -import static org.mockito.Mockito.when; +import static org.junit.Assert.*; +import static org.mockito.ArgumentMatchers.*; +import static org.mockito.Mockito.*; import java.io.IOException; -import java.util.ArrayList; -import java.util.List; -import java.util.Set; +import java.util.*; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.junit.Test; import org.mockito.Mockito; import org.springframework.beans.factory.annotation.Autowired; import org.w3c.dom.Node; import lcsb.mapviewer.annotation.AnnotationTestFunctions; -import lcsb.mapviewer.annotation.cache.GeneralCacheInterface; -import lcsb.mapviewer.annotation.cache.PermanentDatabaseLevelCacheInterface; -import lcsb.mapviewer.annotation.cache.SourceNotAvailable; -import lcsb.mapviewer.annotation.cache.WebPageDownloader; -import lcsb.mapviewer.annotation.cache.XmlSerializer; -import lcsb.mapviewer.annotation.data.Drug; -import lcsb.mapviewer.annotation.data.Target; -import lcsb.mapviewer.annotation.data.TargetType; -import lcsb.mapviewer.annotation.services.annotators.AnnotatorException; -import lcsb.mapviewer.annotation.services.annotators.HgncAnnotator; -import lcsb.mapviewer.annotation.services.annotators.UniprotAnnotator; -import lcsb.mapviewer.annotation.services.annotators.UniprotSearchException; +import lcsb.mapviewer.annotation.cache.*; +import lcsb.mapviewer.annotation.data.*; +import lcsb.mapviewer.annotation.services.annotators.*; import lcsb.mapviewer.common.exception.InvalidArgumentException; -import lcsb.mapviewer.model.map.MiriamData; -import lcsb.mapviewer.model.map.MiriamRelationType; -import lcsb.mapviewer.model.map.MiriamType; +import lcsb.mapviewer.model.map.*; public class ChEMBLParserTest extends AnnotationTestFunctions { Logger logger = LogManager.getLogger(ChEMBLParserTest.class); @@ -54,195 +35,134 @@ public class ChEMBLParserTest extends AnnotationTestFunctions { @Test public void test1FindDrug() throws Exception { - try { - Drug drug = chemblParser.findDrug("CABOZANTINIB"); - - assertEquals("CHEMBL2105717", drug.getSources().get(0).getResource()); - assertEquals("CABOZANTINIB", drug.getName()); - assertNull(drug.getDescription()); - assertEquals(2, drug.getTargets().size()); - List<String> lowerCaseSynonyms = new ArrayList<>(); - for (String s : drug.getSynonyms()) { - lowerCaseSynonyms.add(s.toLowerCase()); - } - assertTrue(lowerCaseSynonyms.contains("cabozantinib")); - assertTrue(drug.getApproved()); - } catch (Exception e) { - e.printStackTrace(); - throw e; + Drug drug = chemblParser.findDrug("CABOZANTINIB"); + + assertEquals("CHEMBL2105717", drug.getSources().get(0).getResource()); + assertEquals("CABOZANTINIB", drug.getName()); + assertNull(drug.getDescription()); + assertEquals(2, drug.getTargets().size()); + List<String> lowerCaseSynonyms = new ArrayList<>(); + for (String s : drug.getSynonyms()) { + lowerCaseSynonyms.add(s.toLowerCase()); } + assertTrue(lowerCaseSynonyms.contains("cabozantinib")); + assertTrue(drug.getApproved()); } @Test public void test2FindDrug() throws Exception { - try { - String n = "DIMETHYL FUMARATE"; - Drug test = chemblParser.findDrug(n); - - assertEquals("CHEMBL2107333", test.getSources().get(0).getResource()); - assertEquals("DIMETHYL FUMARATE", test.getName()); - // assertNull(test.getDescription()); - assertEquals(1, test.getTargets().size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String n = "DIMETHYL FUMARATE"; + Drug test = chemblParser.findDrug(n); + assertEquals("CHEMBL2107333", test.getSources().get(0).getResource()); + assertEquals("DIMETHYL FUMARATE", test.getName()); + // assertNull(test.getDescription()); + assertEquals(1, test.getTargets().size()); } @Test public void test3FindDrug() throws Exception { - try { - String n = "LOMITAPIDE"; - Drug test = chemblParser.findDrug(n); + String n = "LOMITAPIDE"; + Drug test = chemblParser.findDrug(n); - assertEquals("CHEMBL354541", test.getSources().get(0).getResource()); - assertEquals("LOMITAPIDE", test.getName()); - assertNull(test.getDescription()); - assertEquals(1, test.getTargets().size()); + assertEquals("CHEMBL354541", test.getSources().get(0).getResource()); + assertEquals("LOMITAPIDE", test.getName()); + assertNull(test.getDescription()); + assertEquals(1, test.getTargets().size()); - for (Target t : test.getTargets()) { - assertEquals(0, t.getReferences().size()); - } - } catch (Exception e) { - e.printStackTrace(); - throw e; + for (Target t : test.getTargets()) { + assertEquals(0, t.getReferences().size()); } - } @Test public void test4FindDrug() throws Exception { - try { - String n = "COBICISTAT"; - Drug test = chemblParser.findDrug(n); + String n = "COBICISTAT"; + Drug test = chemblParser.findDrug(n); - assertEquals("CHEMBL2095208", test.getSources().get(0).getResource()); - assertEquals("COBICISTAT", test.getName()); - assertNull(test.getDescription()); - assertEquals(1, test.getTargets().size()); + assertEquals("CHEMBL2095208", test.getSources().get(0).getResource()); + assertEquals("COBICISTAT", test.getName()); + assertNull(test.getDescription()); + assertEquals(1, test.getTargets().size()); - for (Target t : test.getTargets()) { - assertEquals(0, t.getReferences().size()); - } - } catch (Exception e) { - e.printStackTrace(); - throw e; + for (Target t : test.getTargets()) { + assertEquals(0, t.getReferences().size()); } - } @Test public void test5FindDrug() throws Exception { - try { - String n = "TALIGLUCERASE ALFA"; - Drug test = chemblParser.findDrug(n); + String n = "TALIGLUCERASE ALFA"; + Drug test = chemblParser.findDrug(n); - assertEquals("CHEMBL1964120", test.getSources().get(0).getResource()); - assertEquals("TALIGLUCERASE ALFA", test.getName()); - assertNull(test.getDescription()); - assertEquals(1, test.getTargets().size()); + assertEquals("CHEMBL1964120", test.getSources().get(0).getResource()); + assertEquals("TALIGLUCERASE ALFA", test.getName()); + assertNull(test.getDescription()); + assertEquals(1, test.getTargets().size()); - for (Target t : test.getTargets()) { - assertEquals(0, t.getReferences().size()); - } - } catch (Exception e) { - e.printStackTrace(); - throw e; + for (Target t : test.getTargets()) { + assertEquals(0, t.getReferences().size()); } - } @Test public void test6FindDrug() throws Exception { - try { - String n = "ABIRATERONE ACETATE"; - Drug test = chemblParser.findDrug(n); + String n = "ABIRATERONE ACETATE"; + Drug test = chemblParser.findDrug(n); - assertEquals("CHEMBL271227", test.getSources().get(0).getResource()); - assertEquals("ABIRATERONE ACETATE", test.getName()); - assertNull(test.getDescription()); - assertEquals(1, test.getTargets().size()); + assertEquals("CHEMBL271227", test.getSources().get(0).getResource()); + assertEquals("ABIRATERONE ACETATE", test.getName()); + assertNull(test.getDescription()); + assertEquals(1, test.getTargets().size()); - for (Target t : test.getTargets()) { - assertEquals(0, t.getReferences().size()); - } - } catch (Exception e) { - e.printStackTrace(); - throw e; + for (Target t : test.getTargets()) { + assertEquals(0, t.getReferences().size()); } - } @Test public void test7FindDrug() throws Exception { - try { - String n = "asdwrgwedas"; - Drug test = chemblParser.findDrug(n); - assertNull(test); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - + String n = "asdwrgwedas"; + Drug test = chemblParser.findDrug(n); + assertNull(test); } @Test public void test8FindDrug() throws Exception { - try { - String n = "aa a32"; - Drug test = chemblParser.findDrug(n); - assertNull(test); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - + String n = "aa a32"; + Drug test = chemblParser.findDrug(n); + assertNull(test); } @Test public void test9FindDrug() throws Exception { - try { - String name = "PONATINIB"; - Drug test = chemblParser.findDrug(name); - - assertEquals("CHEMBL1171837", test.getSources().get(0).getResource()); - assertEquals(name, test.getName()); - assertNull(test.getDescription()); - assertEquals(3, test.getTargets().size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String name = "PONATINIB"; + Drug test = chemblParser.findDrug(name); + assertEquals("CHEMBL1171837", test.getSources().get(0).getResource()); + assertEquals(name, test.getName()); + assertNull(test.getDescription()); + assertEquals(3, test.getTargets().size()); } @Test public void test10FindDrug() throws Exception { - try { - String n = "DEXAMETHASONE"; - Drug test = chemblParser.findDrug(n); - - assertEquals("CHEMBL384467", test.getSources().get(0).getResource()); - assertEquals("DEXAMETHASONE", test.getName()); - assertNull(test.getDescription()); - assertEquals(1, test.getTargets().size()); - - for (Target t : test.getTargets()) { - assertTrue(t.getReferences() - .contains(new MiriamData(MiriamRelationType.BQ_BIOL_IS_DESCRIBED_BY, MiriamType.PUBMED, "16891588"))); - assertTrue(t.getReferences() - .contains(new MiriamData(MiriamRelationType.BQ_BIOL_IS_DESCRIBED_BY, MiriamType.PUBMED, "16956592"))); - assertTrue(t.getReferences() - .contains(new MiriamData(MiriamRelationType.BQ_BIOL_IS_DESCRIBED_BY, MiriamType.PUBMED, "16971495"))); - } - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String n = "DEXAMETHASONE"; + Drug test = chemblParser.findDrug(n); + + assertEquals("CHEMBL384467", test.getSources().get(0).getResource()); + assertEquals("DEXAMETHASONE", test.getName()); + assertNull(test.getDescription()); + assertEquals(1, test.getTargets().size()); + for (Target t : test.getTargets()) { + assertTrue(t.getReferences() + .contains(new MiriamData(MiriamRelationType.BQ_BIOL_IS_DESCRIBED_BY, MiriamType.PUBMED, "16891588"))); + assertTrue(t.getReferences() + .contains(new MiriamData(MiriamRelationType.BQ_BIOL_IS_DESCRIBED_BY, MiriamType.PUBMED, "16956592"))); + assertTrue(t.getReferences() + .contains(new MiriamData(MiriamRelationType.BQ_BIOL_IS_DESCRIBED_BY, MiriamType.PUBMED, "16971495"))); + } } /** @@ -251,55 +171,35 @@ public class ChEMBLParserTest extends AnnotationTestFunctions { */ @Test public void test1getTargetFromId() throws Exception { - try { - Target test = chemblParser.getTargetFromId(new MiriamData(MiriamType.CHEMBL_TARGET, "CHEMBL3717")); - - assertEquals(test.getSource().getResource(), "CHEMBL3717"); - assertEquals(test.getName(), "Hepatocyte growth factor receptor"); - assertEquals(test.getOrganism().getResource(), "9606"); - assertEquals(TargetType.SINGLE_PROTEIN, test.getType()); - boolean contains = false; - for (MiriamData md : test.getGenes()) { - if (md.getResource().equals("MET")) { - contains = true; - } + Target test = chemblParser.getTargetFromId(new MiriamData(MiriamType.CHEMBL_TARGET, "CHEMBL3717")); + + assertEquals(test.getSource().getResource(), "CHEMBL3717"); + assertEquals(test.getName(), "Hepatocyte growth factor receptor"); + assertEquals(test.getOrganism().getResource(), "9606"); + assertEquals(TargetType.SINGLE_PROTEIN, test.getType()); + boolean contains = false; + for (MiriamData md : test.getGenes()) { + if (md.getResource().equals("MET")) { + contains = true; } - assertTrue(contains); - assertEquals(0, test.getReferences().size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; } - + assertTrue(contains); + assertEquals(0, test.getReferences().size()); } @Test public void testGetTargetWithRnaComponent() throws Exception { - try { - Target test = chemblParser.getTargetFromId(new MiriamData(MiriamType.CHEMBL_TARGET, "CHEMBL2363135")); - - assertEquals(test.getSource().getResource(), "CHEMBL2363135"); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Target test = chemblParser.getTargetFromId(new MiriamData(MiriamType.CHEMBL_TARGET, "CHEMBL2363135")); + assertEquals(test.getSource().getResource(), "CHEMBL2363135"); } - @Test + @Test(expected = InvalidArgumentException.class) public void testGetTargetFromInvalidId() throws Exception { - try { - chemblParser.getTargetFromId(new MiriamData(MiriamType.WIKIPEDIA, "water")); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - + chemblParser.getTargetFromId(new MiriamData(MiriamType.WIKIPEDIA, "water")); } - @Test + @Test(expected = DrugSearchException.class) public void testGetTargetFromIdWhenProblemWithDbConnection() throws Exception { WebPageDownloader downloader = chemblParser.getWebPageDownloader(); try { @@ -308,12 +208,6 @@ public class ChEMBLParserTest extends AnnotationTestFunctions { when(mockDownloader.getFromNetwork(anyString(), anyString(), nullable(String.class))).thenReturn("invalid xml"); chemblParser.setWebPageDownloader(mockDownloader); chemblParser.getTargetFromId(new MiriamData(MiriamType.CHEMBL_TARGET, "water")); - fail("Exception expected"); - } catch (DrugSearchException e) { - assertTrue(e.getMessage().contains("Problem with accessing information about target")); - } catch (Exception e) { - e.printStackTrace(); - throw e; } finally { chemblParser.setCache(cache); chemblParser.setWebPageDownloader(downloader); @@ -321,7 +215,7 @@ public class ChEMBLParserTest extends AnnotationTestFunctions { } - @Test + @Test(expected = DrugSearchException.class) public void testFindDrugWhenProblemWithDbConnection() throws Exception { WebPageDownloader downloader = chemblParser.getWebPageDownloader(); try { @@ -330,12 +224,6 @@ public class ChEMBLParserTest extends AnnotationTestFunctions { when(mockDownloader.getFromNetwork(anyString(), anyString(), nullable(String.class))).thenReturn("invalid xml"); chemblParser.setWebPageDownloader(mockDownloader); chemblParser.findDrug("test"); - fail("Exception expected"); - } catch (DrugSearchException e) { - assertTrue(e.getMessage().contains("Problem with parsing data from CHEMBL database")); - } catch (Exception e) { - e.printStackTrace(); - throw e; } finally { chemblParser.setCache(cache); chemblParser.setWebPageDownloader(downloader); @@ -343,21 +231,16 @@ public class ChEMBLParserTest extends AnnotationTestFunctions { } - @Test + @Test(expected = DrugSearchException.class) public void testGetTargetFromIdWhenProblemWithDbConnection2() throws Exception { WebPageDownloader downloader = chemblParser.getWebPageDownloader(); try { chemblParser.setCache(null); WebPageDownloader mockDownloader = Mockito.mock(WebPageDownloader.class); - when(mockDownloader.getFromNetwork(anyString(), anyString(), nullable(String.class))).thenThrow(new IOException()); + when(mockDownloader.getFromNetwork(anyString(), anyString(), nullable(String.class))) + .thenThrow(new IOException()); chemblParser.setWebPageDownloader(mockDownloader); chemblParser.getTargetFromId(new MiriamData(MiriamType.CHEMBL_TARGET, "water")); - fail("Exception expected"); - } catch (DrugSearchException e) { - assertTrue(e.getMessage().contains("Problem with accessing information about target")); - } catch (Exception e) { - e.printStackTrace(); - throw e; } finally { chemblParser.setCache(cache); chemblParser.setWebPageDownloader(downloader); @@ -365,7 +248,7 @@ public class ChEMBLParserTest extends AnnotationTestFunctions { } - @Test + @Test(expected = DrugSearchException.class) public void testGetTargetFromIdWhenProblemWithUniprot() throws Exception { UniprotAnnotator uniprotAnnotator = chemblParser.getUniprotAnnotator(); @@ -374,18 +257,13 @@ public class ChEMBLParserTest extends AnnotationTestFunctions { when(mockAnnotator.uniProtToHgnc(any())).thenThrow(new UniprotSearchException(null, null)); chemblParser.setUniprotAnnotator(mockAnnotator); chemblParser.getTargetFromId(new MiriamData(MiriamType.CHEMBL_TARGET, "CHEMBL3717")); - fail("Exception expected"); - } catch (DrugSearchException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; } finally { chemblParser.setUniprotAnnotator(uniprotAnnotator); } } - @Test + @Test(expected = DrugSearchException.class) public void testGetTargetFromIdWhenProblemWithTaxonomy() throws Exception { TaxonomyBackend taxonomyBackend = chemblParser.getTaxonomyBackend(); @@ -394,11 +272,6 @@ public class ChEMBLParserTest extends AnnotationTestFunctions { when(mockAnnotator.getNameForTaxonomy(any())).thenThrow(new TaxonomySearchException(null, null)); chemblParser.setTaxonomyBackend(mockAnnotator); chemblParser.getTargetFromId(new MiriamData(MiriamType.CHEMBL_TARGET, "CHEMBL3717")); - fail("Exception expected"); - } catch (DrugSearchException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; } finally { chemblParser.setTaxonomyBackend(taxonomyBackend); } @@ -411,13 +284,11 @@ public class ChEMBLParserTest extends AnnotationTestFunctions { try { chemblParser.setCache(null); WebPageDownloader mockDownloader = Mockito.mock(WebPageDownloader.class); - when(mockDownloader.getFromNetwork(anyString(), anyString(), nullable(String.class))).thenReturn("<target><unk/></target>"); + when(mockDownloader.getFromNetwork(anyString(), anyString(), nullable(String.class))) + .thenReturn("<target><unk/></target>"); chemblParser.setWebPageDownloader(mockDownloader); chemblParser.getTargetFromId(new MiriamData(MiriamType.CHEMBL_TARGET, "water")); assertEquals(1, getWarnings().size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; } finally { chemblParser.setCache(cache); chemblParser.setWebPageDownloader(downloader); @@ -435,9 +306,6 @@ public class ChEMBLParserTest extends AnnotationTestFunctions { chemblParser.setWebPageDownloader(mockDownloader); chemblParser.getTargetFromId(new MiriamData(MiriamType.CHEMBL_TARGET, "water")); assertEquals(1, getWarnings().size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; } finally { chemblParser.setCache(cache); chemblParser.setWebPageDownloader(downloader); @@ -455,9 +323,6 @@ public class ChEMBLParserTest extends AnnotationTestFunctions { chemblParser.setWebPageDownloader(mockDownloader); chemblParser.getTargetFromId(new MiriamData(MiriamType.CHEMBL_TARGET, "water")); assertEquals(1, getWarnings().size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; } finally { chemblParser.setCache(cache); chemblParser.setWebPageDownloader(downloader); @@ -466,140 +331,96 @@ public class ChEMBLParserTest extends AnnotationTestFunctions { @Test public void test2getTargetFromId() throws Exception { - try { - Target test = chemblParser.getTargetFromId(new MiriamData(MiriamType.CHEMBL_TARGET, "CHEMBL3522")); - - assertEquals(test.getSource().getResource(), "CHEMBL3522"); - assertEquals(test.getName(), "Cytochrome P450 17A1"); - assertEquals(test.getOrganism().getResource(), "9606"); - boolean contains = false; - for (MiriamData md : test.getGenes()) { - if (md.getResource().equals("CYP17A1")) { - contains = true; - } + Target test = chemblParser.getTargetFromId(new MiriamData(MiriamType.CHEMBL_TARGET, "CHEMBL3522")); + + assertEquals(test.getSource().getResource(), "CHEMBL3522"); + assertEquals(test.getName(), "Cytochrome P450 17A1"); + assertEquals(test.getOrganism().getResource(), "9606"); + boolean contains = false; + for (MiriamData md : test.getGenes()) { + if (md.getResource().equals("CYP17A1")) { + contains = true; } - assertTrue(contains); - assertEquals(0, test.getReferences().size()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; } - + assertTrue(contains); + assertEquals(0, test.getReferences().size()); } @Test public void test4getTargetFromId() throws Exception { - try { - Target test = chemblParser.getTargetFromId(new MiriamData(MiriamType.CHEMBL_TARGET, "CHEMBL2364681")); - - assertEquals(test.getSource().getResource(), "CHEMBL2364681"); - assertEquals(test.getName(), "Microsomal triglyceride transfer protein"); - assertEquals(test.getOrganism().getResource(), "9606"); - boolean contains = false; - boolean contains2 = false; - for (MiriamData md : test.getGenes()) { - if (md.getResource().equals("MTTP")) { - contains = true; - } - if (md.getResource().equals("P4HB")) { - contains2 = true; - } + Target test = chemblParser.getTargetFromId(new MiriamData(MiriamType.CHEMBL_TARGET, "CHEMBL2364681")); + + assertEquals(test.getSource().getResource(), "CHEMBL2364681"); + assertEquals(test.getName(), "Microsomal triglyceride transfer protein"); + assertEquals(test.getOrganism().getResource(), "9606"); + boolean contains = false; + boolean contains2 = false; + for (MiriamData md : test.getGenes()) { + if (md.getResource().equals("MTTP")) { + contains = true; + } + if (md.getResource().equals("P4HB")) { + contains2 = true; } - assertTrue(contains); - assertTrue(contains2); - assertEquals(0, test.getReferences().size()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; } - + assertTrue(contains); + assertTrue(contains2); + assertEquals(0, test.getReferences().size()); } @Test public void test5getTargetFromId() throws Exception { - try { - Target test = chemblParser.getTargetFromId(new MiriamData(MiriamType.CHEMBL_TARGET, "CHEMBL2364176")); - - assertEquals(test.getSource().getResource(), "CHEMBL2364176"); - assertEquals(test.getName(), "Glucocerebroside"); - assertEquals(test.getOrganism().getResource(), "9606"); - assertEquals(0, test.getGenes().size()); - assertEquals(0, test.getReferences().size()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Target test = chemblParser.getTargetFromId(new MiriamData(MiriamType.CHEMBL_TARGET, "CHEMBL2364176")); + assertEquals(test.getSource().getResource(), "CHEMBL2364176"); + assertEquals(test.getName(), "Glucocerebroside"); + assertEquals(test.getOrganism().getResource(), "9606"); + assertEquals(0, test.getGenes().size()); + assertEquals(0, test.getReferences().size()); } @Test public void test6getTargetFromId() throws Exception { - try { - Target test = chemblParser.getTargetFromId(new MiriamData(MiriamType.CHEMBL_TARGET, "CHEMBL2069156")); - - assertEquals(test.getSource().getResource(), "CHEMBL2069156"); - assertEquals(test.getName(), "Kelch-like ECH-associated protein 1"); - assertEquals(test.getOrganism().getResource(), "9606"); - boolean contains = false; - for (MiriamData md : test.getGenes()) { - if (md.getResource().equals("KEAP1")) { - contains = true; - } + Target test = chemblParser.getTargetFromId(new MiriamData(MiriamType.CHEMBL_TARGET, "CHEMBL2069156")); + + assertEquals(test.getSource().getResource(), "CHEMBL2069156"); + assertEquals(test.getName(), "Kelch-like ECH-associated protein 1"); + assertEquals(test.getOrganism().getResource(), "9606"); + boolean contains = false; + for (MiriamData md : test.getGenes()) { + if (md.getResource().equals("KEAP1")) { + contains = true; } - assertTrue(contains); - assertEquals(0, test.getReferences().size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; } - + assertTrue(contains); + assertEquals(0, test.getReferences().size()); } @Test public void testGetTargetsForAmantadine() throws Exception { - try { - Drug drug = chemblParser.findDrug("AMANTADINE"); - for (Target target : drug.getTargets()) { - assertEquals(0, target.getReferences().size()); - } - assertTrue(drug.getTargets().size() > 0); - - } catch (Exception e) { - e.printStackTrace(); - throw e; + Drug drug = chemblParser.findDrug("AMANTADINE"); + for (Target target : drug.getTargets()) { + assertEquals(0, target.getReferences().size()); } + assertTrue(drug.getTargets().size() > 0); } @Test public void testGetTargetsWithReferences() throws Exception { - try { - Drug drug = chemblParser.findDrug("TRIMETHOPRIM"); - for (Target target : drug.getTargets()) { - assertEquals(0, target.getReferences().size()); - } - assertTrue(drug.getTargets().size() > 0); - - } catch (Exception e) { - e.printStackTrace(); - throw e; + Drug drug = chemblParser.findDrug("TRIMETHOPRIM"); + for (Target target : drug.getTargets()) { + assertEquals(0, target.getReferences().size()); } + assertTrue(drug.getTargets().size() > 0); } @Test public void testFindDrugByInvalidHgncTarget() throws Exception { - try { - List<Drug> drugs = chemblParser.getDrugListByTarget(new MiriamData(MiriamType.HGNC_SYMBOL, "NR3B")); - assertNotNull(drugs); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + List<Drug> drugs = chemblParser.getDrugListByTarget(new MiriamData(MiriamType.HGNC_SYMBOL, "NR3B")); + assertNotNull(drugs); } - @Test + @Test(expected = DrugSearchException.class) public void testFindDrugByHgncWhenHgncCrash() throws Exception { HgncAnnotator hgncAnnotator = chemblParser.getHgncAnnotator(); try { @@ -607,11 +428,6 @@ public class ChEMBLParserTest extends AnnotationTestFunctions { when(mockAnnotator.hgncToUniprot(any())).thenThrow(new AnnotatorException("")); chemblParser.setHgncAnnotator(mockAnnotator); chemblParser.getDrugListByTarget(new MiriamData(MiriamType.HGNC_SYMBOL, "NR3B")); - fail("Exception expected"); - } catch (DrugSearchException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; } finally { chemblParser.setHgncAnnotator(hgncAnnotator); } @@ -619,220 +435,129 @@ public class ChEMBLParserTest extends AnnotationTestFunctions { @Test public void testFindDrugByHgncTargetWithManyUniprot() throws Exception { - try { - List<Drug> drugs = chemblParser.getDrugListByTarget(new MiriamData(MiriamType.HGNC_SYMBOL, "AKAP7")); - assertNotNull(drugs); - // we should have a warning that akap7 has more than one uniprot id - assertEquals(1, getWarnings().size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - + List<Drug> drugs = chemblParser.getDrugListByTarget(new MiriamData(MiriamType.HGNC_SYMBOL, "AKAP7")); + assertNotNull(drugs); + // we should have a warning that akap7 has more than one uniprot id + assertEquals(1, getWarnings().size()); } @Test public void testFindDrugByUniprotTarget() throws Exception { - try { - List<Drug> drugs = chemblParser.getDrugListByTarget(new MiriamData(MiriamType.UNIPROT, "O60391")); - assertTrue(drugs.size() > 0); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - + List<Drug> drugs = chemblParser.getDrugListByTarget(new MiriamData(MiriamType.UNIPROT, "O60391")); + assertTrue(drugs.size() > 0); } - @Test + @Test(expected = DrugSearchException.class) public void testFindDrugByInvalidTarget() throws Exception { - try { - chemblParser.getDrugListByTarget(new MiriamData(MiriamType.MESH_2012, "D010300")); - } catch (DrugSearchException e) { - assertTrue(e.getMessage().contains("Don't know how to process target of")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - + chemblParser.getDrugListByTarget(new MiriamData(MiriamType.MESH_2012, "D010300")); } @Test public void testFindDrugByHgncTarget() throws Exception { - try { - List<Drug> drugs = chemblParser.getDrugListByTarget(new MiriamData(MiriamType.HGNC_SYMBOL, "GRIN3B")); - assertNotNull(drugs); - assertTrue(drugs.size() > 0); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - + List<Drug> drugs = chemblParser.getDrugListByTarget(new MiriamData(MiriamType.HGNC_SYMBOL, "GRIN3B")); + assertNotNull(drugs); + assertTrue(drugs.size() > 0); } @Test public void testFindDrugByPFKMTarget() throws Exception { - try { - // this gene raised some errors at some point - List<Drug> drugs = chemblParser.getDrugListByTarget(new MiriamData(MiriamType.HGNC_SYMBOL, "PFKM")); - assertNotNull(drugs); - assertTrue(drugs.size() >= 0); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - + // this gene raised some errors at some point + List<Drug> drugs = chemblParser.getDrugListByTarget(new MiriamData(MiriamType.HGNC_SYMBOL, "PFKM")); + assertNotNull(drugs); + assertTrue(drugs.size() >= 0); } @Test public void testFindDrugsByHgncTargets() throws Exception { - try { - List<Drug> drugs = chemblParser.getDrugListByTarget(new MiriamData(MiriamType.HGNC_SYMBOL, "GRIN3B")); - List<Drug> drugs2 = chemblParser.getDrugListByTarget(new MiriamData(MiriamType.HGNC_SYMBOL, "GRIN3A")); - List<MiriamData> hgnc = new ArrayList<MiriamData>(); - hgnc.add(new MiriamData(MiriamType.HGNC_SYMBOL, "GRIN3B")); - hgnc.add(new MiriamData(MiriamType.HGNC_SYMBOL, "GRIN3A")); - List<Drug> drugs3 = chemblParser.getDrugListByTargets(hgnc); - assertNotNull(drugs3); - assertTrue(drugs.size() + drugs2.size() > drugs3.size()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - + List<Drug> drugs = chemblParser.getDrugListByTarget(new MiriamData(MiriamType.HGNC_SYMBOL, "GRIN3B")); + List<Drug> drugs2 = chemblParser.getDrugListByTarget(new MiriamData(MiriamType.HGNC_SYMBOL, "GRIN3A")); + List<MiriamData> hgnc = new ArrayList<MiriamData>(); + hgnc.add(new MiriamData(MiriamType.HGNC_SYMBOL, "GRIN3B")); + hgnc.add(new MiriamData(MiriamType.HGNC_SYMBOL, "GRIN3A")); + List<Drug> drugs3 = chemblParser.getDrugListByTargets(hgnc); + assertNotNull(drugs3); + assertTrue(drugs.size() + drugs2.size() > drugs3.size()); } @Test public void testFindDrugByHgncTargetAndFilteredOutByOrganism() throws Exception { - try { - List<MiriamData> organisms = new ArrayList<>(); - organisms.add(new MiriamData(MiriamType.TAXONOMY, "-1")); - List<Drug> drugs = chemblParser.getDrugListByTarget(new MiriamData(MiriamType.HGNC_SYMBOL, "GRIN3B"), organisms); - assertNotNull(drugs); - assertEquals("No drugs for this organisms should be found", 0, drugs.size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + List<MiriamData> organisms = new ArrayList<>(); + organisms.add(new MiriamData(MiriamType.TAXONOMY, "-1")); + List<Drug> drugs = chemblParser.getDrugListByTarget(new MiriamData(MiriamType.HGNC_SYMBOL, "GRIN3B"), organisms); + assertNotNull(drugs); + assertEquals("No drugs for this organisms should be found", 0, drugs.size()); } @Test public void testFindDrugByHgncTargetAndFilteredByOrganism() throws Exception { - try { - List<MiriamData> organisms = new ArrayList<>(); - organisms.add(TaxonomyBackend.HUMAN_TAXONOMY); - List<Drug> drugs = chemblParser.getDrugListByTarget(new MiriamData(MiriamType.HGNC_SYMBOL, "GRIN3B"), organisms); - assertNotNull(drugs); - assertTrue(drugs.size() > 0); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + List<MiriamData> organisms = new ArrayList<>(); + organisms.add(TaxonomyBackend.HUMAN_TAXONOMY); + List<Drug> drugs = chemblParser.getDrugListByTarget(new MiriamData(MiriamType.HGNC_SYMBOL, "GRIN3B"), organisms); + assertNotNull(drugs); + assertTrue(drugs.size() > 0); } @Test public void testFindDrugsByRepeatingHgncTargets() throws Exception { - try { - List<Drug> drugs = chemblParser.getDrugListByTarget(new MiriamData(MiriamType.HGNC_SYMBOL, "GRIN3B")); - List<MiriamData> hgnc = new ArrayList<MiriamData>(); - hgnc.add(new MiriamData(MiriamType.HGNC_SYMBOL, "GRIN3B")); - hgnc.add(new MiriamData(MiriamType.HGNC_SYMBOL, "GRIN3B")); - hgnc.add(new MiriamData(MiriamType.HGNC_SYMBOL, "GRIN3B")); - List<Drug> drugs3 = chemblParser.getDrugListByTargets(hgnc); - assertNotNull(drugs3); - assertEquals(drugs.size(), drugs3.size()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - + List<Drug> drugs = chemblParser.getDrugListByTarget(new MiriamData(MiriamType.HGNC_SYMBOL, "GRIN3B")); + List<MiriamData> hgnc = new ArrayList<MiriamData>(); + hgnc.add(new MiriamData(MiriamType.HGNC_SYMBOL, "GRIN3B")); + hgnc.add(new MiriamData(MiriamType.HGNC_SYMBOL, "GRIN3B")); + hgnc.add(new MiriamData(MiriamType.HGNC_SYMBOL, "GRIN3B")); + List<Drug> drugs3 = chemblParser.getDrugListByTargets(hgnc); + assertNotNull(drugs3); + assertEquals(drugs.size(), drugs3.size()); } @Test public void testCachableInterfaceInvalidateUrl() throws Exception { String query = "http://google.lu/"; String newRes = "hello"; - try { - cache.setCachedQuery(query, chemblParser.getCacheType(), newRes); - cache.invalidateByQuery(query, chemblParser.getCacheType()); + cache.setCachedQuery(query, chemblParser.getCacheType(), newRes); + cache.invalidateByQuery(query, chemblParser.getCacheType()); - permanentDatabaseLevelCache.waitToFinishTasks(); + permanentDatabaseLevelCache.waitToFinishTasks(); - String res = cache.getStringByQuery(query, chemblParser.getCacheType()); + String res = cache.getStringByQuery(query, chemblParser.getCacheType()); - assertNotNull(res); + assertNotNull(res); - assertFalse("Value wasn't refreshed from db", newRes.equals(res)); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertFalse("Value wasn't refreshed from db", newRes.equals(res)); } - // wait max 15 second @Test(timeout = 15000) public void testCachableInterfaceInvalidateDrug() throws Exception { String query = ChEMBLParser.NAME_PREFIX + "TRIMETHOPRIM"; String newRes = "hello"; - try { - cache.setCachedQuery(query, chemblParser.getCacheType(), newRes); - cache.invalidateByQuery(query, chemblParser.getCacheType()); + cache.setCachedQuery(query, chemblParser.getCacheType(), newRes); + cache.invalidateByQuery(query, chemblParser.getCacheType()); - permanentDatabaseLevelCache.waitToFinishTasks(); + permanentDatabaseLevelCache.waitToFinishTasks(); - String res = cache.getStringByQuery(query, chemblParser.getCacheType()); + String res = cache.getStringByQuery(query, chemblParser.getCacheType()); - assertNotNull(res); + assertNotNull(res); - assertFalse("Value wasn't refreshed from db", newRes.equals(res)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertFalse("Value wasn't refreshed from db", newRes.equals(res)); } - @Test + @Test(expected = InvalidArgumentException.class) public void testRefreshInvalidCacheQuery() throws Exception { - try { - chemblParser.refreshCacheQuery("invalid_query"); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - assertTrue(e.getMessage().contains("Don't know what to do")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + chemblParser.refreshCacheQuery("invalid_query"); } - @Test + @Test(expected = InvalidArgumentException.class) public void testRefreshInvalidCacheQuery2() throws Exception { - try { - chemblParser.refreshCacheQuery(new Object()); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - assertTrue(e.getMessage().contains("Don't know what to do")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + chemblParser.refreshCacheQuery(new Object()); } @Test public void testRefreshCacheQuery() throws Exception { - try { - Object res = chemblParser.refreshCacheQuery("http://google.pl/"); - assertNotNull(res); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Object res = chemblParser.refreshCacheQuery("http://google.pl/"); + assertNotNull(res); } - @Test + @Test(expected = SourceNotAvailable.class) public void testRefreshCacheQueryNotAvailable() throws Exception { WebPageDownloader downloader = chemblParser.getWebPageDownloader(); GeneralCacheInterface cache = chemblParser.getCache(); @@ -842,21 +567,17 @@ public class ChEMBLParserTest extends AnnotationTestFunctions { // simulate problem with downloading WebPageDownloader mockDownloader = Mockito.mock(WebPageDownloader.class); - when(mockDownloader.getFromNetwork(anyString(), anyString(), nullable(String.class))).thenThrow(new IOException()); + when(mockDownloader.getFromNetwork(anyString(), anyString(), nullable(String.class))) + .thenThrow(new IOException()); chemblParser.setWebPageDownloader(mockDownloader); chemblParser.refreshCacheQuery("http://google.pl/"); - fail("Exception expected"); - } catch (SourceNotAvailable e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; } finally { chemblParser.setWebPageDownloader(downloader); chemblParser.setCache(cache); } } - @Test + @Test(expected = DrugSearchException.class) public void testGetDrugsByChemblTargetWhenChemblCrash() throws Exception { WebPageDownloader downloader = chemblParser.getWebPageDownloader(); GeneralCacheInterface cache = chemblParser.getCache(); @@ -866,23 +587,17 @@ public class ChEMBLParserTest extends AnnotationTestFunctions { // simulate problem with downloading WebPageDownloader mockDownloader = Mockito.mock(WebPageDownloader.class); - when(mockDownloader.getFromNetwork(anyString(), anyString(), nullable(String.class))).thenThrow(new IOException()); + when(mockDownloader.getFromNetwork(anyString(), anyString(), nullable(String.class))) + .thenThrow(new IOException()); chemblParser.setWebPageDownloader(mockDownloader); chemblParser.getDrugsByChemblTarget(new MiriamData()); - - fail("Exception expected"); - } catch (DrugSearchException e) { - assertEquals("Problem with accessing Chembl database", e.getMessage()); - } catch (Exception e) { - e.printStackTrace(); - throw e; } finally { chemblParser.setWebPageDownloader(downloader); chemblParser.setCache(cache); } } - @Test + @Test(expected = DrugSearchException.class) public void testGetDrugsByChemblTargetWhenChemblCrash2() throws Exception { WebPageDownloader downloader = chemblParser.getWebPageDownloader(); GeneralCacheInterface cache = chemblParser.getCache(); @@ -895,20 +610,13 @@ public class ChEMBLParserTest extends AnnotationTestFunctions { when(mockDownloader.getFromNetwork(anyString(), anyString(), nullable(String.class))).thenReturn(""); chemblParser.setWebPageDownloader(mockDownloader); chemblParser.getDrugsByChemblTarget(new MiriamData()); - - fail("Exception expected"); - } catch (DrugSearchException e) { - assertEquals("Problem with parsing Chembl response", e.getMessage()); - } catch (Exception e) { - e.printStackTrace(); - throw e; } finally { chemblParser.setWebPageDownloader(downloader); chemblParser.setCache(cache); } } - @Test + @Test(expected = SourceNotAvailable.class) public void testRefreshCacheQueryWhenChemblDbNotAvailable() throws Exception { String query = ChEMBLParser.NAME_PREFIX + "TRIMETHOPRIM"; @@ -920,14 +628,10 @@ public class ChEMBLParserTest extends AnnotationTestFunctions { // simulate problem with downloading WebPageDownloader mockDownloader = Mockito.mock(WebPageDownloader.class); - when(mockDownloader.getFromNetwork(anyString(), anyString(), nullable(String.class))).thenThrow(new IOException()); + when(mockDownloader.getFromNetwork(anyString(), anyString(), nullable(String.class))) + .thenThrow(new IOException()); chemblParser.setWebPageDownloader(mockDownloader); chemblParser.refreshCacheQuery(query); - fail("Exception expected"); - } catch (SourceNotAvailable e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; } finally { chemblParser.setWebPageDownloader(downloader); chemblParser.setCache(cache); @@ -936,12 +640,7 @@ public class ChEMBLParserTest extends AnnotationTestFunctions { @Test public void testStatus() throws Exception { - try { - assertEquals(ExternalServiceStatusType.OK, chemblParser.getServiceStatus().getStatus()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(ExternalServiceStatusType.OK, chemblParser.getServiceStatus().getStatus()); } @Test @@ -949,12 +648,10 @@ public class ChEMBLParserTest extends AnnotationTestFunctions { WebPageDownloader downloader = chemblParser.getWebPageDownloader(); try { WebPageDownloader mockDownloader = Mockito.mock(WebPageDownloader.class); - when(mockDownloader.getFromNetwork(anyString(), anyString(), nullable(String.class))).thenThrow(new IOException()); + when(mockDownloader.getFromNetwork(anyString(), anyString(), nullable(String.class))) + .thenThrow(new IOException()); chemblParser.setWebPageDownloader(mockDownloader); assertEquals(ExternalServiceStatusType.DOWN, chemblParser.getServiceStatus().getStatus()); - } catch (Exception e) { - e.printStackTrace(); - throw e; } finally { chemblParser.setWebPageDownloader(downloader); } @@ -969,9 +666,6 @@ public class ChEMBLParserTest extends AnnotationTestFunctions { .thenReturn("<response><molecules/></response>"); chemblParser.setWebPageDownloader(mockDownloader); assertEquals(ExternalServiceStatusType.CHANGED, chemblParser.getServiceStatus().getStatus()); - } catch (Exception e) { - e.printStackTrace(); - throw e; } finally { chemblParser.setWebPageDownloader(downloader); } @@ -984,14 +678,12 @@ public class ChEMBLParserTest extends AnnotationTestFunctions { WebPageDownloader mockDownloader = Mockito.mock(WebPageDownloader.class); // valid xml but with empty data - when(mockDownloader.getFromNetwork(anyString(), anyString(), nullable(String.class))).thenReturn("<response><molecules>" - + "<molecule><pref_name/><max_phase/><molecule_chembl_id/><molecule_synonyms/></molecule>" - + "</molecules><mechanisms/><molecule_forms/></response>"); + when(mockDownloader.getFromNetwork(anyString(), anyString(), nullable(String.class))) + .thenReturn("<response><molecules>" + + "<molecule><pref_name/><max_phase/><molecule_chembl_id/><molecule_synonyms/></molecule>" + + "</molecules><mechanisms/><molecule_forms/></response>"); chemblParser.setWebPageDownloader(mockDownloader); assertEquals(ExternalServiceStatusType.CHANGED, chemblParser.getServiceStatus().getStatus()); - } catch (Exception e) { - e.printStackTrace(); - throw e; } finally { chemblParser.setWebPageDownloader(downloader); } @@ -1005,19 +697,12 @@ public class ChEMBLParserTest extends AnnotationTestFunctions { assertEquals(drugSerializer, parser.getDrugSerializer()); } - @Test + @Test(expected = InvalidArgumentException.class) public void testGetTargetsByInvalidDrugId() throws Exception { - try { - chemblParser.getTargetsByDrugId(new MiriamData()); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + chemblParser.getTargetsByDrugId(new MiriamData()); } - @Test + @Test(expected = DrugSearchException.class) public void testGetTargetsByDrugIdWithExternalDbDown() throws Exception { WebPageDownloader downloader = chemblParser.getWebPageDownloader(); try { @@ -1026,51 +711,38 @@ public class ChEMBLParserTest extends AnnotationTestFunctions { when(mockDownloader.getFromNetwork(anyString(), anyString(), nullable(String.class))).thenReturn("invalid xml"); chemblParser.setWebPageDownloader(mockDownloader); chemblParser.getTargetsByDrugId(new MiriamData(MiriamType.CHEMBL_COMPOUND, "123")); - fail("Exception expected"); - } catch (DrugSearchException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; } finally { chemblParser.setWebPageDownloader(downloader); chemblParser.setCache(cache); } } - @Test + @Test(expected = DrugSearchException.class) public void testGetTargetsByDrugIdWithExternalDbDown2() throws Exception { WebPageDownloader downloader = chemblParser.getWebPageDownloader(); try { chemblParser.setCache(null); WebPageDownloader mockDownloader = Mockito.mock(WebPageDownloader.class); - when(mockDownloader.getFromNetwork(anyString(), anyString(), nullable(String.class))).thenThrow(new IOException()); + when(mockDownloader.getFromNetwork(anyString(), anyString(), nullable(String.class))) + .thenThrow(new IOException()); chemblParser.setWebPageDownloader(mockDownloader); chemblParser.getTargetsByDrugId(new MiriamData(MiriamType.CHEMBL_COMPOUND, "123")); - fail("Exception expected"); - } catch (DrugSearchException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; } finally { chemblParser.setWebPageDownloader(downloader); chemblParser.setCache(cache); } } - @Test + @Test(expected = DrugSearchException.class) public void testFindDrugByUniprotTargetWhenChemblCrash() throws Exception { WebPageDownloader downloader = chemblParser.getWebPageDownloader(); try { chemblParser.setCache(null); WebPageDownloader mockDownloader = Mockito.mock(WebPageDownloader.class); - when(mockDownloader.getFromNetwork(anyString(), anyString(), nullable(String.class))).thenThrow(new IOException()); + when(mockDownloader.getFromNetwork(anyString(), anyString(), nullable(String.class))) + .thenThrow(new IOException()); chemblParser.setWebPageDownloader(mockDownloader); chemblParser.getDrugListByTarget(new MiriamData(MiriamType.UNIPROT, "O60391")); - fail("Exception expected"); - } catch (DrugSearchException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; } finally { chemblParser.setWebPageDownloader(downloader); chemblParser.setCache(cache); @@ -1078,7 +750,7 @@ public class ChEMBLParserTest extends AnnotationTestFunctions { } - @Test + @Test(expected = DrugSearchException.class) public void testFindDrugByUniprotTargetWhenChemblCrash2() throws Exception { WebPageDownloader downloader = chemblParser.getWebPageDownloader(); try { @@ -1087,11 +759,6 @@ public class ChEMBLParserTest extends AnnotationTestFunctions { when(mockDownloader.getFromNetwork(anyString(), anyString(), nullable(String.class))).thenReturn("invalid xml"); chemblParser.setWebPageDownloader(mockDownloader); chemblParser.getDrugListByTarget(new MiriamData(MiriamType.UNIPROT, "O60391")); - fail("Exception expected"); - } catch (DrugSearchException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; } finally { chemblParser.setWebPageDownloader(downloader); chemblParser.setCache(cache); @@ -1101,45 +768,28 @@ public class ChEMBLParserTest extends AnnotationTestFunctions { @Test public void testParseReferences() throws Exception { - try { - Node node = super.getXmlDocumentFromFile("testFiles/chembl/references.xml"); - Set<MiriamData> references = chemblParser.parseReferences(node.getFirstChild()); - // we might have more references (if we decide to parse wikipedia, isbn, - // etc) - assertTrue(references.size() >= 3); - assertEquals(1, getWarnings().size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Node node = super.getXmlDocumentFromFile("testFiles/chembl/references.xml"); + Set<MiriamData> references = chemblParser.parseReferences(node.getFirstChild()); + // we might have more references (if we decide to parse wikipedia, isbn, + // etc) + assertTrue(references.size() >= 3); + assertEquals(1, getWarnings().size()); } @Test public void testParseReferencesWithSpecInId() throws Exception { - try { - Node node = super.getXmlDocumentFromFile("testFiles/chembl/references_with_space.xml"); - Set<MiriamData> references = chemblParser.parseReferences(node.getFirstChild()); - assertEquals(1, references.size()); - assertFalse(references.iterator().next().getResource().contains(" ")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Node node = super.getXmlDocumentFromFile("testFiles/chembl/references_with_space.xml"); + Set<MiriamData> references = chemblParser.parseReferences(node.getFirstChild()); + assertEquals(1, references.size()); + assertFalse(references.iterator().next().getResource().contains(" ")); } - @Test + @Test(expected = InvalidArgumentException.class) public void testGetDrugByInvalidDrugId() throws Exception { - try { - chemblParser.getDrugById(new MiriamData()); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + chemblParser.getDrugById(new MiriamData()); } - @Test + @Test(expected = DrugSearchException.class) public void testGetDrugByDrugIdWhenCehmblCrash() throws Exception { WebPageDownloader downloader = chemblParser.getWebPageDownloader(); try { @@ -1148,31 +798,22 @@ public class ChEMBLParserTest extends AnnotationTestFunctions { when(mockDownloader.getFromNetwork(anyString(), anyString(), nullable(String.class))).thenReturn("invalid xml"); chemblParser.setWebPageDownloader(mockDownloader); chemblParser.getDrugById(new MiriamData(MiriamType.CHEMBL_COMPOUND, "")); - fail("Exception expected"); - } catch (DrugSearchException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; } finally { chemblParser.setWebPageDownloader(downloader); chemblParser.setCache(cache); } } - @Test + @Test(expected = DrugSearchException.class) public void testGetDrugByDrugIdWhenChemblCrash2() throws Exception { WebPageDownloader downloader = chemblParser.getWebPageDownloader(); try { chemblParser.setCache(null); WebPageDownloader mockDownloader = Mockito.mock(WebPageDownloader.class); - when(mockDownloader.getFromNetwork(anyString(), anyString(), nullable(String.class))).thenThrow(new IOException()); + when(mockDownloader.getFromNetwork(anyString(), anyString(), nullable(String.class))) + .thenThrow(new IOException()); chemblParser.setWebPageDownloader(mockDownloader); chemblParser.getDrugById(new MiriamData(MiriamType.CHEMBL_COMPOUND, "")); - fail("Exception expected"); - } catch (DrugSearchException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; } finally { chemblParser.setWebPageDownloader(downloader); chemblParser.setCache(cache); @@ -1181,39 +822,30 @@ public class ChEMBLParserTest extends AnnotationTestFunctions { @Test public void testParseSynonymsNode() throws Exception { - try { - Node node = super.getNodeFromXmlString( - "<molecule_synonyms><synonym><synonyms>some synonym</synonyms></synonym><unknode/></molecule_synonyms>"); - List<String> synonyms = chemblParser.parseSynonymsNode(node); - assertEquals(1, synonyms.size()); - assertEquals(1, getWarnings().size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Node node = super.getNodeFromXmlString( + "<molecule_synonyms><synonym><synonyms>some synonym</synonyms></synonym><unknode/></molecule_synonyms>"); + List<String> synonyms = chemblParser.parseSynonymsNode(node); + assertEquals(1, synonyms.size()); + assertEquals(1, getWarnings().size()); } - @Test + @Test(expected = DrugSearchException.class) public void testGetTargetsForChildElementsWhenChemblCrash() throws Exception { WebPageDownloader downloader = chemblParser.getWebPageDownloader(); try { chemblParser.setCache(null); WebPageDownloader mockDownloader = Mockito.mock(WebPageDownloader.class); - when(mockDownloader.getFromNetwork(anyString(), anyString(), nullable(String.class))).thenThrow(new IOException()); + when(mockDownloader.getFromNetwork(anyString(), anyString(), nullable(String.class))) + .thenThrow(new IOException()); chemblParser.setWebPageDownloader(mockDownloader); chemblParser.getTargetsForChildElements(new MiriamData()); - fail("Exception expected"); - } catch (DrugSearchException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; } finally { chemblParser.setWebPageDownloader(downloader); chemblParser.setCache(cache); } } - @Test + @Test(expected = DrugSearchException.class) public void testGetTargetsForChildElementsWhenChemblCrash2() throws Exception { WebPageDownloader downloader = chemblParser.getWebPageDownloader(); try { @@ -1222,11 +854,6 @@ public class ChEMBLParserTest extends AnnotationTestFunctions { when(mockDownloader.getFromNetwork(anyString(), anyString(), nullable(String.class))).thenReturn("invalid xml"); chemblParser.setWebPageDownloader(mockDownloader); chemblParser.getTargetsForChildElements(new MiriamData()); - fail("Exception expected"); - } catch (DrugSearchException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; } finally { chemblParser.setWebPageDownloader(downloader); chemblParser.setCache(cache); @@ -1244,9 +871,6 @@ public class ChEMBLParserTest extends AnnotationTestFunctions { chemblParser.setWebPageDownloader(mockDownloader); chemblParser.getTargetsForChildElements(new MiriamData()); assertEquals(1, getWarnings().size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; } finally { chemblParser.setWebPageDownloader(downloader); chemblParser.setCache(cache); diff --git a/annotation/src/test/java/lcsb/mapviewer/annotation/services/ChemicalParserTest.java b/annotation/src/test/java/lcsb/mapviewer/annotation/services/ChemicalParserTest.java index f47ae7c9510f80baeb5e3ac9ab80bca71b4a805f..bb82811c857857c2672e159af13471f215cdf1cc 100644 --- a/annotation/src/test/java/lcsb/mapviewer/annotation/services/ChemicalParserTest.java +++ b/annotation/src/test/java/lcsb/mapviewer/annotation/services/ChemicalParserTest.java @@ -1,35 +1,23 @@ package lcsb.mapviewer.annotation.services; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.ArgumentMatchers.nullable; -import static org.mockito.Mockito.when; +import static org.junit.Assert.*; +import static org.mockito.ArgumentMatchers.*; +import static org.mockito.Mockito.*; import java.io.IOException; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; +import java.util.*; import org.apache.commons.lang3.math.NumberUtils; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.junit.Ignore; import org.junit.Test; import org.mockito.Mockito; import org.springframework.beans.factory.annotation.Autowired; import lcsb.mapviewer.annotation.AnnotationTestFunctions; -import lcsb.mapviewer.annotation.cache.GeneralCacheInterface; -import lcsb.mapviewer.annotation.cache.PermanentDatabaseLevelCacheInterface; -import lcsb.mapviewer.annotation.cache.SourceNotAvailable; -import lcsb.mapviewer.annotation.cache.WebPageDownloader; -import lcsb.mapviewer.annotation.data.Chemical; -import lcsb.mapviewer.annotation.data.ChemicalDirectEvidence; -import lcsb.mapviewer.annotation.data.Target; +import lcsb.mapviewer.annotation.cache.*; +import lcsb.mapviewer.annotation.data.*; import lcsb.mapviewer.annotation.services.annotators.AnnotatorException; import lcsb.mapviewer.annotation.services.annotators.HgncAnnotator; import lcsb.mapviewer.common.exception.InvalidArgumentException; @@ -62,19 +50,14 @@ public class ChemicalParserTest extends AnnotationTestFunctions { @Test public void testCreateChemicalListFromDB() throws Exception { - try { - // skip first call to cache, so we will have to at least parse the data - // Parkinson disease - Map<MiriamData, String> result = chemicalParser.getChemicalsForDisease(parkinsonDiseaseId); - assertNotNull(result); - assertTrue(!result.isEmpty()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + // skip first call to cache, so we will have to at least parse the data + // Parkinson disease + Map<MiriamData, String> result = chemicalParser.getChemicalsForDisease(parkinsonDiseaseId); + assertNotNull(result); + assertTrue(!result.isEmpty()); } - @Test + @Test(expected = ChemicalSearchException.class) public void testGetChemicalListWhenProblemWithConnection() throws Exception { GeneralCacheInterface cache = chemicalParser.getCache(); WebPageDownloader downloader = chemicalParser.getWebPageDownloader(); @@ -87,242 +70,155 @@ public class ChemicalParserTest extends AnnotationTestFunctions { chemicalParser.setWebPageDownloader(mockDownloader); // Parkinson disease chemicalParser.getChemicalsForDisease(parkinsonDiseaseId); - } catch (ChemicalSearchException e) { - assertTrue(e.getMessage().contains("ctdbase service unavailable")); - } catch (Exception e) { - e.printStackTrace(); - throw e; } finally { chemicalParser.setCache(cache); chemicalParser.setWebPageDownloader(downloader); } } - @Test + @Test(expected = InvalidArgumentException.class) public void testGetChemicalListForInvalidDiseaseId() throws Exception { - try { - chemicalParser.getChemicalsForDisease(null); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - assertTrue(e.getMessage().contains("disease cannot be null")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + chemicalParser.getChemicalsForDisease(null); } @Test public void testCreateChemicalListFromDBWithInvalidId() throws Exception { - try { - // Parkinson disease - MiriamData diseaseID = new MiriamData(MiriamType.MESH_2012, "D01030012"); - Map<MiriamData, String> result = chemicalParser.getChemicalsForDisease(diseaseID); - assertNotNull(result); - assertTrue(result.isEmpty()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + // Parkinson disease + MiriamData diseaseID = new MiriamData(MiriamType.MESH_2012, "D01030012"); + Map<MiriamData, String> result = chemicalParser.getChemicalsForDisease(diseaseID); + assertNotNull(result); + assertTrue(result.isEmpty()); } @Test public void testFindByIDFromChemicalList() throws Exception { - try { - - List<MiriamData> idsList = new ArrayList<>(); - idsList.add(stilbeneOxideChemicalId); - idsList.add(lazabemideChemicalId); - - List<Chemical> chemcials = chemicalParser.getChemicals(parkinsonDiseaseId, idsList); - assertEquals(idsList.size(), chemcials.size()); - for (Chemical chem : chemcials) { - assertNotNull(chem); - for (Target t : chem.getInferenceNetwork()) { - for (MiriamData md : t.getReferences()) { - assertEquals(MiriamType.PUBMED, md.getDataType()); - assertTrue(NumberUtils.isDigits(md.getResource())); - } + List<MiriamData> idsList = new ArrayList<>(); + idsList.add(stilbeneOxideChemicalId); + idsList.add(lazabemideChemicalId); + + List<Chemical> chemcials = chemicalParser.getChemicals(parkinsonDiseaseId, idsList); + assertEquals(idsList.size(), chemcials.size()); + for (Chemical chem : chemcials) { + assertNotNull(chem); + for (Target t : chem.getInferenceNetwork()) { + for (MiriamData md : t.getReferences()) { + assertEquals(MiriamType.PUBMED, md.getDataType()); + assertTrue(NumberUtils.isDigits(md.getResource())); } } - } catch (Exception e) { - e.printStackTrace(); - throw e; } - } @Test public void testGetGlutathioneDisulfideData() throws Exception { - try { + List<MiriamData> idsList = new ArrayList<>(); + idsList.add(glutathioneDisulfideChemicalId); + List<Chemical> chemicals = chemicalParser.getChemicals(parkinsonDiseaseId, idsList); - List<MiriamData> idsList = new ArrayList<>(); - idsList.add(glutathioneDisulfideChemicalId); - List<Chemical> chemicals = chemicalParser.getChemicals(parkinsonDiseaseId, idsList); - - assertEquals(1, chemicals.size()); - Chemical glutathioneDisulfide = chemicals.get(0); - - assertTrue(glutathioneDisulfide.getSynonyms().size() > 0); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(1, chemicals.size()); + Chemical glutathioneDisulfide = chemicals.get(0); + assertTrue(glutathioneDisulfide.getSynonyms().size() > 0); } @Test public void testGetChemicalBySynonym() throws Exception { - try { - String glutathioneDisulfideSynonym = "GSSG"; - List<Chemical> chemicals = chemicalParser.getChemicalsBySynonym(parkinsonDiseaseId, glutathioneDisulfideSynonym); + String glutathioneDisulfideSynonym = "GSSG"; + List<Chemical> chemicals = chemicalParser.getChemicalsBySynonym(parkinsonDiseaseId, glutathioneDisulfideSynonym); - assertEquals(1, chemicals.size()); - Chemical mptp = chemicals.get(0); - - assertTrue(mptp.getSynonyms().contains(glutathioneDisulfideSynonym)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(1, chemicals.size()); + Chemical mptp = chemicals.get(0); + assertTrue(mptp.getSynonyms().contains(glutathioneDisulfideSynonym)); } @Test public void testFindByInvalidIdFromChemicalList() throws Exception { + // Parkinson disease + MiriamData chemicalId2 = new MiriamData(MiriamType.TOXICOGENOMIC_CHEMICAL, "D0198012433"); - try { - // Parkinson disease - MiriamData chemicalId2 = new MiriamData(MiriamType.TOXICOGENOMIC_CHEMICAL, "D0198012433"); - - List<MiriamData> idsList = new ArrayList<MiriamData>(); - idsList.add(chemicalId2); - - List<Chemical> chemcials = chemicalParser.getChemicals(parkinsonDiseaseId, idsList); + List<MiriamData> idsList = new ArrayList<MiriamData>(); + idsList.add(chemicalId2); - assertTrue(chemcials.isEmpty()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + List<Chemical> chemcials = chemicalParser.getChemicals(parkinsonDiseaseId, idsList); + assertTrue(chemcials.isEmpty()); } - @Test + @Test(expected = InvalidArgumentException.class) public void testFindByInvalidDiseaseIdFromChemicalList() throws Exception { - try { - chemicalParser.getChemicals(null, new ArrayList<>()); - fail("Exceptione expected"); - } catch (InvalidArgumentException e) { - assertTrue(e.getMessage().contains("disease cannot be null")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - + chemicalParser.getChemicals(null, new ArrayList<>()); } @Test(timeout = 30000) public void testCachableInterfaceInvalidateChemical() throws Exception { - try { + Map<MiriamData, String> listFromDB = chemicalParser.getChemicalsForDisease(parkinsonDiseaseId); + assertNotNull(listFromDB); + assertTrue(!listFromDB.isEmpty()); + List<MiriamData> idsList = new ArrayList<>(); + idsList.add(stilbeneOxideChemicalId); + List<Chemical> chemcials = chemicalParser.getChemicals(parkinsonDiseaseId, idsList); + assertNotNull(chemcials); + assertTrue(chemcials.size() > 0); - Map<MiriamData, String> listFromDB = chemicalParser.getChemicalsForDisease(parkinsonDiseaseId); - assertNotNull(listFromDB); - assertTrue(!listFromDB.isEmpty()); - List<MiriamData> idsList = new ArrayList<>(); - idsList.add(stilbeneOxideChemicalId); - List<Chemical> chemcials = chemicalParser.getChemicals(parkinsonDiseaseId, idsList); - assertNotNull(chemcials); - assertTrue(chemcials.size() > 0); + cache.invalidateByQuery(chemicalParser.getIdentifier(parkinsonDiseaseId, chemcials.get(0).getChemicalId()), + chemicalParser.getCacheType()); - cache.invalidateByQuery(chemicalParser.getIdentifier(parkinsonDiseaseId, chemcials.get(0).getChemicalId()), - chemicalParser.getCacheType()); - - permanentDatabaseLevelCache.waitToFinishTasks(); - - idsList.clear(); + permanentDatabaseLevelCache.waitToFinishTasks(); - idsList.add(chemcials.get(0).getChemicalId()); + idsList.clear(); - List<Chemical> chemcials2 = chemicalParser.getChemicals(parkinsonDiseaseId, idsList); - assertNotNull(chemcials2); - assertTrue(chemcials2.size() > 0); + idsList.add(chemcials.get(0).getChemicalId()); - assertFalse("Value wasn't refreshed from db", chemcials.get(0).equals(chemcials2.get(0))); + List<Chemical> chemcials2 = chemicalParser.getChemicals(parkinsonDiseaseId, idsList); + assertNotNull(chemcials2); + assertTrue(chemcials2.size() > 0); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertFalse("Value wasn't refreshed from db", chemcials.get(0).equals(chemcials2.get(0))); } @Test public void testGetByTarget() throws Exception { - try { - MiriamData target = new MiriamData(MiriamType.HGNC_SYMBOL, "GCH1"); - List<MiriamData> targets = new ArrayList<>(); - targets.add(target); - - List<Chemical> list = chemicalParser.getChemicalListByTarget(targets, dystoniaDisease); - assertNotNull(list); - assertFalse(list.isEmpty()); + MiriamData target = new MiriamData(MiriamType.HGNC_SYMBOL, "GCH1"); + List<MiriamData> targets = new ArrayList<>(); + targets.add(target); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + List<Chemical> list = chemicalParser.getChemicalListByTarget(targets, dystoniaDisease); + assertNotNull(list); + assertFalse(list.isEmpty()); } @Test public void testGetByTargetWithAnnotator() throws Exception { - try { - MiriamData target = new MiriamData(MiriamType.HGNC_SYMBOL, "GCH1", String.class); - List<MiriamData> targets = new ArrayList<>(); - targets.add(target); - - List<Chemical> list = chemicalParser.getChemicalListByTarget(targets, dystoniaDisease); - assertNotNull(list); - assertFalse(list.isEmpty()); + MiriamData target = new MiriamData(MiriamType.HGNC_SYMBOL, "GCH1", String.class); + List<MiriamData> targets = new ArrayList<>(); + targets.add(target); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + List<Chemical> list = chemicalParser.getChemicalListByTarget(targets, dystoniaDisease); + assertNotNull(list); + assertFalse(list.isEmpty()); } - @Test + @Test(expected = InvalidArgumentException.class) public void testGetByInvalidTarget() throws Exception { - try { - MiriamData target = new MiriamData(MiriamType.WIKIPEDIA, "TNF"); - List<MiriamData> targets = new ArrayList<>(); - targets.add(target); - chemicalParser.getChemicalListByTarget(targets, parkinsonDiseaseId); - fail("Exception expected"); - - } catch (InvalidArgumentException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + MiriamData target = new MiriamData(MiriamType.WIKIPEDIA, "TNF"); + List<MiriamData> targets = new ArrayList<>(); + targets.add(target); + chemicalParser.getChemicalListByTarget(targets, parkinsonDiseaseId); } @Test public void testGetByUnknownHgnc() throws Exception { - try { - // Parkinson disease - MiriamData target = new MiriamData(MiriamType.HGNC_SYMBOL, "UNK_HGNC"); - chemicalParser.getChemicalListByTarget(target, parkinsonDiseaseId); - // we have one warning regarding unknown hgnc symbol (we shouldn't throw - // exception here bcuase these symbols sometimes are some - // generic gene names) - assertEquals(1, getWarnings().size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + // Parkinson disease + MiriamData target = new MiriamData(MiriamType.HGNC_SYMBOL, "UNK_HGNC"); + chemicalParser.getChemicalListByTarget(target, parkinsonDiseaseId); + // we have one warning regarding unknown hgnc symbol (we shouldn't throw + // exception here bcuase these symbols sometimes are some + // generic gene names) + assertEquals(1, getWarnings().size()); } - @Test + @Test(expected = ChemicalSearchException.class) public void testGetByTargetWhenProblemWithHgncConnection() throws Exception { HgncAnnotator annotator = chemicalParser.getHgncAnnotator(); try { @@ -334,12 +230,6 @@ public class ChemicalParserTest extends AnnotationTestFunctions { List<MiriamData> targets = new ArrayList<>(); targets.add(target); chemicalParser.getChemicalListByTarget(targets, parkinsonDiseaseId); - fail("Exception expected"); - } catch (ChemicalSearchException e) { - assertTrue(e.getMessage().contains("Problem with accessing hgnc service")); - } catch (Exception e) { - e.printStackTrace(); - throw e; } finally { chemicalParser.setHgncAnnotator(annotator); } @@ -347,82 +237,46 @@ public class ChemicalParserTest extends AnnotationTestFunctions { @Test public void testGetByEntrezTarget() throws Exception { - try { - MiriamData target = new MiriamData(MiriamType.ENTREZ, "2643"); - List<MiriamData> targets = new ArrayList<>(); - targets.add(target); - List<Chemical> list = chemicalParser.getChemicalListByTarget(targets, dystoniaDisease); - assertTrue(list.size() > 0); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + MiriamData target = new MiriamData(MiriamType.ENTREZ, "2643"); + List<MiriamData> targets = new ArrayList<>(); + targets.add(target); + List<Chemical> list = chemicalParser.getChemicalListByTarget(targets, dystoniaDisease); + assertTrue(list.size() > 0); } @Test public void testGetByTarget2() throws Exception { - try { - MiriamData target = new MiriamData(MiriamType.HGNC_SYMBOL, "GALM"); - List<MiriamData> targets = new ArrayList<>(); - targets.add(target); - List<Chemical> list = chemicalParser.getChemicalListByTarget(targets, parkinsonDiseaseId); - assertNotNull(list); - assertTrue(list.isEmpty()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + MiriamData target = new MiriamData(MiriamType.HGNC_SYMBOL, "GALM"); + List<MiriamData> targets = new ArrayList<>(); + targets.add(target); + List<Chemical> list = chemicalParser.getChemicalListByTarget(targets, parkinsonDiseaseId); + assertNotNull(list); + assertTrue(list.isEmpty()); } @Test public void testRefreshQuery() throws Exception { - try { - Object object = chemicalParser.refreshCacheQuery(ChemicalParser.DISEASE_CHEMICALS_PREFIX + "D010300"); - assertNotNull(object); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Object object = chemicalParser.refreshCacheQuery(ChemicalParser.DISEASE_CHEMICALS_PREFIX + "D010300"); + assertNotNull(object); } @Test public void testRefreshQuery2() throws Exception { - try { - Object object = chemicalParser.refreshCacheQuery("https://www.google.pl/"); - assertNotNull(object); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Object object = chemicalParser.refreshCacheQuery("https://www.google.pl/"); + assertNotNull(object); } - @Test + @Test(expected = InvalidArgumentException.class) public void testRefreshInvalidCacheQuery() throws Exception { - try { - chemicalParser.refreshCacheQuery("invalid_query"); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - assertTrue(e.getMessage().contains("Don't know what to do")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + chemicalParser.refreshCacheQuery("invalid_query"); } - @Test + @Test(expected = InvalidArgumentException.class) public void testRefreshInvalidCacheQuery2() throws Exception { - try { - chemicalParser.refreshCacheQuery(new Object()); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - assertTrue(e.getMessage().contains("Don't know what to do")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + chemicalParser.refreshCacheQuery(new Object()); } - @Test + @Test(expected = SourceNotAvailable.class) public void testRefreshCacheQueryWhenCtdDbNotAvailable() throws Exception { MiriamData chemicalId = new MiriamData(MiriamType.TOXICOGENOMIC_CHEMICAL, "D015039"); @@ -439,11 +293,6 @@ public class ChemicalParserTest extends AnnotationTestFunctions { when(mockDownloader.getFromNetwork(anyString(), anyString(), nullable(String.class))).thenReturn(""); chemicalParser.setWebPageDownloader(mockDownloader); chemicalParser.refreshCacheQuery(query); - fail("Exception expected"); - } catch (SourceNotAvailable e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; } finally { chemicalParser.setWebPageDownloader(downloader); chemicalParser.setCache(cache); @@ -452,12 +301,7 @@ public class ChemicalParserTest extends AnnotationTestFunctions { @Test public void testStatus() throws Exception { - try { - assertEquals(ExternalServiceStatusType.OK, chemicalParser.getServiceStatus().getStatus()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(ExternalServiceStatusType.OK, chemicalParser.getServiceStatus().getStatus()); } @Test @@ -469,9 +313,6 @@ public class ChemicalParserTest extends AnnotationTestFunctions { .thenThrow(new IOException()); chemicalParser.setWebPageDownloader(mockDownloader); assertEquals(ExternalServiceStatusType.DOWN, chemicalParser.getServiceStatus().getStatus()); - } catch (Exception e) { - e.printStackTrace(); - throw e; } finally { chemicalParser.setWebPageDownloader(downloader); } @@ -485,9 +326,6 @@ public class ChemicalParserTest extends AnnotationTestFunctions { when(mockDownloader.getFromNetwork(anyString(), anyString(), nullable(String.class))).thenReturn(""); chemicalParser.setWebPageDownloader(mockDownloader); assertEquals(ExternalServiceStatusType.CHANGED, chemicalParser.getServiceStatus().getStatus()); - } catch (Exception e) { - e.printStackTrace(); - throw e; } finally { chemicalParser.setWebPageDownloader(downloader); } @@ -495,30 +333,25 @@ public class ChemicalParserTest extends AnnotationTestFunctions { @Test public void testGetChemicalFromChemicalLineWithInvalidHgnc() throws Exception { - try { - String line[] = new String[ChemicalParser.CHEMICALS_COUNT_COL + 1]; - for (int i = 0; i < line.length; i++) { - line[i] = ""; - } - line[ChemicalParser.CHEMICALS_DIRECT_COL] = ChemicalDirectEvidence.THERAPEUTIC.getValue(); - line[ChemicalParser.CHEMICALS_NETWORK_COL] = "UNK_HGNC"; - Chemical result = chemicalParser.getChemicalFromChemicalLine(line, - new MiriamData(MiriamType.TOXICOGENOMIC_CHEMICAL, "D015039000")); - // we have two errors related to parsing inference score and reference - // count - assertEquals(2, getErrors().size()); - // there are no genes (we have one that is invalid and should be - // discarded) - assertEquals(0, result.getInferenceNetwork().size()); - - assertEquals(ChemicalDirectEvidence.THERAPEUTIC, result.getDirectEvidence()); - } catch (Exception e) { - e.printStackTrace(); - throw e; + String line[] = new String[ChemicalParser.CHEMICALS_COUNT_COL + 1]; + for (int i = 0; i < line.length; i++) { + line[i] = ""; } + line[ChemicalParser.CHEMICALS_DIRECT_COL] = ChemicalDirectEvidence.THERAPEUTIC.getValue(); + line[ChemicalParser.CHEMICALS_NETWORK_COL] = "UNK_HGNC"; + Chemical result = chemicalParser.getChemicalFromChemicalLine(line, + new MiriamData(MiriamType.TOXICOGENOMIC_CHEMICAL, "D015039000")); + // we have two errors related to parsing inference score and reference + // count + assertEquals(2, getErrors().size()); + // there are no genes (we have one that is invalid and should be + // discarded) + assertEquals(0, result.getInferenceNetwork().size()); + + assertEquals(ChemicalDirectEvidence.THERAPEUTIC, result.getDirectEvidence()); } - @Test + @Test(expected = ChemicalSearchException.class) public void testGetChemicalFromChemicalLineWithHgncConnectionProblem() throws Exception { HgncAnnotator hgncAnnotator = chemicalParser.getHgncAnnotator(); try { @@ -532,19 +365,13 @@ public class ChemicalParserTest extends AnnotationTestFunctions { when(mockAnnotator.hgncToEntrez(any())).thenThrow(new AnnotatorException("")); chemicalParser.setHgncAnnotator(mockAnnotator); chemicalParser.getChemicalFromChemicalLine(line, new MiriamData(MiriamType.TOXICOGENOMIC_CHEMICAL, "D015039000")); - fail("Exception expected"); - } catch (ChemicalSearchException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; } finally { chemicalParser.setHgncAnnotator(hgncAnnotator); } } - @Test + @Test(expected = ChemicalSearchException.class) public void testProblemWithPubmeds() throws Exception { - GeneralCacheInterface cache = chemicalParser.getCache(); WebPageDownloader downloader = chemicalParser.getWebPageDownloader(); try { @@ -566,14 +393,7 @@ public class ChemicalParserTest extends AnnotationTestFunctions { when(mockDownloader.getFromNetwork(anyString(), anyString(), nullable(String.class))) .thenThrow(new IOException()); chemicalParser.setWebPageDownloader(mockDownloader); - try { - chemicalParser.getChemicals(parkinsonDiseaseId, idsList); - fail("Exception expected"); - } catch (ChemicalSearchException e) { - } - } catch (Exception e) { - e.printStackTrace(); - throw e; + chemicalParser.getChemicals(parkinsonDiseaseId, idsList); } finally { chemicalParser.setCache(cache); chemicalParser.setWebPageDownloader(downloader); @@ -583,55 +403,34 @@ public class ChemicalParserTest extends AnnotationTestFunctions { @Test public void testGetEmptySuggestedQueryList() throws Exception { - try { - Project project = new Project(); - project.setId(-1); - - List<String> result = chemicalParser.getSuggestedQueryList(project, parkinsonDiseaseId); - - assertEquals(0, result.size()); + Project project = new Project(); + project.setId(-1); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + List<String> result = chemicalParser.getSuggestedQueryList(project, parkinsonDiseaseId); + assertEquals(0, result.size()); } @Test public void testGetSuggestedQueryList() throws Exception { - try { - Project project = new Project(); - Model model = getModelForFile("testFiles/target_chemical/target.xml", false); - project.addModel(model); - - List<String> result = chemicalParser.getSuggestedQueryList(project, dystoniaDisease); + Project project = new Project(); + Model model = getModelForFile("testFiles/target_chemical/target.xml", false); + project.addModel(model); - assertTrue(result.size() > 0); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + List<String> result = chemicalParser.getSuggestedQueryList(project, dystoniaDisease); + assertTrue(result.size() > 0); } @Test public void testGetSuggestedQueryListForUnknownDiseas() throws Exception { - try { - Project project = new Project(); - Model model = getModelForFile("testFiles/target_chemical/target.xml", false); - project.addModel(model); + Project project = new Project(); + Model model = getModelForFile("testFiles/target_chemical/target.xml", false); + project.addModel(model); - List<String> result = chemicalParser.getSuggestedQueryList(project, null); - - assertEquals(0, result.size()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + List<String> result = chemicalParser.getSuggestedQueryList(project, null); + assertEquals(0, result.size()); } } diff --git a/annotation/src/test/java/lcsb/mapviewer/annotation/services/DrugAnnotationTest.java b/annotation/src/test/java/lcsb/mapviewer/annotation/services/DrugAnnotationTest.java index 5bf0d396920536e825b6e004a9c7d9e979b3efda..3ba3717a96874f88714191d3d5d9a058a65c2157 100644 --- a/annotation/src/test/java/lcsb/mapviewer/annotation/services/DrugAnnotationTest.java +++ b/annotation/src/test/java/lcsb/mapviewer/annotation/services/DrugAnnotationTest.java @@ -1,14 +1,13 @@ package lcsb.mapviewer.annotation.services; -import static org.junit.Assert.assertEquals; +import static org.junit.Assert.*; import java.util.Collection; import java.util.List; -import org.apache.logging.log4j.*; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.junit.*; import org.springframework.beans.factory.annotation.Autowired; import lcsb.mapviewer.annotation.AnnotationTestFunctions; @@ -31,35 +30,29 @@ public class DrugAnnotationTest extends AnnotationTestFunctions { @Test public void testXmlSerialization() throws Exception { - try { - DrugAnnotation drugAnnotation = new DrugAnnotation(DrugAnnotation.class) { - @Override - public Drug findDrug(String name) { - // TODO Auto-generated method stub - return null; - } + DrugAnnotation drugAnnotation = new DrugAnnotation(DrugAnnotation.class) { + @Override + public Drug findDrug(String name) { + // TODO Auto-generated method stub + return null; + } - @Override - public List<Drug> getDrugListByTarget(MiriamData target, Collection<MiriamData> organisms) { - // TODO Auto-generated method stub - return null; - } + @Override + public List<Drug> getDrugListByTarget(MiriamData target, Collection<MiriamData> organisms) { + // TODO Auto-generated method stub + return null; + } - }; - Drug drug = drugBankHTMLParser.findDrug("aspirin"); + }; + Drug drug = drugBankHTMLParser.findDrug("aspirin"); - String xml = drugAnnotation.getDrugSerializer().objectToString(drug); + String xml = drugAnnotation.getDrugSerializer().objectToString(drug); - Drug drug2 = drugAnnotation.getDrugSerializer().xmlToObject(getNodeFromXmlString(xml)); + Drug drug2 = drugAnnotation.getDrugSerializer().xmlToObject(getNodeFromXmlString(xml)); - assertEquals(drug.getTargets().size(), drug2.getTargets().size()); - assertEquals(drug.getTargets().get(0).getGenes().size(), drug2.getTargets().get(0).getGenes().size()); - assertEquals(drug.getTargets().get(0).getReferences().size(), drug2.getTargets().get(0).getReferences().size()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(drug.getTargets().size(), drug2.getTargets().size()); + assertEquals(drug.getTargets().get(0).getGenes().size(), drug2.getTargets().get(0).getGenes().size()); + assertEquals(drug.getTargets().get(0).getReferences().size(), drug2.getTargets().get(0).getReferences().size()); } } diff --git a/annotation/src/test/java/lcsb/mapviewer/annotation/services/DrugbankHTMLParserTest.java b/annotation/src/test/java/lcsb/mapviewer/annotation/services/DrugbankHTMLParserTest.java index 440c857cff4a552d536e238715ca377b3eacaa09..e5e204064e5165e2627a125acb9333a4a14236d3 100644 --- a/annotation/src/test/java/lcsb/mapviewer/annotation/services/DrugbankHTMLParserTest.java +++ b/annotation/src/test/java/lcsb/mapviewer/annotation/services/DrugbankHTMLParserTest.java @@ -1,29 +1,21 @@ package lcsb.mapviewer.annotation.services; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.ArgumentMatchers.nullable; -import static org.mockito.Mockito.when; +import static org.junit.Assert.*; +import static org.mockito.ArgumentMatchers.*; +import static org.mockito.Mockito.*; import java.io.IOException; import java.util.ArrayList; import java.util.List; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.junit.Test; import org.mockito.Mockito; import org.springframework.beans.factory.annotation.Autowired; import lcsb.mapviewer.annotation.AnnotationTestFunctions; -import lcsb.mapviewer.annotation.cache.GeneralCacheInterface; -import lcsb.mapviewer.annotation.cache.PermanentDatabaseLevelCacheInterface; -import lcsb.mapviewer.annotation.cache.SourceNotAvailable; -import lcsb.mapviewer.annotation.cache.WebPageDownloader; +import lcsb.mapviewer.annotation.cache.*; import lcsb.mapviewer.annotation.data.Drug; import lcsb.mapviewer.annotation.data.Target; import lcsb.mapviewer.annotation.services.annotators.UniprotAnnotator; @@ -44,366 +36,235 @@ public class DrugbankHTMLParserTest extends AnnotationTestFunctions { @Test public void test1FindDrug() throws Exception { - try { - Drug test = drugBankHTMLParser.findDrug("Urokinase"); - assertNotNull(test); - assertEquals(MiriamType.DRUGBANK, test.getSources().get(0).getDataType()); - assertEquals("DB00013", test.getSources().get(0).getResource()); - assertEquals("Urokinase", test.getName()); - assertTrue(test.getBloodBrainBarrier().equalsIgnoreCase("N/A")); - boolean res = test.getDescription().contains( - "Low molecular weight form of human urokinase, that consists of an A chain of 2,000 daltons linked by a sulfhydryl bond to a B chain of 30,400 daltons. Recombinant urokinase plasminogen activator"); - assertTrue(res); - assertEquals(10, test.getTargets().size()); - assertNull(test.getApproved()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Drug test = drugBankHTMLParser.findDrug("Urokinase"); + assertNotNull(test); + assertEquals(MiriamType.DRUGBANK, test.getSources().get(0).getDataType()); + assertEquals("DB00013", test.getSources().get(0).getResource()); + assertEquals("Urokinase", test.getName()); + assertTrue(test.getBloodBrainBarrier().equalsIgnoreCase("N/A")); + boolean res = test.getDescription().contains( + "Low molecular weight form of human urokinase, that consists of an A chain of 2,000 daltons linked by a sulfhydryl bond to a B chain of 30,400 daltons. Recombinant urokinase plasminogen activator"); + assertTrue(res); + assertEquals(10, test.getTargets().size()); + assertNull(test.getApproved()); } @Test public void testFindRapamycin() throws Exception { - try { - // finding synonym - Drug rapamycinDrug = drugBankHTMLParser.findDrug("Rapamycin"); - assertNotNull(rapamycinDrug); - assertEquals("Sirolimus", rapamycinDrug.getName()); - assertEquals("DB00877", rapamycinDrug.getSources().get(0).getResource()); - assertTrue(rapamycinDrug.getBloodBrainBarrier().equalsIgnoreCase("NO")); - boolean res = rapamycinDrug.getDescription().contains("A macrolide compound obtained from Streptomyces"); - assertTrue(res); - assertEquals(3, rapamycinDrug.getTargets().size()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + // finding synonym + Drug rapamycinDrug = drugBankHTMLParser.findDrug("Rapamycin"); + assertNotNull(rapamycinDrug); + assertEquals("Sirolimus", rapamycinDrug.getName()); + assertEquals("DB00877", rapamycinDrug.getSources().get(0).getResource()); + assertTrue(rapamycinDrug.getBloodBrainBarrier().equalsIgnoreCase("NO")); + boolean res = rapamycinDrug.getDescription().contains("A macrolide compound obtained from Streptomyces"); + assertTrue(res); + assertEquals(3, rapamycinDrug.getTargets().size()); } @Test public void testFindAfegostat() throws Exception { - try { - // finding synonym - Drug afegostatDrug = drugBankHTMLParser.findDrug("Afegostat"); - assertNotNull(afegostatDrug); - assertFalse(afegostatDrug.getApproved()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + // finding synonym + Drug afegostatDrug = drugBankHTMLParser.findDrug("Afegostat"); + assertNotNull(afegostatDrug); + assertFalse(afegostatDrug.getApproved()); } @Test public void test4FindDrug() throws Exception { + Drug test = drugBankHTMLParser.findDrug("Methylamine"); + assertNotNull(test); + assertEquals("Methylamine", test.getName()); + assertEquals("DB01828", test.getSources().get(0).getResource()); + assertEquals(null, test.getDescription()); + assertEquals(1, test.getTargets().size()); - try { - Drug test = drugBankHTMLParser.findDrug("Methylamine"); - assertNotNull(test); - assertEquals("Methylamine", test.getName()); - assertEquals("DB01828", test.getSources().get(0).getResource()); - assertEquals(null, test.getDescription()); - assertEquals(1, test.getTargets().size()); - - List<Target> tmp; - tmp = test.getTargets(); - for (Target a : tmp) { - assertEquals("Ammonia channel", a.getName()); - assertEquals(2, a.getReferences().size()); - assertEquals(1, a.getGenes().size()); - } - - } catch (Exception e) { - e.printStackTrace(); - throw e; + List<Target> tmp; + tmp = test.getTargets(); + for (Target a : tmp) { + assertEquals("Ammonia channel", a.getName()); + assertEquals(2, a.getReferences().size()); + assertEquals(1, a.getGenes().size()); } } @Test public void testFindInvalidDrug() throws Exception { - try { - Drug test = drugBankHTMLParser.findDrug("qwertyuiop"); - assertNull(test); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Drug test = drugBankHTMLParser.findDrug("qwertyuiop"); + assertNull(test); } @Test public void test7FindDrug() throws Exception { - try { - Drug test = drugBankHTMLParser.findDrug("Aluminum hydroxide"); - assertNotNull(test); - assertEquals("Aluminum hydroxide", test.getName()); - assertEquals("DB06723", test.getSources().get(0).getResource()); - assertTrue(test.getDescription().contains( - "Aluminum hydroxide is an inorganic salt used as an antacid. It is a basic compound that acts by neutralizing hydrochloric acid in gastric secretions. Subsequent increases in pH may inhibit the action of pepsin. An increase in bicarbonate ions and prostaglandins may also confer cytoprotective effects.")); - assertEquals(0, test.getTargets().size()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Drug test = drugBankHTMLParser.findDrug("Aluminum hydroxide"); + assertNotNull(test); + assertEquals("Aluminum hydroxide", test.getName()); + assertEquals("DB06723", test.getSources().get(0).getResource()); + assertTrue(test.getDescription().contains( + "Aluminum hydroxide is an inorganic salt used as an antacid. It is a basic compound that acts by neutralizing hydrochloric acid in gastric secretions. Subsequent increases in pH may inhibit the action of pepsin. An increase in bicarbonate ions and prostaglandins may also confer cytoprotective effects.")); + assertEquals(0, test.getTargets().size()); } @Test public void testFindDrugAmantadineWithBrandNames() throws Exception { - try { - Drug drug = drugBankHTMLParser.findDrug("amantadine"); - - assertNotNull(drug); - assertTrue(drug.getBrandNames().contains("PK-Merz")); - assertTrue(drug.getBrandNames().contains("Symadine")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Drug drug = drugBankHTMLParser.findDrug("amantadine"); + + assertNotNull(drug); + assertTrue(drug.getBrandNames().contains("PK-Merz")); + assertTrue(drug.getBrandNames().contains("Symadine")); } @Test public void testFindDrugSelegiline() throws Exception { - try { - Drug test = drugBankHTMLParser.findDrug("Selegiline"); - assertNotNull(test); - assertEquals(2, test.getTargets().size()); - for (String string : new String[] { "MAOA", "MAOB" }) { - boolean contain = false; - for (Target target : test.getTargets()) { - for (MiriamData md : target.getGenes()) { - if (md.getResource().equals(string)) { - contain = true; - } + Drug test = drugBankHTMLParser.findDrug("Selegiline"); + assertNotNull(test); + assertEquals(2, test.getTargets().size()); + for (String string : new String[] { "MAOA", "MAOB" }) { + boolean contain = false; + for (Target target : test.getTargets()) { + for (MiriamData md : target.getGenes()) { + if (md.getResource().equals(string)) { + contain = true; } } - assertTrue("Missing traget: " + string, contain); } - } catch (Exception e) { - e.printStackTrace(); - throw e; + assertTrue("Missing traget: " + string, contain); } } @Test public void testFindDrugDaidzinWithHtmlCharacters() throws Exception { - try { - Drug test = drugBankHTMLParser.findDrug("Daidzin"); - assertNotNull(test); - for (String str : test.getSynonyms()) { - assertFalse(str.contains("'")); - } - } catch (Exception e) { - e.printStackTrace(); - throw e; + Drug test = drugBankHTMLParser.findDrug("Daidzin"); + assertNotNull(test); + for (String str : test.getSynonyms()) { + assertFalse(str.contains("'")); } } @Test public void testFindDrugGliclazideWithHtmlTags() throws Exception { - try { - Drug test = drugBankHTMLParser.findDrug("Gliclazide"); - assertNotNull(test); - assertFalse(test.getDescription().contains("<span")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Drug test = drugBankHTMLParser.findDrug("Gliclazide"); + assertNotNull(test); + assertFalse(test.getDescription().contains("<span")); } @Test public void testFindDrugSevofluraneWithHtmlTags() throws Exception { - try { - Drug test = drugBankHTMLParser.findDrug("sevoflurane"); - assertNotNull(test); - for (String str : test.getSynonyms()) { - assertFalse(str.contains("<div")); - } - } catch (Exception e) { - e.printStackTrace(); - throw e; + Drug test = drugBankHTMLParser.findDrug("sevoflurane"); + assertNotNull(test); + for (String str : test.getSynonyms()) { + assertFalse(str.contains("<div")); } } @Test public void testFindDrugByHgncTarget() throws Exception { - try { - List<Drug> drugs = drugBankHTMLParser.getDrugListByTarget(new MiriamData(MiriamType.HGNC_SYMBOL, "SIRT3")); - assertNotNull(drugs); - assertTrue("At least 1 drug was expected", drugs.size() >= 1); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + List<Drug> drugs = drugBankHTMLParser.getDrugListByTarget(new MiriamData(MiriamType.HGNC_SYMBOL, "SIRT3")); + assertNotNull(drugs); + assertTrue("At least 1 drug was expected", drugs.size() >= 1); } @Test public void testFindDrugByHgncTargetWithAnnotatorAssigned() throws Exception { - try { - List<Drug> drugs = drugBankHTMLParser.getDrugListByTarget(new MiriamData(MiriamType.HGNC_SYMBOL, "SIRT3", String.class)); - assertNotNull(drugs); - assertTrue("At least 1 drug was expected", drugs.size() >= 1); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + List<Drug> drugs = drugBankHTMLParser + .getDrugListByTarget(new MiriamData(MiriamType.HGNC_SYMBOL, "SIRT3", String.class)); + assertNotNull(drugs); + assertTrue("At least 1 drug was expected", drugs.size() >= 1); } @Test public void testTargetPageMatchTargetForTFProtein() throws Exception { - try { - MiriamData tfMiriam = new MiriamData(MiriamType.HGNC_SYMBOL, "TF"); - String content = drugBankHTMLParser.getWebPageDownloader() - .getFromNetwork("https://www.drugbank.ca/biodb/bio_entities/BE0000510"); - assertTrue(drugBankHTMLParser.targetPageMatchTarget(content, tfMiriam)); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + MiriamData tfMiriam = new MiriamData(MiriamType.HGNC_SYMBOL, "TF"); + String content = drugBankHTMLParser.getWebPageDownloader() + .getFromNetwork("https://www.drugbank.ca/biodb/bio_entities/BE0000510"); + assertTrue(drugBankHTMLParser.targetPageMatchTarget(content, tfMiriam)); } @Test public void testTargetPageMatchTargetForNotMatchingTFProtein() throws Exception { - try { - MiriamData tfMiriam = new MiriamData(MiriamType.HGNC_SYMBOL, "TF"); - String content = drugBankHTMLParser.getWebPageDownloader() - .getFromNetwork("https://www.drugbank.ca/biodb/bio_entities/BE0002803"); - assertFalse(drugBankHTMLParser.targetPageMatchTarget(content, tfMiriam)); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + MiriamData tfMiriam = new MiriamData(MiriamType.HGNC_SYMBOL, "TF"); + String content = drugBankHTMLParser.getWebPageDownloader() + .getFromNetwork("https://www.drugbank.ca/biodb/bio_entities/BE0002803"); + assertFalse(drugBankHTMLParser.targetPageMatchTarget(content, tfMiriam)); } @Test public void testIsDrugContainTarget() throws Exception { - try { - Drug afegostat = drugBankHTMLParser.findDrug("Urokinase"); - MiriamData plgMiriam = new MiriamData(MiriamType.HGNC_SYMBOL, "PLG"); - MiriamData tfMiriam = new MiriamData(MiriamType.HGNC_SYMBOL, "TF"); - assertTrue(drugBankHTMLParser.isDrugContainTarget(plgMiriam, afegostat)); - assertFalse(drugBankHTMLParser.isDrugContainTarget(tfMiriam, afegostat)); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Drug afegostat = drugBankHTMLParser.findDrug("Urokinase"); + MiriamData plgMiriam = new MiriamData(MiriamType.HGNC_SYMBOL, "PLG"); + MiriamData tfMiriam = new MiriamData(MiriamType.HGNC_SYMBOL, "TF"); + assertTrue(drugBankHTMLParser.isDrugContainTarget(plgMiriam, afegostat)); + assertFalse(drugBankHTMLParser.isDrugContainTarget(tfMiriam, afegostat)); } @Test public void testFindAluminiumByName() throws Exception { - try { - Drug drug = drugBankHTMLParser.findDrug("Aluminium"); - assertTrue(drug.getName().equalsIgnoreCase("Aluminium")); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Drug drug = drugBankHTMLParser.findDrug("Aluminium"); + assertTrue(drug.getName().equalsIgnoreCase("Aluminium")); } @Test public void testFindDrugByHgncTargetAndFilteredOutByOrganism() throws Exception { - try { - List<MiriamData> organisms = new ArrayList<>(); - organisms.add(new MiriamData(MiriamType.TAXONOMY, "-1")); - List<Drug> drugs = drugBankHTMLParser.getDrugListByTarget(new MiriamData(MiriamType.HGNC_SYMBOL, "SIRT3"), - organisms); - assertNotNull(drugs); - assertEquals("No drugs for this organisms should be found", 0, drugs.size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + List<MiriamData> organisms = new ArrayList<>(); + organisms.add(new MiriamData(MiriamType.TAXONOMY, "-1")); + List<Drug> drugs = drugBankHTMLParser.getDrugListByTarget(new MiriamData(MiriamType.HGNC_SYMBOL, "SIRT3"), + organisms); + assertNotNull(drugs); + assertEquals("No drugs for this organisms should be found", 0, drugs.size()); } @Test public void testFindDrugByHgncTargetAndFilteredByOrganism() throws Exception { - try { - List<MiriamData> organisms = new ArrayList<>(); - organisms.add(TaxonomyBackend.HUMAN_TAXONOMY); - List<Drug> drugs = drugBankHTMLParser.getDrugListByTarget(new MiriamData(MiriamType.HGNC_SYMBOL, "SIRT3"), - organisms); - assertNotNull(drugs); - assertTrue(drugs.size() > 0); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + List<MiriamData> organisms = new ArrayList<>(); + organisms.add(TaxonomyBackend.HUMAN_TAXONOMY); + List<Drug> drugs = drugBankHTMLParser.getDrugListByTarget(new MiriamData(MiriamType.HGNC_SYMBOL, "SIRT3"), + organisms); + assertNotNull(drugs); + assertTrue(drugs.size() > 0); } - @Test + @Test(expected = InvalidArgumentException.class) public void testFindDrugByInvalidTarget() throws Exception { - try { - drugBankHTMLParser.getDrugListByTarget(new MiriamData(MiriamType.WIKIPEDIA, "h2o")); - fail("Exception"); - } catch (InvalidArgumentException e) { - assertTrue(e.getMessage().contains("type is accepted")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + drugBankHTMLParser.getDrugListByTarget(new MiriamData(MiriamType.WIKIPEDIA, "h2o")); } @Test public void testFindDrugByEmptyTarget() throws Exception { - try { - List<Drug> drugs = drugBankHTMLParser.getDrugListByTarget(null); - assertEquals(0, drugs.size()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + List<Drug> drugs = drugBankHTMLParser.getDrugListByTarget(null); + assertEquals(0, drugs.size()); } @Test public void testFindDrugByHgncTargets() throws Exception { - try { - MiriamData target1 = new MiriamData(MiriamType.HGNC_SYMBOL, "SIRT3"); - MiriamData target2 = new MiriamData(MiriamType.HGNC_SYMBOL, "SIRT5"); - List<Drug> drug1 = drugBankHTMLParser.getDrugListByTarget(target1); - List<Drug> drug2 = drugBankHTMLParser.getDrugListByTarget(target2); - int size = drug1.size() + drug2.size(); - - List<MiriamData> list = new ArrayList<>(); - list.add(target1); - list.add(target2); - - List<Drug> drugs = drugBankHTMLParser.getDrugListByTargets(list); - assertNotNull(drugs); - assertTrue("Merged list should be shorter then sum of the two lists", drugs.size() < size); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + MiriamData target1 = new MiriamData(MiriamType.HGNC_SYMBOL, "SIRT3"); + MiriamData target2 = new MiriamData(MiriamType.HGNC_SYMBOL, "SIRT5"); + List<Drug> drug1 = drugBankHTMLParser.getDrugListByTarget(target1); + List<Drug> drug2 = drugBankHTMLParser.getDrugListByTarget(target2); + int size = drug1.size() + drug2.size(); + List<MiriamData> list = new ArrayList<>(); + list.add(target1); + list.add(target2); + + List<Drug> drugs = drugBankHTMLParser.getDrugListByTargets(list); + assertNotNull(drugs); + assertTrue("Merged list should be shorter then sum of the two lists", drugs.size() < size); } @Test(timeout = 15000) public void testCachableInterfaceInvalidateUrl() throws Exception { String query = "http://google.lu/"; String newRes = "hello"; - try { - cache.setCachedQuery(query, drugBankHTMLParser.getCacheType(), newRes); - cache.invalidateByQuery(query, drugBankHTMLParser.getCacheType()); + cache.setCachedQuery(query, drugBankHTMLParser.getCacheType(), newRes); + cache.invalidateByQuery(query, drugBankHTMLParser.getCacheType()); - permanentDatabaseLevelCache.waitToFinishTasks(); + permanentDatabaseLevelCache.waitToFinishTasks(); - String res = cache.getStringByQuery(query, drugBankHTMLParser.getCacheType()); + String res = cache.getStringByQuery(query, drugBankHTMLParser.getCacheType()); - assertNotNull(res); + assertNotNull(res); - assertFalse("Value wasn't refreshed from db", newRes.equals(res)); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertFalse("Value wasn't refreshed from db", newRes.equals(res)); } // wait max 15 second @@ -412,150 +273,93 @@ public class DrugbankHTMLParserTest extends AnnotationTestFunctions { String query = "drug:amantadine"; String newRes = "hello"; - try { - cache.setCachedQuery(query, drugBankHTMLParser.getCacheType(), newRes); - cache.invalidateByQuery(query, drugBankHTMLParser.getCacheType()); - - permanentDatabaseLevelCache.waitToFinishTasks(); + cache.setCachedQuery(query, drugBankHTMLParser.getCacheType(), newRes); + cache.invalidateByQuery(query, drugBankHTMLParser.getCacheType()); - String res = cache.getStringByQuery(query, drugBankHTMLParser.getCacheType()); + permanentDatabaseLevelCache.waitToFinishTasks(); - assertNotNull(res); + String res = cache.getStringByQuery(query, drugBankHTMLParser.getCacheType()); - assertFalse("Value wasn't refreshed from db", newRes.equals(res)); + assertNotNull(res); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertFalse("Value wasn't refreshed from db", newRes.equals(res)); } @Test public void testByTargetsForCCNB1() throws Exception { - try { - List<MiriamData> targets = new ArrayList<>(); - MiriamData miriamTarget = new MiriamData(MiriamType.HGNC_SYMBOL, "CCNB1"); - targets.add(miriamTarget); - List<Drug> drugs = drugBankHTMLParser.getDrugListByTargets(targets); - for (Drug drug : drugs) { - boolean found = false; - for (Target target : drug.getTargets()) { - for (MiriamData md : target.getGenes()) { - if (miriamTarget.equals(md)) { - found = true; - } + List<MiriamData> targets = new ArrayList<>(); + MiriamData miriamTarget = new MiriamData(MiriamType.HGNC_SYMBOL, "CCNB1"); + targets.add(miriamTarget); + List<Drug> drugs = drugBankHTMLParser.getDrugListByTargets(targets); + for (Drug drug : drugs) { + boolean found = false; + for (Target target : drug.getTargets()) { + for (MiriamData md : target.getGenes()) { + if (miriamTarget.equals(md)) { + found = true; } } - assertTrue("Drug " + drug.getName() + " doesn't contain expected target", found); } - } catch (Exception e) { - e.printStackTrace(); - throw e; + assertTrue("Drug " + drug.getName() + " doesn't contain expected target", found); } - } @Test public void testFindIbuprofen() throws Exception { - try { - Drug drug = drugBankHTMLParser.findDrug("Ibuprofen"); - assertNotNull(drug); - assertEquals("Ibuprofen", drug.getName()); - assertEquals("DB01050", drug.getSources().get(0).getResource()); - assertNotNull(drug.getDescription()); - assertTrue(drug.getTargets().size() >= 8); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Drug drug = drugBankHTMLParser.findDrug("Ibuprofen"); + assertNotNull(drug); + assertEquals("Ibuprofen", drug.getName()); + assertEquals("DB01050", drug.getSources().get(0).getResource()); + assertNotNull(drug.getDescription()); + assertTrue(drug.getTargets().size() >= 8); } @Test public void testFindIronSaccharate() throws Exception { - try { - Drug drug = drugBankHTMLParser.findDrug("Iron saccharate"); - assertNotNull(drug); - MiriamData tfProtein = new MiriamData(MiriamType.HGNC_SYMBOL, "TF"); - for (Target target : drug.getTargets()) { - for (MiriamData md : target.getGenes()) { - assertFalse("TF is a carrier, not a target", md.equals(tfProtein)); - } + Drug drug = drugBankHTMLParser.findDrug("Iron saccharate"); + assertNotNull(drug); + MiriamData tfProtein = new MiriamData(MiriamType.HGNC_SYMBOL, "TF"); + for (Target target : drug.getTargets()) { + for (MiriamData md : target.getGenes()) { + assertFalse("TF is a carrier, not a target", md.equals(tfProtein)); } - - } catch (Exception e) { - e.printStackTrace(); - throw e; } } @Test public void testFindDopamine() throws Exception { - - try { - Drug test = drugBankHTMLParser.findDrug("Dopamine"); - assertNotNull(test); - for (Target target : test.getTargets()) { - assertFalse(target.getName().contains("Details")); - } - } catch (Exception e) { - e.printStackTrace(); - throw e; + Drug test = drugBankHTMLParser.findDrug("Dopamine"); + assertNotNull(test); + for (Target target : test.getTargets()) { + assertFalse(target.getName().contains("Details")); } } @Test public void testFindGadobutrol() throws Exception { - try { - Drug gadobutrolDrug = drugBankHTMLParser.findDrug("Gadobutrol"); - assertNotNull(gadobutrolDrug); - assertTrue(gadobutrolDrug.getBloodBrainBarrier().equalsIgnoreCase("NO")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Drug gadobutrolDrug = drugBankHTMLParser.findDrug("Gadobutrol"); + assertNotNull(gadobutrolDrug); + assertTrue(gadobutrolDrug.getBloodBrainBarrier().equalsIgnoreCase("NO")); } @Test public void testFindDrugWithSpecialCharacters() throws Exception { - - try { - Drug test = drugBankHTMLParser.findDrug("Thymidine-5'- Diphosphate"); - assertNotNull(test); - assertFalse(test.getName().contains("&")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Drug test = drugBankHTMLParser.findDrug("Thymidine-5'- Diphosphate"); + assertNotNull(test); + assertFalse(test.getName().contains("&")); } - @Test + @Test(expected = InvalidArgumentException.class) public void testRefreshInvalidCacheQuery() throws Exception { - try { - drugBankHTMLParser.refreshCacheQuery("invalid_query"); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - assertTrue(e.getMessage().contains("Don't know what to do")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + drugBankHTMLParser.refreshCacheQuery("invalid_query"); } - @Test + @Test(expected = InvalidArgumentException.class) public void testRefreshInvalidCacheQuery2() throws Exception { - try { - drugBankHTMLParser.refreshCacheQuery(new Object()); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - assertTrue(e.getMessage().contains("Don't know what to do")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + drugBankHTMLParser.refreshCacheQuery(new Object()); } - @Test + @Test(expected = SourceNotAvailable.class) public void testRefreshCacheQueryNotAvailable() throws Exception { WebPageDownloader downloader = drugBankHTMLParser.getWebPageDownloader(); try { @@ -564,17 +368,12 @@ public class DrugbankHTMLParserTest extends AnnotationTestFunctions { .thenThrow(new IOException()); drugBankHTMLParser.setWebPageDownloader(mockDownloader); drugBankHTMLParser.refreshCacheQuery("http://google.pl/"); - fail("Exception expected"); - } catch (SourceNotAvailable e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; } finally { drugBankHTMLParser.setWebPageDownloader(downloader); } } - @Test + @Test(expected = SourceNotAvailable.class) public void testRefreshCacheQueryWhenDbNotAvailable() throws Exception { WebPageDownloader downloader = drugBankHTMLParser.getWebPageDownloader(); GeneralCacheInterface cache = drugBankHTMLParser.getCache(); @@ -586,11 +385,6 @@ public class DrugbankHTMLParserTest extends AnnotationTestFunctions { drugBankHTMLParser.setCache(null); drugBankHTMLParser.refreshCacheQuery(DrugbankHTMLParser.DRUG_NAME_PREFIX + "aspirin"); - fail("Exception expected"); - } catch (SourceNotAvailable e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; } finally { drugBankHTMLParser.setWebPageDownloader(downloader); drugBankHTMLParser.setCache(cache); @@ -599,74 +393,44 @@ public class DrugbankHTMLParserTest extends AnnotationTestFunctions { @Test public void testGetPubmedFromRef() throws Exception { - try { - String descriptionString = "<a href=\"/pubmed/1234\">link to 1234</a>"; - List<MiriamData> result = drugBankHTMLParser.getPubmedFromRef(descriptionString); - assertEquals(1, result.size()); - assertEquals(new MiriamData(MiriamType.PUBMED, "1234"), result.get(0)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String descriptionString = "<a href=\"/pubmed/1234\">link to 1234</a>"; + List<MiriamData> result = drugBankHTMLParser.getPubmedFromRef(descriptionString); + assertEquals(1, result.size()); + assertEquals(new MiriamData(MiriamType.PUBMED, "1234"), result.get(0)); } @Test public void testGetPubmedFromRef2() throws Exception { - try { - String descriptionString = "<a href=\"/pubmed/12345678901234_\">link to 123456789</a>"; - List<MiriamData> result = drugBankHTMLParser.getPubmedFromRef(descriptionString); - assertEquals(1, result.size()); - assertEquals(new MiriamData(MiriamType.PUBMED, "123456789"), result.get(0)); - assertEquals(1, getWarnings().size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String descriptionString = "<a href=\"/pubmed/12345678901234_\">link to 123456789</a>"; + List<MiriamData> result = drugBankHTMLParser.getPubmedFromRef(descriptionString); + assertEquals(1, result.size()); + assertEquals(new MiriamData(MiriamType.PUBMED, "123456789"), result.get(0)); + assertEquals(1, getWarnings().size()); } @Test public void testGetPubmedFromRef3() throws Exception { - try { - String descriptionString = "<a href=\"/pubmed/invalid\">link to invalid</a>"; - List<MiriamData> result = drugBankHTMLParser.getPubmedFromRef(descriptionString); - assertEquals(0, result.size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String descriptionString = "<a href=\"/pubmed/invalid\">link to invalid</a>"; + List<MiriamData> result = drugBankHTMLParser.getPubmedFromRef(descriptionString); + assertEquals(0, result.size()); } @Test public void testGetDescription() throws Exception { - try { - String descriptionString = "untagged description"; - assertNull(drugBankHTMLParser.getDescriptionForDrug(descriptionString)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String descriptionString = "untagged description"; + assertNull(drugBankHTMLParser.getDescriptionForDrug(descriptionString)); } @Test public void testGetTargets() throws Exception { - try { - String descriptionString = "invalid content"; - List<Target> targets = drugBankHTMLParser.getTargetsForDrug(descriptionString); - assertEquals(0, targets.size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String descriptionString = "invalid content"; + List<Target> targets = drugBankHTMLParser.getTargetsForDrug(descriptionString); + assertEquals(0, targets.size()); } @Test public void testStatus() throws Exception { - try { - assertEquals(ExternalServiceStatusType.OK, drugBankHTMLParser.getServiceStatus().getStatus()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(ExternalServiceStatusType.OK, drugBankHTMLParser.getServiceStatus().getStatus()); } @Test @@ -678,9 +442,6 @@ public class DrugbankHTMLParserTest extends AnnotationTestFunctions { .thenThrow(new IOException()); drugBankHTMLParser.setWebPageDownloader(mockDownloader); assertEquals(ExternalServiceStatusType.DOWN, drugBankHTMLParser.getServiceStatus().getStatus()); - } catch (Exception e) { - e.printStackTrace(); - throw e; } finally { drugBankHTMLParser.setWebPageDownloader(downloader); } @@ -694,9 +455,6 @@ public class DrugbankHTMLParserTest extends AnnotationTestFunctions { when(mockDownloader.getFromNetwork(anyString(), anyString(), nullable(String.class))).thenReturn(""); drugBankHTMLParser.setWebPageDownloader(mockDownloader); assertEquals(ExternalServiceStatusType.CHANGED, drugBankHTMLParser.getServiceStatus().getStatus()); - } catch (Exception e) { - e.printStackTrace(); - throw e; } finally { drugBankHTMLParser.setWebPageDownloader(downloader); } @@ -704,23 +462,18 @@ public class DrugbankHTMLParserTest extends AnnotationTestFunctions { @Test public void testGetBBB() throws Exception { - try { - assertTrue( - drugBankHTMLParser.getBloodBrainBarrier("<tr><td>Blood Brain Barrier</td><td>-</td><td>0.7581</td></tr>") - .equalsIgnoreCase("NO")); - assertTrue( - drugBankHTMLParser.getBloodBrainBarrier("<tr><td>Blood Brain Barrier</td><td>+</td><td>0.7581</td></tr>") - .equalsIgnoreCase("YES")); - assertTrue(drugBankHTMLParser - .getBloodBrainBarrier("<tr><td>Blood Brain Barrier</td><td>don't know</td><td>0.7581</td></tr>") - .equalsIgnoreCase("N/A")); - assertTrue(drugBankHTMLParser.getBloodBrainBarrier("invalid str").equalsIgnoreCase("N/A")); - assertTrue(drugBankHTMLParser.getBloodBrainBarrier("<tr><td>Blood Brain Barrier</td>invalid str") - .equalsIgnoreCase("N/A")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertTrue( + drugBankHTMLParser.getBloodBrainBarrier("<tr><td>Blood Brain Barrier</td><td>-</td><td>0.7581</td></tr>") + .equalsIgnoreCase("NO")); + assertTrue( + drugBankHTMLParser.getBloodBrainBarrier("<tr><td>Blood Brain Barrier</td><td>+</td><td>0.7581</td></tr>") + .equalsIgnoreCase("YES")); + assertTrue(drugBankHTMLParser + .getBloodBrainBarrier("<tr><td>Blood Brain Barrier</td><td>don't know</td><td>0.7581</td></tr>") + .equalsIgnoreCase("N/A")); + assertTrue(drugBankHTMLParser.getBloodBrainBarrier("invalid str").equalsIgnoreCase("N/A")); + assertTrue(drugBankHTMLParser.getBloodBrainBarrier("<tr><td>Blood Brain Barrier</td>invalid str") + .equalsIgnoreCase("N/A")); } @Test @@ -742,72 +495,44 @@ public class DrugbankHTMLParserTest extends AnnotationTestFunctions { @Test public void testGetEmptySuggestedQueryList() throws Exception { - try { - Project project = new Project(); - project.setId(-2); - - List<String> result = drugBankHTMLParser.getSuggestedQueryList(project, TaxonomyBackend.HUMAN_TAXONOMY); + Project project = new Project(); + project.setId(-2); - assertEquals(0, result.size()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + List<String> result = drugBankHTMLParser.getSuggestedQueryList(project, TaxonomyBackend.HUMAN_TAXONOMY); + assertEquals(0, result.size()); } @Test public void testGetSuggestedQueryList() throws Exception { - try { - Project project = new Project(); - project.setId(-1); - Model model = getModelForFile("testFiles/target_drugbank/target.xml", false); - project.addModel(model); - - List<String> result = drugBankHTMLParser.getSuggestedQueryList(project, TaxonomyBackend.HUMAN_TAXONOMY); + Project project = new Project(); + project.setId(-1); + Model model = getModelForFile("testFiles/target_drugbank/target.xml", false); + project.addModel(model); - assertTrue(result.size() > 0); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + List<String> result = drugBankHTMLParser.getSuggestedQueryList(project, TaxonomyBackend.HUMAN_TAXONOMY); + assertTrue(result.size() > 0); } @Test public void testGetSuggestedQueryListForUnknownOrganism() throws Exception { - try { - Project project = new Project(); - project.setId(-2); - Model model = getModelForFile("testFiles/target_drugbank/target.xml", false); - project.addModel(model); + Project project = new Project(); + project.setId(-2); + Model model = getModelForFile("testFiles/target_drugbank/target.xml", false); + project.addModel(model); - List<String> result = drugBankHTMLParser.getSuggestedQueryList(project, null); - - assertEquals(0, result.size()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + List<String> result = drugBankHTMLParser.getSuggestedQueryList(project, null); + assertEquals(0, result.size()); } @Test public void testExtractTargetsFromPageContent() throws Exception { - try { - String pageContent = " Details</a>blablablablabla Details</a>"; - List<Target> result = drugBankHTMLParser.extractTargetsFromPageContent(pageContent, 2, 3); - - assertEquals(0, result.size()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String pageContent = " Details</a>blablablablabla Details</a>"; + List<Target> result = drugBankHTMLParser.extractTargetsFromPageContent(pageContent, 2, 3); + assertEquals(0, result.size()); } } diff --git a/annotation/src/test/java/lcsb/mapviewer/annotation/services/ImproperAnnotationsTest.java b/annotation/src/test/java/lcsb/mapviewer/annotation/services/ImproperAnnotationsTest.java index 2af983bf77d38f2c86ac5afefabee2e16af02c9a..b7316ecc36c4b0b6de63db365141a3a46435f03b 100644 --- a/annotation/src/test/java/lcsb/mapviewer/annotation/services/ImproperAnnotationsTest.java +++ b/annotation/src/test/java/lcsb/mapviewer/annotation/services/ImproperAnnotationsTest.java @@ -1,56 +1,43 @@ package lcsb.mapviewer.annotation.services; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import java.util.ArrayList; import java.util.List; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; +import lcsb.mapviewer.annotation.AnnotationTestFunctions; import lcsb.mapviewer.common.exception.InvalidArgumentException; import lcsb.mapviewer.model.map.MiriamData; import lcsb.mapviewer.model.map.MiriamType; import lcsb.mapviewer.model.map.species.GenericProtein; -public class ImproperAnnotationsTest { - - @AfterClass - public static void tearDownAfterClass() throws Exception { - } - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testConstructor3() { - try { - List<MiriamData> list = new ArrayList<>(); - list.add(new MiriamData(MiriamType.CAS, "a")); - ImproperAnnotations ie = new ImproperAnnotations(new GenericProtein("id"), list); - assertNotNull(ie.toString()); - } catch (InvalidArgumentException e) { - assertTrue(e.getMessage().contains("Only miriam data from elements are accepted")); - } - } - - @Test - public void testConstructor4() { - try { - new ImproperAnnotations(new GenericProtein("id"), new ArrayList<>()); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - assertTrue(e.getMessage().contains("List of improper annotations cannot be null")); - } - } +public class ImproperAnnotationsTest extends AnnotationTestFunctions { + + @AfterClass + public static void tearDownAfterClass() throws Exception { + } + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testConstructor3() { + List<MiriamData> list = new ArrayList<>(); + list.add(new MiriamData(MiriamType.CAS, "a")); + ImproperAnnotations ie = new ImproperAnnotations(new GenericProtein("id"), list); + assertNotNull(ie.toString()); + } + + @Test(expected = InvalidArgumentException.class) + public void testConstructor4() { + new ImproperAnnotations(new GenericProtein("id"), new ArrayList<>()); + } } diff --git a/annotation/src/test/java/lcsb/mapviewer/annotation/services/MeSHParserTest.java b/annotation/src/test/java/lcsb/mapviewer/annotation/services/MeSHParserTest.java index a892afafd5330f11fa1f1a9a17006f22fc90a610..2232a229caa37fd4ec0a63b03cf6581421022774 100644 --- a/annotation/src/test/java/lcsb/mapviewer/annotation/services/MeSHParserTest.java +++ b/annotation/src/test/java/lcsb/mapviewer/annotation/services/MeSHParserTest.java @@ -1,29 +1,21 @@ package lcsb.mapviewer.annotation.services; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.ArgumentMatchers.nullable; -import static org.mockito.Mockito.when; +import static org.junit.Assert.*; +import static org.mockito.ArgumentMatchers.*; +import static org.mockito.Mockito.*; import java.io.IOException; import java.util.List; import org.apache.http.HttpStatus; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.junit.Test; import org.mockito.Mockito; import org.springframework.beans.factory.annotation.Autowired; import lcsb.mapviewer.annotation.AnnotationTestFunctions; -import lcsb.mapviewer.annotation.cache.GeneralCacheInterface; -import lcsb.mapviewer.annotation.cache.PermanentDatabaseLevelCacheInterface; -import lcsb.mapviewer.annotation.cache.SourceNotAvailable; -import lcsb.mapviewer.annotation.cache.WebPageDownloader; +import lcsb.mapviewer.annotation.cache.*; import lcsb.mapviewer.annotation.data.MeSH; import lcsb.mapviewer.annotation.services.annotators.AnnotatorException; import lcsb.mapviewer.common.exception.InvalidArgumentException; @@ -44,163 +36,99 @@ public class MeSHParserTest extends AnnotationTestFunctions { @Test public void testGetMesh() throws Exception { - try { - // Parkinson disease - MiriamData meshID = new MiriamData(MiriamType.MESH_2012, "D004298"); - MeSH mesh = meshParser.getMeSH(meshID); - assertTrue(mesh != null); - assertTrue(mesh.getMeSHId() != null); - assertTrue(mesh.getName() != null); - assertTrue(mesh.getName().toLowerCase().equals("dopamine")); - assertTrue(mesh.getDescription() != null); - assertTrue(mesh.getSynonyms().size() > 0); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + // Parkinson disease + MiriamData meshID = new MiriamData(MiriamType.MESH_2012, "D004298"); + MeSH mesh = meshParser.getMeSH(meshID); + assertTrue(mesh != null); + assertTrue(mesh.getMeSHId() != null); + assertTrue(mesh.getName() != null); + assertTrue(mesh.getName().toLowerCase().equals("dopamine")); + assertTrue(mesh.getDescription() != null); + assertTrue(mesh.getSynonyms().size() > 0); } @Test public void testGetMeshBySynonym() throws Exception { - try { - String synonym = "MPTP"; - List<MeSH> result = meshParser.getMeshBySynonym(synonym); - assertEquals(1, result.size()); - MeSH mesh = result.get(0); - assertTrue(mesh.getSynonyms().contains(synonym)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String synonym = "MPTP"; + List<MeSH> result = meshParser.getMeshBySynonym(synonym); + assertEquals(1, result.size()); + MeSH mesh = result.get(0); + assertTrue(mesh.getSynonyms().contains(synonym)); } @Test public void testIsValidMesh() throws Exception { - try { - MiriamData meshID = new MiriamData(MiriamType.MESH_2012, "D004298"); - assertTrue(meshParser.isValidMeshId(meshID)); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + MiriamData meshID = new MiriamData(MiriamType.MESH_2012, "D004298"); + assertTrue(meshParser.isValidMeshId(meshID)); } @Test public void testIsValidMesh3() throws Exception { - try { - MiriamData meshID = new MiriamData(MiriamType.MESH_2012, "blablabla"); - assertFalse(meshParser.isValidMeshId(meshID)); + MiriamData meshID = new MiriamData(MiriamType.MESH_2012, "blablabla"); + assertFalse(meshParser.isValidMeshId(meshID)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } } @Test public void testIsValidMesh2() throws Exception { - try { - assertFalse(meshParser.isValidMeshId(null)); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertFalse(meshParser.isValidMeshId(null)); } @Test public void testIsValidWithSpace() throws Exception { - try { - MiriamData meshID = new MiriamData(MiriamType.MESH_2012, "some disease"); - assertFalse(meshParser.isValidMeshId(meshID)); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + MiriamData meshID = new MiriamData(MiriamType.MESH_2012, "some disease"); + assertFalse(meshParser.isValidMeshId(meshID)); } - @Test + @Test(expected = InvalidArgumentException.class) public void testGetInvalidMesh() throws Exception { - try { - meshParser.getMeSH(null); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + meshParser.getMeSH(null); } @Test public void testRefreshCacheQuery() throws Exception { - try { - Object res = meshParser.refreshCacheQuery("http://google.pl/"); - assertNotNull(res); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Object res = meshParser.refreshCacheQuery("http://google.pl/"); + assertNotNull(res); } @Test public void testGetRotenoneMesh() throws Exception { - try { - // Rotenone disease -no synonyms - MiriamData meshID = new MiriamData(MiriamType.MESH_2012, "D012402"); - MeSH mesh = meshParser.getMeSH(meshID); - assertTrue(mesh != null); - assertTrue(mesh.getMeSHId() != null); - assertTrue(mesh.getName() != null); - assertTrue(mesh.getName().toLowerCase().equals("rotenone")); - assertTrue(mesh.getDescription() != null); - assertEquals(0, mesh.getSynonyms().size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + // Rotenone disease -no synonyms + MiriamData meshID = new MiriamData(MiriamType.MESH_2012, "D012402"); + MeSH mesh = meshParser.getMeSH(meshID); + assertTrue(mesh != null); + assertTrue(mesh.getMeSHId() != null); + assertTrue(mesh.getName() != null); + assertTrue(mesh.getName().toLowerCase().equals("rotenone")); + assertTrue(mesh.getDescription() != null); + assertEquals(0, mesh.getSynonyms().size()); } @Test public void testCreateChemicalListFromDB3() throws Exception { - try { - // One synonyms - MiriamData meshID = new MiriamData(MiriamType.MESH_2012, "C503102"); - MeSH mesh = meshParser.getMeSH(meshID); - assertTrue(mesh != null); - assertTrue(mesh.getMeSHId() != null); - assertTrue(mesh.getName() != null); - assertTrue( - mesh.getName().toLowerCase().contains("1-(3-(2-(1-benzothiophen-5-yl) ethoxy) propyl)-3-azetidinol maleate")); - assertNull(mesh.getDescription()); - assertEquals(1, mesh.getSynonyms().size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test + // One synonyms + MiriamData meshID = new MiriamData(MiriamType.MESH_2012, "C503102"); + MeSH mesh = meshParser.getMeSH(meshID); + assertTrue(mesh != null); + assertTrue(mesh.getMeSHId() != null); + assertTrue(mesh.getName() != null); + assertTrue( + mesh.getName().toLowerCase().contains("1-(3-(2-(1-benzothiophen-5-yl) ethoxy) propyl)-3-azetidinol maleate")); + assertNull(mesh.getDescription()); + assertEquals(1, mesh.getSynonyms().size()); + } + + @Test(expected = AnnotatorException.class) public void testGetMEshWithNetworkProblems() throws Exception { - try { - // Parkinson disease - MiriamData meshID = new MiriamData(MiriamType.MESH_2012, "D004298"); - MeSHParser parserUnderTest = new MeSHParser(); - WebPageDownloader webPageDownloader = Mockito.mock(WebPageDownloader.class); - when(webPageDownloader.getFromNetwork(anyString(), anyString(), nullable(String.class))) - .thenThrow(new IOException()); - parserUnderTest.setWebPageDownloader(webPageDownloader); - - parserUnderTest.getMeSH(meshID); - fail("Exception expected"); - } catch (AnnotatorException e) { - assertTrue(e.getMessage().contains("Problem with accessing MeSH database")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + // Parkinson disease + MiriamData meshID = new MiriamData(MiriamType.MESH_2012, "D004298"); + MeSHParser parserUnderTest = new MeSHParser(); + WebPageDownloader webPageDownloader = Mockito.mock(WebPageDownloader.class); + when(webPageDownloader.getFromNetwork(anyString(), anyString(), nullable(String.class))) + .thenThrow(new IOException()); + parserUnderTest.setWebPageDownloader(webPageDownloader); + + parserUnderTest.getMeSH(meshID); } /** @@ -215,81 +143,46 @@ public class MeSHParserTest extends AnnotationTestFunctions { @Test public void testCachableInterfaceInvalidateChemical() throws Exception { - try { - MiriamData meshID = new MiriamData(MiriamType.MESH_2012, "D010300"); - MeSH mesh = meshParser.getMeSH(meshID); - assertNotNull(mesh); + MiriamData meshID = new MiriamData(MiriamType.MESH_2012, "D010300"); + MeSH mesh = meshParser.getMeSH(meshID); + assertNotNull(mesh); - cache.invalidateByQuery(meshParser.getIdentifier(meshID), meshParser.getCacheType()); + cache.invalidateByQuery(meshParser.getIdentifier(meshID), meshParser.getCacheType()); - permanentDatabaseLevelCache.waitToFinishTasks(); + permanentDatabaseLevelCache.waitToFinishTasks(); - MeSH mesh2 = meshParser.getMeSH(meshID); - assertNotNull(mesh2); + MeSH mesh2 = meshParser.getMeSH(meshID); + assertNotNull(mesh2); - assertFalse("Value wasn't refreshed from db", mesh.equals(mesh2)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertFalse("Value wasn't refreshed from db", mesh.equals(mesh2)); } @Test public void testCleanHtml() { - try { - String withouthHtml = meshParser.cleanHtml( - "<TD colspan=1>One of the catecholamine <A href=\"/cgi/mesh/2014/MB_cgi?mode=&term=NEUROTRANSMITTERS\">"); - assertFalse(withouthHtml.contains("<")); - assertFalse(withouthHtml.contains(">")); - assertTrue(withouthHtml.contains("catecholamine")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - + String withouthHtml = meshParser.cleanHtml( + "<TD colspan=1>One of the catecholamine <A href=\"/cgi/mesh/2014/MB_cgi?mode=&term=NEUROTRANSMITTERS\">"); + assertFalse(withouthHtml.contains("<")); + assertFalse(withouthHtml.contains(">")); + assertTrue(withouthHtml.contains("catecholamine")); } - @Test + @Test(expected = InvalidArgumentException.class) public void testRefreshInvalidCacheQuery() throws Exception { - try { - meshParser.refreshCacheQuery("invalid_query"); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - assertTrue(e.getMessage().contains("Don't know what to do")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + meshParser.refreshCacheQuery("invalid_query"); } - @Test + @Test(expected = InvalidArgumentException.class) public void testRefreshInvalidCacheQuery2() throws Exception { - try { - meshParser.refreshCacheQuery(new Object()); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - assertTrue(e.getMessage().contains("Don't know what to do")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + meshParser.refreshCacheQuery(new Object()); } - @Test + @Test(expected = InvalidArgumentException.class) public void testRefreshInvalidCacheQuery3() throws Exception { - try { - String query = MeSHParser.MESH_PREFIX + "::::::"; - meshParser.refreshCacheQuery(query); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - assertTrue(e.getMessage().contains("Problematic query")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String query = MeSHParser.MESH_PREFIX + "::::::"; + meshParser.refreshCacheQuery(query); } - @Test + @Test(expected=SourceNotAvailable.class) public void testRefreshWhenProblemWithSourceDb() throws Exception { WebPageDownloader downloader = meshParser.getWebPageDownloader(); GeneralCacheInterface cache = meshParser.getCache(); @@ -303,12 +196,6 @@ public class MeSHParserTest extends AnnotationTestFunctions { MiriamData meshID = new MiriamData(MiriamType.MESH_2012, "D010300"); meshParser.refreshCacheQuery(meshParser.getIdentifier(meshID)); - fail("Exception expected"); - } catch (SourceNotAvailable e) { - assertTrue(e.getMessage().contains("Problem with accessing Mesh database")); - } catch (Exception e) { - e.printStackTrace(); - throw e; } finally { meshParser.setWebPageDownloader(downloader); meshParser.setCache(cache); @@ -324,9 +211,6 @@ public class MeSHParserTest extends AnnotationTestFunctions { .thenThrow(new IOException()); meshParser.setWebPageDownloader(mockDownloader); assertEquals(ExternalServiceStatusType.DOWN, meshParser.getServiceStatus().getStatus()); - } catch (Exception e) { - e.printStackTrace(); - throw e; } finally { meshParser.setWebPageDownloader(downloader); } @@ -341,9 +225,6 @@ public class MeSHParserTest extends AnnotationTestFunctions { .thenThrow(new WrongResponseCodeIOException(null, HttpStatus.SC_NOT_FOUND)); meshParser.setWebPageDownloader(mockDownloader); assertEquals(ExternalServiceStatusType.CHANGED, meshParser.getServiceStatus().getStatus()); - } catch (Exception e) { - e.printStackTrace(); - throw e; } finally { meshParser.setWebPageDownloader(downloader); } diff --git a/annotation/src/test/java/lcsb/mapviewer/annotation/services/MiRNAParserTest.java b/annotation/src/test/java/lcsb/mapviewer/annotation/services/MiRNAParserTest.java index 3f59e26ed3caeab00f110f8f3a83b366b1ee4ff9..ba35eb5f63e097a663322de973a5e9ce06750c59 100644 --- a/annotation/src/test/java/lcsb/mapviewer/annotation/services/MiRNAParserTest.java +++ b/annotation/src/test/java/lcsb/mapviewer/annotation/services/MiRNAParserTest.java @@ -1,30 +1,19 @@ package lcsb.mapviewer.annotation.services; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.Mockito.when; - -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import org.apache.logging.log4j.*; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import static org.junit.Assert.*; +import static org.mockito.ArgumentMatchers.*; +import static org.mockito.Mockito.*; + +import java.util.*; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.junit.*; import org.mockito.Mockito; import org.springframework.beans.factory.annotation.Autowired; import lcsb.mapviewer.annotation.AnnotationTestFunctions; -import lcsb.mapviewer.annotation.cache.GeneralCacheInterface; -import lcsb.mapviewer.annotation.cache.PermanentDatabaseLevelCacheInterface; -import lcsb.mapviewer.annotation.cache.SourceNotAvailable; +import lcsb.mapviewer.annotation.cache.*; import lcsb.mapviewer.annotation.data.MiRNA; import lcsb.mapviewer.annotation.data.Target; import lcsb.mapviewer.common.exception.InvalidArgumentException; @@ -58,41 +47,30 @@ public class MiRNAParserTest extends AnnotationTestFunctions { @Test public void testFindMultipleByIDFromDB() throws Exception { - try { - List<String> names = new ArrayList<>(); - names.add("gga-miR-489-3p"); - names.add("rno-miR-9a-5p"); - List<MiRNA> listFromDB = miRNAParser.getMiRnasByNames(names); - assertTrue(!listFromDB.isEmpty()); - assertEquals(2, listFromDB.size()); - assertEquals(1, listFromDB.get(0).getTargets().size()); - assertEquals(5, listFromDB.get(1).getTargets().size()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + List<String> names = new ArrayList<>(); + names.add("gga-miR-489-3p"); + names.add("rno-miR-9a-5p"); + List<MiRNA> listFromDB = miRNAParser.getMiRnasByNames(names); + assertTrue(!listFromDB.isEmpty()); + assertEquals(2, listFromDB.size()); + assertEquals(1, listFromDB.get(0).getTargets().size()); + assertEquals(5, listFromDB.get(1).getTargets().size()); } @Test public void testFindById() throws Exception { - try { - List<String> names = new ArrayList<>(); - names.add("mmu-miR-122-5p"); - List<MiRNA> listFromDB = miRNAParser.getMiRnasByNames(names); - assertEquals(1, listFromDB.size()); - MiRNA mirna = listFromDB.get(0); - for (Target target : mirna.getTargets()) { - assertNotNull(target.getName()); - assertEquals(new MiriamData(MiriamType.TAXONOMY, "10090"), target.getOrganism()); - } - } catch (Exception e) { - e.printStackTrace(); - throw e; + List<String> names = new ArrayList<>(); + names.add("mmu-miR-122-5p"); + List<MiRNA> listFromDB = miRNAParser.getMiRnasByNames(names); + assertEquals(1, listFromDB.size()); + MiRNA mirna = listFromDB.get(0); + for (Target target : mirna.getTargets()) { + assertNotNull(target.getName()); + assertEquals(new MiriamData(MiriamType.TAXONOMY, "10090"), target.getOrganism()); } } - @Test + @Test(expected = MiRNASearchException.class) public void testFindWhenProblemWithTaxonomy() throws Exception { TaxonomyBackend taxonomyBackend = miRNAParser.getTaxonomyBackend(); GeneralCacheInterface cache = miRNAParser.getCache(); @@ -103,15 +81,7 @@ public class MiRNAParserTest extends AnnotationTestFunctions { TaxonomyBackend backend = Mockito.mock(TaxonomyBackend.class); when(backend.getByName(anyString())).thenThrow(new TaxonomySearchException(null, null)); miRNAParser.setTaxonomyBackend(backend); - try { - miRNAParser.getMiRnasByNames(names); - fail("Exception expected"); - } catch (MiRNASearchException e) { - - } - } catch (Exception e) { - e.printStackTrace(); - throw e; + miRNAParser.getMiRnasByNames(names); } finally { miRNAParser.setCache(cache); miRNAParser.setTaxonomyBackend(taxonomyBackend); @@ -120,170 +90,114 @@ public class MiRNAParserTest extends AnnotationTestFunctions { @Test public void testFindById2() throws Exception { - try { - List<String> names = new ArrayList<>(); - names.add("hsa-miR-122-5p"); - List<MiRNA> listFromDB = miRNAParser.getMiRnasByNames(names); - assertEquals(1, listFromDB.size()); - MiRNA mirna = listFromDB.get(0); - for (Target target : mirna.getTargets()) { - assertNotNull(target.getName()); - } - } catch (Exception e) { - e.printStackTrace(); - throw e; + List<String> names = new ArrayList<>(); + names.add("hsa-miR-122-5p"); + List<MiRNA> listFromDB = miRNAParser.getMiRnasByNames(names); + assertEquals(1, listFromDB.size()); + MiRNA mirna = listFromDB.get(0); + for (Target target : mirna.getTargets()) { + assertNotNull(target.getName()); } } @Test public void testFindByTarget() throws Exception { - - try { - Set<MiriamData> targets = new HashSet<MiriamData>(); - MiriamData hgncTarget = new MiriamData(MiriamType.HGNC_SYMBOL, "PLAG1"); - targets.add(hgncTarget); - List<MiRNA> listFromDB = miRNAParser.getMiRnaListByTargets(targets); - assertTrue(listFromDB.size() > 0); - for (MiRNA miRNA : listFromDB) { - boolean found = false; - for (Target targt : miRNA.getTargets()) { - if (targt.getGenes().contains(hgncTarget)) { - found = true; - } + Set<MiriamData> targets = new HashSet<MiriamData>(); + MiriamData hgncTarget = new MiriamData(MiriamType.HGNC_SYMBOL, "PLAG1"); + targets.add(hgncTarget); + List<MiRNA> listFromDB = miRNAParser.getMiRnaListByTargets(targets); + assertTrue(listFromDB.size() > 0); + for (MiRNA miRNA : listFromDB) { + boolean found = false; + for (Target targt : miRNA.getTargets()) { + if (targt.getGenes().contains(hgncTarget)) { + found = true; } - assertTrue(found); } - } catch (Exception e) { - e.printStackTrace(); - throw e; + assertTrue(found); } } @Test public void testFindByTargetWithAnnotator() throws Exception { - - try { - Set<MiriamData> targets = new HashSet<>(); - MiriamData hgncTarget = new MiriamData(MiriamType.HGNC_SYMBOL, "PLAG1", String.class); - targets.add(hgncTarget); - List<MiRNA> listFromDB = miRNAParser.getMiRnaListByTargets(targets); - assertTrue(listFromDB.size() > 0); - hgncTarget.setAnnotator(null); - for (MiRNA miRNA : listFromDB) { - boolean found = false; - for (Target targt : miRNA.getTargets()) { - if (targt.getGenes().contains(hgncTarget)) { - found = true; - } + Set<MiriamData> targets = new HashSet<>(); + MiriamData hgncTarget = new MiriamData(MiriamType.HGNC_SYMBOL, "PLAG1", String.class); + targets.add(hgncTarget); + List<MiRNA> listFromDB = miRNAParser.getMiRnaListByTargets(targets); + assertTrue(listFromDB.size() > 0); + hgncTarget.setAnnotator(null); + for (MiRNA miRNA : listFromDB) { + boolean found = false; + for (Target targt : miRNA.getTargets()) { + if (targt.getGenes().contains(hgncTarget)) { + found = true; } - assertTrue(found); } - } catch (Exception e) { - e.printStackTrace(); - throw e; + assertTrue(found); } } @Test(timeout = 50000) public void testCachableInterfaceInvalidateMiRNA() throws Exception { - try { - List<String> listIds = new ArrayList<>(); - listIds.add("gga-miR-489-3p"); - List<MiRNA> list = miRNAParser.getMiRnasByNames(listIds); - assertTrue(!list.isEmpty()); - assertEquals(1, list.get(0).getTargets().size()); - - cache.invalidateByQuery(MiRNAParser.MI_RNA_PREFIX + list.get(0).getName(), miRNAParser.getCacheType()); + List<String> listIds = new ArrayList<>(); + listIds.add("gga-miR-489-3p"); + List<MiRNA> list = miRNAParser.getMiRnasByNames(listIds); + assertTrue(!list.isEmpty()); + assertEquals(1, list.get(0).getTargets().size()); - permanentDatabaseLevelCache.waitToFinishTasks(); + cache.invalidateByQuery(MiRNAParser.MI_RNA_PREFIX + list.get(0).getName(), miRNAParser.getCacheType()); - listIds.clear(); - listIds.add(list.get(0).getName()); + permanentDatabaseLevelCache.waitToFinishTasks(); - List<MiRNA> list2 = miRNAParser.getMiRnasByNames(listIds); - assertNotNull(list2); - assertEquals(1, list2.size()); - assertFalse("Value wasn't refreshed from db", list.get(0).equals(list2.get(0))); - assertTrue(list.get(0).getName().equals(list2.get(0).getName())); + listIds.clear(); + listIds.add(list.get(0).getName()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + List<MiRNA> list2 = miRNAParser.getMiRnasByNames(listIds); + assertNotNull(list2); + assertEquals(1, list2.size()); + assertFalse("Value wasn't refreshed from db", list.get(0).equals(list2.get(0))); + assertTrue(list.get(0).getName().equals(list2.get(0).getName())); } @Test public void testGetMiRna() throws Exception { - try { - String mirBaseName = "hsa-miR-296-5p"; - List<String> names = new ArrayList<>(); - names.add(mirBaseName); - List<MiRNA> list = miRNAParser.getMiRnasByNames(names); - assertTrue(!list.isEmpty()); - MiRNA mirna = list.get(0); - - for (Target target : mirna.getTargets()) { - Set<MiriamData> mds = new HashSet<>(); - mds.addAll(target.getReferences()); - assertEquals("Target contains duplicat references: " + target, mds.size(), target.getReferences().size()); - } + String mirBaseName = "hsa-miR-296-5p"; + List<String> names = new ArrayList<>(); + names.add(mirBaseName); + List<MiRNA> list = miRNAParser.getMiRnasByNames(names); + assertTrue(!list.isEmpty()); + MiRNA mirna = list.get(0); - } catch (Exception e) { - e.printStackTrace(); - throw e; + for (Target target : mirna.getTargets()) { + Set<MiriamData> mds = new HashSet<>(); + mds.addAll(target.getReferences()); + assertEquals("Target contains duplicat references: " + target, mds.size(), target.getReferences().size()); } } @Test public void invalidMiRNAToString2() throws Exception { - try { - - String str = miRNAParser.getMiRnaSerializer().objectToString(null); - assertNull(str); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String str = miRNAParser.getMiRnaSerializer().objectToString(null); + assertNull(str); } - @Test + @Test(expected = InvalidArgumentException.class) public void testRefreshInvalidCacheQuery() throws Exception { - try { - miRNAParser.refreshCacheQuery("invalid_query"); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - assertTrue(e.getMessage().contains("Don't know what to do")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + miRNAParser.refreshCacheQuery("invalid_query"); } - @Test + @Test(expected = InvalidArgumentException.class) public void testRefreshInvalidCacheQuery2() throws Exception { - try { - miRNAParser.refreshCacheQuery(new Object()); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - assertTrue(e.getMessage().contains("Don't know what to do")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + miRNAParser.refreshCacheQuery(new Object()); } @Test public void testRefreshCacheQuery() throws Exception { - try { - Object result = miRNAParser.refreshCacheQuery(MiRNAParser.MI_RNA_PREFIX + "mmu-miR-122-5p"); - assertNotNull(result); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Object result = miRNAParser.refreshCacheQuery(MiRNAParser.MI_RNA_PREFIX + "mmu-miR-122-5p"); + assertNotNull(result); } - @Test + @Test(expected = SourceNotAvailable.class) public void testRefreshCacheQueryWhenProblemWithTaxonomy() throws Exception { TaxonomyBackend taxonomyBackend = miRNAParser.getTaxonomyBackend(); try { @@ -291,11 +205,6 @@ public class MiRNAParserTest extends AnnotationTestFunctions { when(mockBackend.getByName(anyString())).thenThrow(new TaxonomySearchException(null, null)); miRNAParser.setTaxonomyBackend(mockBackend); miRNAParser.refreshCacheQuery(MiRNAParser.MI_RNA_PREFIX + "mmu-miR-122-5p"); - fail("Exception expected"); - } catch (SourceNotAvailable e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; } finally { miRNAParser.setTaxonomyBackend(taxonomyBackend); } @@ -303,50 +212,31 @@ public class MiRNAParserTest extends AnnotationTestFunctions { @Test public void testRefreshCacheQuery2() throws Exception { - try { - Object result = miRNAParser - .refreshCacheQuery(MiRNAParser.MI_RNA_TARGET_PREFIX + MiriamType.HGNC_SYMBOL + ":" + "PLAG1"); - assertNotNull(result); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Object result = miRNAParser + .refreshCacheQuery(MiRNAParser.MI_RNA_TARGET_PREFIX + MiriamType.HGNC_SYMBOL + ":" + "PLAG1"); + assertNotNull(result); } @Test public void testGetEmptySuggestedQueryList() throws Exception { - try { - Project project = new Project(); - project.setId(-1); - - List<String> result = miRNAParser.getSuggestedQueryList(project); + Project project = new Project(); + project.setId(-1); - assertEquals(0, result.size()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + List<String> result = miRNAParser.getSuggestedQueryList(project); + assertEquals(0, result.size()); } @Test public void testGetSuggestedQueryList() throws Exception { - try { - Project project = new Project(); - project.setId(-2); - Model model = getModelForFile("testFiles/target_mirna/target.xml", false); - project.addModel(model); - - List<String> result = miRNAParser.getSuggestedQueryList(project); + Project project = new Project(); + project.setId(-2); + Model model = getModelForFile("testFiles/target_mirna/target.xml", false); + project.addModel(model); - assertTrue(result.size() > 0); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + List<String> result = miRNAParser.getSuggestedQueryList(project); + assertTrue(result.size() > 0); } } diff --git a/annotation/src/test/java/lcsb/mapviewer/annotation/services/MiriamConnectorTest.java b/annotation/src/test/java/lcsb/mapviewer/annotation/services/MiriamConnectorTest.java index 75ca732f3a4342751fc0cb210728dc47a2d29b13..7231d204166b4c1227ad107074bcf68d8c9fbf3d 100644 --- a/annotation/src/test/java/lcsb/mapviewer/annotation/services/MiriamConnectorTest.java +++ b/annotation/src/test/java/lcsb/mapviewer/annotation/services/MiriamConnectorTest.java @@ -1,34 +1,22 @@ package lcsb.mapviewer.annotation.services; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.ArgumentMatchers.nullable; -import static org.mockito.Mockito.when; +import static org.junit.Assert.*; +import static org.mockito.ArgumentMatchers.*; +import static org.mockito.Mockito.*; import java.io.IOException; import java.lang.reflect.Field; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.mockito.Mockito; import org.springframework.beans.factory.annotation.Autowired; import lcsb.mapviewer.annotation.AnnotationTestFunctions; -import lcsb.mapviewer.annotation.cache.GeneralCacheInterface; -import lcsb.mapviewer.annotation.cache.SourceNotAvailable; -import lcsb.mapviewer.annotation.cache.WebPageDownloader; +import lcsb.mapviewer.annotation.cache.*; import lcsb.mapviewer.common.exception.InvalidArgumentException; -import lcsb.mapviewer.model.map.MiriamData; -import lcsb.mapviewer.model.map.MiriamRelationType; -import lcsb.mapviewer.model.map.MiriamType; +import lcsb.mapviewer.model.map.*; public class MiriamConnectorTest extends AnnotationTestFunctions { Logger logger = LogManager.getLogger(MiriamConnectorTest.class); @@ -50,138 +38,79 @@ public class MiriamConnectorTest extends AnnotationTestFunctions { @Test public void testGoUri() throws Exception { - try { - assertFalse(MiriamType.GO.getUris().size() == 1); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertFalse(MiriamType.GO.getUris().size() == 1); } @Test(timeout = 15000) public void testMeshUrl() throws Exception { - try { - MiriamData md = new MiriamData(MiriamRelationType.BQ_BIOL_IS_DESCRIBED_BY, MiriamType.MESH_2012, "D004249"); + MiriamData md = new MiriamData(MiriamRelationType.BQ_BIOL_IS_DESCRIBED_BY, MiriamType.MESH_2012, "D004249"); - assertNotNull(getWebpage(miriamConnector.getUrlString(md))); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertNotNull(getWebpage(miriamConnector.getUrlString(md))); } @Test public void testGetUrl() throws Exception { - try { - MiriamData md = TaxonomyBackend.HUMAN_TAXONOMY; - - String url = miriamConnector.getUrlString(md); - assertNotNull(url); + MiriamData md = TaxonomyBackend.HUMAN_TAXONOMY; - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String url = miriamConnector.getUrlString(md); + assertNotNull(url); } - @Test + @Test(expected = InvalidArgumentException.class) public void testGetUrlForInvalidMiriam() throws Exception { - try { - miriamConnector.getUrlString(new MiriamData()); - } catch (InvalidArgumentException e) { - assertTrue(e.getMessage().contains("Data type cannot be empty")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + miriamConnector.getUrlString(new MiriamData()); } - @Test + @Test(expected = InvalidArgumentException.class) public void testGetUrlForInvalidMiriam2() throws Exception { - try { - miriamConnector.getUrlString(new MiriamData(MiriamType.UNKNOWN, "")); - } catch (InvalidArgumentException e) { - assertTrue(e.getMessage().contains("cannot be retreived")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + miriamConnector.getUrlString(new MiriamData(MiriamType.UNKNOWN, "")); } @Test public void testGetUrlForInvalidMiriam3() throws Exception { - try { - String url = miriamConnector.getUrlString(new MiriamData(MiriamType.ENTREZ, "abc")); - assertNull(url); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String url = miriamConnector.getUrlString(new MiriamData(MiriamType.ENTREZ, "abc")); + assertNull(url); } @Test public void testIsValidIdentifier() throws Exception { - try { - assertTrue(miriamConnector.isValidIdentifier(MiriamType.ENTREZ.getCommonName() + ":" + "1234")); - assertFalse(miriamConnector.isValidIdentifier("blablabla")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertTrue(miriamConnector.isValidIdentifier(MiriamType.ENTREZ.getCommonName() + ":" + "1234")); + assertFalse(miriamConnector.isValidIdentifier("blablabla")); } @Test public void testResolveUrl() throws Exception { - try { - for (MiriamType mt : MiriamType.values()) { - boolean deprecated = false; - try { - Field f = MiriamType.class.getField(mt.name()); - if (f.isAnnotationPresent(Deprecated.class)) - deprecated = true; - } catch (NoSuchFieldException | SecurityException e) { - } - - if (!deprecated) { - - assertTrue("Invalid MiriamType (" + mt + ") for MiriamType: " + mt, miriamConnector.isValidMiriamType(mt)); - } + for (MiriamType mt : MiriamType.values()) { + boolean deprecated = false; + try { + Field f = MiriamType.class.getField(mt.name()); + if (f.isAnnotationPresent(Deprecated.class)) + deprecated = true; + } catch (NoSuchFieldException | SecurityException e) { } - } catch (Exception e) { - e.printStackTrace(); - throw e; + if (!deprecated) { + + assertTrue("Invalid MiriamType (" + mt + ") for MiriamType: " + mt, miriamConnector.isValidMiriamType(mt)); + } } } @Test public void testGetUrlForDoi() throws Exception { - try { - // exclude first cached value - MiriamData md = new MiriamData(MiriamType.DOI, "10.1038/npjsba.2016.20"); + // exclude first cached value + MiriamData md = new MiriamData(MiriamType.DOI, "10.1038/npjsba.2016.20"); - String url = miriamConnector.getUrlString(md); - assertNotNull(url); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String url = miriamConnector.getUrlString(md); + assertNotNull(url); } @Test public void testMiriamDataToUri() throws Exception { - try { - assertNotNull(miriamConnector.miriamDataToUri(TaxonomyBackend.HUMAN_TAXONOMY)); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertNotNull(miriamConnector.miriamDataToUri(TaxonomyBackend.HUMAN_TAXONOMY)); } - @Test + @Test(expected = SourceNotAvailable.class) public void testRefreshCacheQueryNotAvailable() throws Exception { WebPageDownloader downloader = miriamConnector.getWebPageDownloader(); try { @@ -190,62 +119,31 @@ public class MiriamConnectorTest extends AnnotationTestFunctions { .thenThrow(new IOException()); miriamConnector.setWebPageDownloader(mockDownloader); miriamConnector.refreshCacheQuery("http://google.pl/"); - fail("Exception expected"); - } catch (SourceNotAvailable e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; } finally { miriamConnector.setWebPageDownloader(downloader); } } - @Test + @Test(expected = InvalidArgumentException.class) public void testRefreshInvalidCacheQuery() throws Exception { - try { - miriamConnector.refreshCacheQuery("invalid_query"); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - assertTrue(e.getMessage().contains("Don't know what to do")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + miriamConnector.refreshCacheQuery("invalid_query"); } - @Test + @Test(expected = InvalidArgumentException.class) public void testRefreshInvalidCacheQuery2() throws Exception { - try { - miriamConnector.refreshCacheQuery(new Object()); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - assertTrue(e.getMessage().contains("Don't know what to do")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + miriamConnector.refreshCacheQuery(new Object()); } @Test public void testCheckValidyOfUnknownMiriamType() throws Exception { - try { - // user connector without cache - boolean value = miriamConnector.isValidMiriamType(MiriamType.UNKNOWN); - assertFalse(value); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + // user connector without cache + boolean value = miriamConnector.isValidMiriamType(MiriamType.UNKNOWN); + assertFalse(value); } @Test public void testStatus() throws Exception { - try { - assertEquals(ExternalServiceStatusType.OK, miriamConnector.getServiceStatus().getStatus()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(ExternalServiceStatusType.OK, miriamConnector.getServiceStatus().getStatus()); } } diff --git a/annotation/src/test/java/lcsb/mapviewer/annotation/services/ModelAnnotatorTest.java b/annotation/src/test/java/lcsb/mapviewer/annotation/services/ModelAnnotatorTest.java index 062823a786d33d99ee39ca8ea907e6387c9e953a..935e765e486376ae6bdf4b7468aa0532f75b1ab0 100644 --- a/annotation/src/test/java/lcsb/mapviewer/annotation/services/ModelAnnotatorTest.java +++ b/annotation/src/test/java/lcsb/mapviewer/annotation/services/ModelAnnotatorTest.java @@ -1,43 +1,22 @@ package lcsb.mapviewer.annotation.services; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; +import static org.junit.Assert.*; + +import java.util.*; import org.apache.commons.lang3.mutable.MutableDouble; -import org.apache.logging.log4j.*; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.junit.*; import org.springframework.beans.factory.annotation.Autowired; import lcsb.mapviewer.annotation.AnnotationTestFunctions; import lcsb.mapviewer.annotation.services.annotators.ElementAnnotator; import lcsb.mapviewer.common.IProgressUpdater; -import lcsb.mapviewer.model.map.BioEntity; -import lcsb.mapviewer.model.map.MiriamData; -import lcsb.mapviewer.model.map.MiriamRelationType; -import lcsb.mapviewer.model.map.MiriamType; -import lcsb.mapviewer.model.map.model.Model; -import lcsb.mapviewer.model.map.model.ModelFullIndexed; -import lcsb.mapviewer.model.map.model.ModelSubmodelConnection; -import lcsb.mapviewer.model.map.model.SubmodelType; +import lcsb.mapviewer.model.map.*; +import lcsb.mapviewer.model.map.model.*; import lcsb.mapviewer.model.map.reaction.Reaction; -import lcsb.mapviewer.model.map.species.Element; -import lcsb.mapviewer.model.map.species.GenericProtein; -import lcsb.mapviewer.model.map.species.Ion; -import lcsb.mapviewer.model.map.species.Protein; -import lcsb.mapviewer.model.map.species.Species; +import lcsb.mapviewer.model.map.species.*; import lcsb.mapviewer.model.user.UserAnnotationSchema; import lcsb.mapviewer.model.user.UserClassAnnotators; import lcsb.mapviewer.persist.dao.map.ModelDao; @@ -66,346 +45,251 @@ public class ModelAnnotatorTest extends AnnotationTestFunctions { @Test public void testAnnotateModel() { - try { - Model model = new ModelFullIndexed(null); - - model.addReaction(new Reaction()); + Model model = new ModelFullIndexed(null); - Species proteinAlias1 = new GenericProtein("a1"); - proteinAlias1.setName("SNCA"); + model.addReaction(new Reaction()); - Species proteinAlias2 = new GenericProtein("a2"); - proteinAlias2.setName("PDK1"); - proteinAlias2.addMiriamData(new MiriamData(MiriamRelationType.BQ_BIOL_IS_DESCRIBED_BY, MiriamType.CAS, "c")); + Species proteinAlias1 = new GenericProtein("a1"); + proteinAlias1.setName("SNCA"); - model.addElement(proteinAlias1); - model.addElement(proteinAlias2); + Species proteinAlias2 = new GenericProtein("a2"); + proteinAlias2.setName("PDK1"); + proteinAlias2.addMiriamData(new MiriamData(MiriamRelationType.BQ_BIOL_IS_DESCRIBED_BY, MiriamType.CAS, "c")); - modelAnnotator.annotateModel(model, updater, modelAnnotator.createDefaultAnnotatorSchema()); + model.addElement(proteinAlias1); + model.addElement(proteinAlias2); - assertTrue(model.getElementByElementId("a1").getMiriamData().size() > 0); - assertTrue(model.getElementByElementId("a2").getMiriamData().size() >= 1); + modelAnnotator.annotateModel(model, updater, modelAnnotator.createDefaultAnnotatorSchema()); - modelAnnotator.annotateModel(model, updater, modelAnnotator.createDefaultAnnotatorSchema()); + assertTrue(model.getElementByElementId("a1").getMiriamData().size() > 0); + assertTrue(model.getElementByElementId("a2").getMiriamData().size() >= 1); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + modelAnnotator.annotateModel(model, updater, modelAnnotator.createDefaultAnnotatorSchema()); } @Test public void testAnnotateModelWithGivenAnnotators() throws Exception { - try { - Model model = new ModelFullIndexed(null); - GenericProtein species = new GenericProtein("id1"); - species.setName("SNCA"); - model.addElement(species); - - Ion species2 = new Ion("id2"); - species2.setName("h2o"); - species2.addMiriamData(new MiriamData(MiriamRelationType.BQ_BIOL_IS_DESCRIBED_BY, MiriamType.CHEBI, "12345")); - model.addElement(species2); - model.addReaction(new Reaction()); - - UserAnnotationSchema annotationSchema = new UserAnnotationSchema(); - - UserClassAnnotators proteinAnnotators = new UserClassAnnotators(GenericProtein.class); - proteinAnnotators.setAnnotators(new ArrayList<>()); - annotationSchema.addClassAnnotator(proteinAnnotators); - - UserClassAnnotators ionAnnotators = new UserClassAnnotators(Ion.class); - ionAnnotators.setAnnotators(modelAnnotator.getDefaultAnnotators(Ion.class)); - annotationSchema.addClassAnnotator(ionAnnotators); - - modelAnnotator.annotateModel(model, updater, annotationSchema); - - // we didn't annotate protein - assertEquals(0, species.getMiriamData().size()); - // but we should annotate ion - assertFalse(species2.getFullName().isEmpty()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Model model = new ModelFullIndexed(null); + GenericProtein species = new GenericProtein("id1"); + species.setName("SNCA"); + model.addElement(species); + + Ion species2 = new Ion("id2"); + species2.setName("h2o"); + species2.addMiriamData(new MiriamData(MiriamRelationType.BQ_BIOL_IS_DESCRIBED_BY, MiriamType.CHEBI, "12345")); + model.addElement(species2); + model.addReaction(new Reaction()); + + UserAnnotationSchema annotationSchema = new UserAnnotationSchema(); + + UserClassAnnotators proteinAnnotators = new UserClassAnnotators(GenericProtein.class); + proteinAnnotators.setAnnotators(new ArrayList<>()); + annotationSchema.addClassAnnotator(proteinAnnotators); + + UserClassAnnotators ionAnnotators = new UserClassAnnotators(Ion.class); + ionAnnotators.setAnnotators(modelAnnotator.getDefaultAnnotators(Ion.class)); + annotationSchema.addClassAnnotator(ionAnnotators); + + modelAnnotator.annotateModel(model, updater, annotationSchema); + + // we didn't annotate protein + assertEquals(0, species.getMiriamData().size()); + // but we should annotate ion + assertFalse(species2.getFullName().isEmpty()); } @Test public void testCopyMissingAnnotationsInCD() throws Exception { - try { - Model model = getModelForFile("testFiles/annotation/copyingAnnotationModel.xml", true); - - modelAnnotator.copyAnnotationFromOtherSpecies(model, updater); + Model model = getModelForFile("testFiles/annotation/copyingAnnotationModel.xml", true); - for (Species element : model.getSpeciesList()) { - if (element.getName().equals("s4")) - assertEquals(0, element.getMiriamData().size()); - else if (element.getName().equals("hello")) - assertEquals(1, element.getMiriamData().size()); - } + modelAnnotator.copyAnnotationFromOtherSpecies(model, updater); - } catch (Exception e) { - e.printStackTrace(); - throw e; + for (Species element : model.getSpeciesList()) { + if (element.getName().equals("s4")) + assertEquals(0, element.getMiriamData().size()); + else if (element.getName().equals("hello")) + assertEquals(1, element.getMiriamData().size()); } } @Test public void testDuplicateAnnotations() throws Exception { - try { - int counter = 0; - Model model = getModelForFile("testFiles/annotation/duplicate.xml", false); + int counter = 0; + Model model = getModelForFile("testFiles/annotation/duplicate.xml", false); - Set<String> knowAnnotations = new HashSet<String>(); + Set<String> knowAnnotations = new HashSet<String>(); - modelAnnotator.annotateModel(model, updater, modelAnnotator.createDefaultAnnotatorSchema()); - for (MiriamData md : model.getElementByElementId("sa1").getMiriamData()) { - knowAnnotations.add(md.getDataType() + ":" + md.getRelationType() + ":" + md.getResource()); - } - counter = 0; - for (String string : knowAnnotations) { - if (string.contains("29108")) { - counter++; - } + modelAnnotator.annotateModel(model, updater, modelAnnotator.createDefaultAnnotatorSchema()); + for (MiriamData md : model.getElementByElementId("sa1").getMiriamData()) { + knowAnnotations.add(md.getDataType() + ":" + md.getRelationType() + ":" + md.getResource()); + } + counter = 0; + for (String string : knowAnnotations) { + if (string.contains("29108")) { + counter++; } - assertEquals(1, counter); + } + assertEquals(1, counter); - modelAnnotator.annotateModel(model, updater, modelAnnotator.createDefaultAnnotatorSchema()); + modelAnnotator.annotateModel(model, updater, modelAnnotator.createDefaultAnnotatorSchema()); - knowAnnotations.clear(); - for (MiriamData md : model.getElementByElementId("sa1").getMiriamData()) { - knowAnnotations.add(md.getDataType() + ":" + md.getRelationType() + ":" + md.getResource()); - } - counter = 0; - for (String string : knowAnnotations) { - if (string.contains("29108")) { - counter++; - } + knowAnnotations.clear(); + for (MiriamData md : model.getElementByElementId("sa1").getMiriamData()) { + knowAnnotations.add(md.getDataType() + ":" + md.getRelationType() + ":" + md.getResource()); + } + counter = 0; + for (String string : knowAnnotations) { + if (string.contains("29108")) { + counter++; } - assertEquals(1, counter); - - } catch (Exception e) { - e.printStackTrace(); - throw e; } + assertEquals(1, counter); } @Test public void testGetAnnotationsForSYN() throws Exception { - try { - Model model = getModelForFile("testFiles/annotation/emptyAnnotationsSyn1.xml", true); - Element sa1 = model.getElementByElementId("sa1"); - Element sa2 = model.getElementByElementId("sa2"); - - assertFalse(sa1.getNotes().contains("Symbol")); - assertFalse(sa2.getNotes().contains("Symbol")); - modelAnnotator.annotateModel(model, updater, modelAnnotator.createDefaultAnnotatorSchema()); - assertFalse(sa2.getNotes().contains("Symbol")); - assertNotNull(sa1.getSymbol()); - assertFalse(sa1.getSymbol().equals("")); - // modelAnnotator.removeIncorrectAnnotations(model, updater); - assertNotNull(sa1.getSymbol()); - assertFalse(sa1.getSymbol().equals("")); - assertFalse(sa1.getNotes().contains("Symbol")); - assertFalse(sa2.getNotes().contains("Symbol")); - assertNull(sa2.getSymbol()); - - for (Species el : model.getSpeciesList()) { - if (el.getNotes() != null) { - assertFalse("Invalid notes: " + el.getNotes(), el.getNotes().contains("Symbol")); - assertFalse("Invalid notes: " + el.getNotes(), el.getNotes().contains("HGNC")); - } + Model model = getModelForFile("testFiles/annotation/emptyAnnotationsSyn1.xml", true); + Element sa1 = model.getElementByElementId("sa1"); + Element sa2 = model.getElementByElementId("sa2"); + + assertFalse(sa1.getNotes().contains("Symbol")); + assertFalse(sa2.getNotes().contains("Symbol")); + modelAnnotator.annotateModel(model, updater, modelAnnotator.createDefaultAnnotatorSchema()); + assertFalse(sa2.getNotes().contains("Symbol")); + assertNotNull(sa1.getSymbol()); + assertFalse(sa1.getSymbol().equals("")); + // modelAnnotator.removeIncorrectAnnotations(model, updater); + assertNotNull(sa1.getSymbol()); + assertFalse(sa1.getSymbol().equals("")); + assertFalse(sa1.getNotes().contains("Symbol")); + assertFalse(sa2.getNotes().contains("Symbol")); + assertNull(sa2.getSymbol()); + + for (Species el : model.getSpeciesList()) { + if (el.getNotes() != null) { + assertFalse("Invalid notes: " + el.getNotes(), el.getNotes().contains("Symbol")); + assertFalse("Invalid notes: " + el.getNotes(), el.getNotes().contains("HGNC")); } - } catch (Exception e) { - e.printStackTrace(); - throw e; } } @Test public void testFindInmproperAnnotations() throws Exception { - try { - Model model = getModelForFile("testFiles/annotation/centeredAnchorInModifier.xml", true); - Collection<? extends ProblematicAnnotation> results = modelAnnotator.findImproperAnnotations(model, - new IProgressUpdater() { - - @Override - public void setProgress(double progress) { - // TODO Auto-generated method stub - - } - }, null); - assertTrue(results.size() > 0); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Model model = getModelForFile("testFiles/annotation/centeredAnchorInModifier.xml", true); + Collection<? extends ProblematicAnnotation> results = modelAnnotator.findImproperAnnotations(model, + new IProgressUpdater() { + + @Override + public void setProgress(double progress) { + // TODO Auto-generated method stub + + } + }, null); + assertTrue(results.size() > 0); } @Test public void testFindInmproperAnnotations2() throws Exception { - try { - List<MiriamType> list = new ArrayList<>(); - list.add(MiriamType.PUBMED); - Reaction reaction = new Reaction(); - reaction.addMiriamData(new MiriamData(MiriamType.PUBMED, "12345")); - List<ImproperAnnotations> result = modelAnnotator.findImproperAnnotations(reaction, list); - assertEquals("Unexpected improper annotations found: " + result, 0, result.size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + List<MiriamType> list = new ArrayList<>(); + list.add(MiriamType.PUBMED); + Reaction reaction = new Reaction(); + reaction.addMiriamData(new MiriamData(MiriamType.PUBMED, "12345")); + List<ImproperAnnotations> result = modelAnnotator.findImproperAnnotations(reaction, list); + assertEquals("Unexpected improper annotations found: " + result, 0, result.size()); } @Test public void testFindInmproperAnnotations3() throws Exception { - try { - List<MiriamType> list = new ArrayList<>(); - list.add(MiriamType.PUBMED); - Reaction reaction = new Reaction(); - reaction.addMiriamData(new MiriamData(MiriamType.PUBMED, "inv_id")); - List<ImproperAnnotations> result = modelAnnotator.findImproperAnnotations(reaction, list); - assertEquals(1, result.size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + List<MiriamType> list = new ArrayList<>(); + list.add(MiriamType.PUBMED); + Reaction reaction = new Reaction(); + reaction.addMiriamData(new MiriamData(MiriamType.PUBMED, "inv_id")); + List<ImproperAnnotations> result = modelAnnotator.findImproperAnnotations(reaction, list); + assertEquals(1, result.size()); } @Test public void testFindMissingAnnotations() throws Exception { - try { - Model model = getModelForFile("testFiles/annotation/missingAnnotations.xml", false); - Collection<? extends ProblematicAnnotation> results = modelAnnotator.findMissingAnnotations(model, null); - assertEquals(7, results.size()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Model model = getModelForFile("testFiles/annotation/missingAnnotations.xml", false); + Collection<? extends ProblematicAnnotation> results = modelAnnotator.findMissingAnnotations(model, null); + assertEquals(7, results.size()); } @Test public void testFindMissingAnnotations2() throws Exception { - try { - Model model = getModelForFile("testFiles/annotation/missingAnnotations.xml", false); - Map<Class<? extends BioEntity>, Set<MiriamType>> requestedAnnotations = new HashMap<>(); - ; - requestedAnnotations.put(GenericProtein.class, new HashSet<>()); - Collection<? extends ProblematicAnnotation> results = modelAnnotator.findMissingAnnotations(model, - requestedAnnotations); - assertEquals(1, results.size()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Model model = getModelForFile("testFiles/annotation/missingAnnotations.xml", false); + Map<Class<? extends BioEntity>, Set<MiriamType>> requestedAnnotations = new HashMap<>(); + requestedAnnotations.put(GenericProtein.class, new HashSet<>()); + Collection<? extends ProblematicAnnotation> results = modelAnnotator.findMissingAnnotations(model, + requestedAnnotations); + assertEquals(1, results.size()); } @Test public void testAnnotateModelWithDrugMolecule() throws Exception { - try { - Model model = super.getModelForFile("testFiles/annotation/problematic.xml", false); + Model model = super.getModelForFile("testFiles/annotation/problematic.xml", false); - modelAnnotator.annotateModel(model, updater, modelAnnotator.createDefaultAnnotatorSchema()); - modelDao.add(model); + modelAnnotator.annotateModel(model, updater, modelAnnotator.createDefaultAnnotatorSchema()); + modelDao.add(model); - modelDao.delete(model); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + modelDao.delete(model); } @Test public void testGetDefaultRequired() throws Exception { - try { - Map<Class<? extends BioEntity>, Set<MiriamType>> map1 = modelAnnotator.getDefaultRequiredClasses(); - assertNotNull(map1); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Map<Class<? extends BioEntity>, Set<MiriamType>> map1 = modelAnnotator.getDefaultRequiredClasses(); + assertNotNull(map1); } @Test public void testGetDefaultValid() throws Exception { - try { - Map<Class<? extends BioEntity>, Set<MiriamType>> map2 = modelAnnotator.getDefaultValidClasses(); - assertNotNull(map2); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Map<Class<? extends BioEntity>, Set<MiriamType>> map2 = modelAnnotator.getDefaultValidClasses(); + assertNotNull(map2); } @Test public void testPerformAnnotationAndCheckProgress() throws Exception { - try { - Model model = new ModelFullIndexed(null); - Model submodel = new ModelFullIndexed(null); - Model submodel2 = new ModelFullIndexed(null); + Model model = new ModelFullIndexed(null); + Model submodel = new ModelFullIndexed(null); + Model submodel2 = new ModelFullIndexed(null); - GenericProtein protein = new GenericProtein("el"); + GenericProtein protein = new GenericProtein("el"); - model.addSubmodelConnection(new ModelSubmodelConnection(submodel, SubmodelType.UNKNOWN)); - model.addSubmodelConnection(new ModelSubmodelConnection(submodel2, SubmodelType.UNKNOWN)); + model.addSubmodelConnection(new ModelSubmodelConnection(submodel, SubmodelType.UNKNOWN)); + model.addSubmodelConnection(new ModelSubmodelConnection(submodel2, SubmodelType.UNKNOWN)); - model.addElement(protein); - submodel.addElement(protein); - submodel2.addElement(protein); + model.addElement(protein); + submodel.addElement(protein); + submodel2.addElement(protein); - final MutableDouble maxProgress = new MutableDouble(0.0); + final MutableDouble maxProgress = new MutableDouble(0.0); - modelAnnotator.performAnnotations(model, new IProgressUpdater() { - @Override - public void setProgress(double progress) { - maxProgress.setValue(Math.max(progress, maxProgress.getValue())); - } - }); - assertTrue(maxProgress.getValue() <= IProgressUpdater.MAX_PROGRESS); + modelAnnotator.performAnnotations(model, new IProgressUpdater() { + @Override + public void setProgress(double progress) { + maxProgress.setValue(Math.max(progress, maxProgress.getValue())); + } + }); + assertTrue(maxProgress.getValue() <= IProgressUpdater.MAX_PROGRESS); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } } @Test public void testGetAvailableAnnotators() { - try { - List<ElementAnnotator> list = modelAnnotator.getAvailableAnnotators(Protein.class); - assertTrue(list.size() > 0); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + List<ElementAnnotator> list = modelAnnotator.getAvailableAnnotators(Protein.class); + assertTrue(list.size() > 0); } @Test public void testGetAvailableAnnotators2() { - try { - List<ElementAnnotator> list = modelAnnotator.getAvailableAnnotators(); - assertTrue(list.size() > 0); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + List<ElementAnnotator> list = modelAnnotator.getAvailableAnnotators(); + assertTrue(list.size() > 0); } @Test public void testGetAvailableDefaultAnnotators() { - try { - List<ElementAnnotator> list = modelAnnotator.getAvailableDefaultAnnotators(Protein.class); - assertTrue(list.size() > 0); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + List<ElementAnnotator> list = modelAnnotator.getAvailableDefaultAnnotators(Protein.class); + assertTrue(list.size() > 0); } } diff --git a/annotation/src/test/java/lcsb/mapviewer/annotation/services/PubmedParserTest.java b/annotation/src/test/java/lcsb/mapviewer/annotation/services/PubmedParserTest.java index 949bbfb0d0d0f68129a1883cbeeba48d1cb45aed..83aa54626cbca4d4e974bf34177e77261bf5f3c9 100644 --- a/annotation/src/test/java/lcsb/mapviewer/annotation/services/PubmedParserTest.java +++ b/annotation/src/test/java/lcsb/mapviewer/annotation/services/PubmedParserTest.java @@ -1,35 +1,25 @@ package lcsb.mapviewer.annotation.services; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.ArgumentMatchers.nullable; -import static org.mockito.Mockito.when; +import static org.junit.Assert.*; +import static org.mockito.ArgumentMatchers.*; +import static org.mockito.Mockito.*; import java.io.IOException; import java.util.ArrayList; import java.util.List; -import org.apache.logging.log4j.*; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.junit.*; import org.mockito.Mockito; import org.springframework.beans.factory.annotation.Autowired; import lcsb.mapviewer.annotation.AnnotationTestFunctions; -import lcsb.mapviewer.annotation.cache.GeneralCacheInterface; -import lcsb.mapviewer.annotation.cache.PermanentDatabaseLevelCacheInterface; -import lcsb.mapviewer.annotation.cache.SourceNotAvailable; -import lcsb.mapviewer.annotation.cache.WebPageDownloader; -import lcsb.mapviewer.annotation.cache.XmlSerializer; +import lcsb.mapviewer.annotation.cache.*; import lcsb.mapviewer.annotation.data.Article; import lcsb.mapviewer.common.Configuration; import lcsb.mapviewer.common.exception.InvalidArgumentException; +import lcsb.mapviewer.common.exception.InvalidXmlSchemaException; public class PubmedParserTest extends AnnotationTestFunctions { Logger logger = LogManager.getLogger(PubmedParserTest.class); @@ -55,180 +45,116 @@ public class PubmedParserTest extends AnnotationTestFunctions { } @Test - public void test() { - try { - Configuration.setApplicationCacheOn(false); - Article art = pubmedParser.getPubmedArticleById(9481670); - assertNotNull(art); - assertEquals( - "Adjacent asparagines in the NR2-subunit of the NMDA receptor channel control the voltage-dependent block by extracellular Mg2+.", - art.getTitle()); - assertEquals((Integer) 1998, art.getYear()); - assertEquals("The Journal of physiology", art.getJournal()); - assertTrue(art.getStringAuthors().contains("Wollmuth")); - assertTrue(art.getStringAuthors().contains("Kuner")); - assertTrue(art.getStringAuthors().contains("Sakmann")); - - } catch (Exception e) { - e.printStackTrace(); - fail("Unknown exception " + e.getMessage()); - } + public void test() throws PubmedSearchException { + Configuration.setApplicationCacheOn(false); + Article art = pubmedParser.getPubmedArticleById(9481670); + assertNotNull(art); + assertEquals( + "Adjacent asparagines in the NR2-subunit of the NMDA receptor channel control the voltage-dependent block by extracellular Mg2+.", + art.getTitle()); + assertEquals((Integer) 1998, art.getYear()); + assertEquals("The Journal of physiology", art.getJournal()); + assertTrue(art.getStringAuthors().contains("Wollmuth")); + assertTrue(art.getStringAuthors().contains("Kuner")); + assertTrue(art.getStringAuthors().contains("Sakmann")); } @Test - public void testCache() { - try { - Configuration.setApplicationCacheOn(true); + public void testCache() throws PubmedSearchException { + Configuration.setApplicationCacheOn(true); - Article art = pubmedParser.getPubmedArticleById(9481671); - assertNotNull(art); - - } catch (Exception e) { - e.printStackTrace(); - fail("Unknown exception " + e.getMessage()); - } + Article art = pubmedParser.getPubmedArticleById(9481671); + assertNotNull(art); } @Test - public void testSerialization() { - try { - - Article art = new Article(); - List<String> list = new ArrayList<String>(); - list.add("aaa"); - list.add("bbb"); - art.setTitle("ttt"); - art.setAuthors(list); - art.setJournal("jjjj"); - art.setYear(123); - - String serialString = pubmedParser.getArticleSerializer().objectToString(art); - - assertTrue(serialString.contains("aaa")); - assertTrue(serialString.contains("bbb")); - assertTrue(serialString.contains("ttt")); - assertTrue(serialString.contains("jjjj")); - assertTrue(serialString.contains("123")); - - Article art2 = pubmedParser.getArticleSerializer().xmlToObject(getNodeFromXmlString(serialString)); - - assertEquals(art.getStringAuthors(), art2.getStringAuthors()); - assertEquals(art.getTitle(), art2.getTitle()); - assertEquals(art.getJournal(), art2.getJournal()); - assertEquals(art.getYear(), art2.getYear()); - - } catch (Exception e) { - e.printStackTrace(); - fail("Exception occurred"); - } + public void testSerialization() throws InvalidXmlSchemaException, IOException { + Article art = new Article(); + List<String> list = new ArrayList<String>(); + list.add("aaa"); + list.add("bbb"); + art.setTitle("ttt"); + art.setAuthors(list); + art.setJournal("jjjj"); + art.setYear(123); + + String serialString = pubmedParser.getArticleSerializer().objectToString(art); + + assertTrue(serialString.contains("aaa")); + assertTrue(serialString.contains("bbb")); + assertTrue(serialString.contains("ttt")); + assertTrue(serialString.contains("jjjj")); + assertTrue(serialString.contains("123")); + + Article art2 = pubmedParser.getArticleSerializer().xmlToObject(getNodeFromXmlString(serialString)); + + assertEquals(art.getStringAuthors(), art2.getStringAuthors()); + assertEquals(art.getTitle(), art2.getTitle()); + assertEquals(art.getJournal(), art2.getJournal()); + assertEquals(art.getYear(), art2.getYear()); } /** * This case was problematic with old API used to retrieve data from pubmed + * @throws PubmedSearchException */ @Test - public void testProblematicCase() { - try { - - Article art = pubmedParser.getPubmedArticleById(22363258); - assertNotNull(art); - - } catch (Exception e) { - e.printStackTrace(); - fail("Unknown exception " + e.getMessage()); - } + public void testProblematicCase() throws PubmedSearchException { + Article art = pubmedParser.getPubmedArticleById(22363258); + assertNotNull(art); } @Test - public void testCitationCount() { - try { - - Article art = pubmedParser.getPubmedArticleById(18400456); - assertNotNull(art); - assertTrue(art.getCitationCount() >= 53); - - } catch (Exception e) { - e.printStackTrace(); - fail("Unknown exception " + e.getMessage()); - } + public void testCitationCount() throws PubmedSearchException { + Article art = pubmedParser.getPubmedArticleById(18400456); + assertNotNull(art); + assertTrue(art.getCitationCount() >= 53); } @Test public void testGetSummary() throws Exception { - try { - String summary = pubmedParser.getSummary(18400456); - assertNotNull(summary); - assertFalse(summary.isEmpty()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String summary = pubmedParser.getSummary(18400456); + assertNotNull(summary); + assertFalse(summary.isEmpty()); } @Test public void testGetSummary2() throws Exception { - try { - - String summary = pubmedParser.getSummary(23644949); - assertNull(summary); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String summary = pubmedParser.getSummary(23644949); + assertNull(summary); } @Test public void testGetSummary3() throws Exception { - try { - String summary = pubmedParser.getSummary("18400456"); - assertNotNull(summary); - assertFalse(summary.isEmpty()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String summary = pubmedParser.getSummary("18400456"); + assertNotNull(summary); + assertFalse(summary.isEmpty()); } @Test - // wait max 15 second public void testCachableInterface() throws Exception { String query = "pubmed: 2112"; - try { - String newRes = "hello"; - permanentDatabaseLevelCacheInterface.waitToFinishTasks(); - - cache.setCachedQuery(query, pubmedParser.getCacheType(), newRes); - cache.invalidateByQuery(query, pubmedParser.getCacheType()); + String newRes = "hello"; + permanentDatabaseLevelCacheInterface.waitToFinishTasks(); - permanentDatabaseLevelCacheInterface.waitToFinishTasks(); + cache.setCachedQuery(query, pubmedParser.getCacheType(), newRes); + cache.invalidateByQuery(query, pubmedParser.getCacheType()); - String res = cache.getStringByQuery(query, pubmedParser.getCacheType()); + permanentDatabaseLevelCacheInterface.waitToFinishTasks(); - assertNotNull(res); + String res = cache.getStringByQuery(query, pubmedParser.getCacheType()); - assertFalse("Value wasn't refreshed from db", newRes.equals(res)); + assertNotNull(res); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertFalse("Value wasn't refreshed from db", newRes.equals(res)); } - @Test + @Test(expected = InvalidArgumentException.class) public void testRefreshInvalidCacheQuery() throws Exception { - try { - pubmedParser.refreshCacheQuery("invalid_query"); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - assertTrue(e.getMessage().contains("Don't know what to do")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + pubmedParser.refreshCacheQuery("invalid_query"); } - @Test + @Test(expected = SourceNotAvailable.class) public void testRefreshWhenExternalNotAvailable() throws Exception { WebPageDownloader downloader = pubmedParser.getWebPageDownloader(); try { @@ -241,11 +167,6 @@ public class PubmedParserTest extends AnnotationTestFunctions { String query = PubmedParser.PUBMED_PREFIX + PubmedParser.SERVICE_STATUS_PUBMED_ID; pubmedParser.refreshCacheQuery(query); - fail("Exception expected"); - } catch (SourceNotAvailable e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; } finally { pubmedParser.setWebPageDownloader(downloader); pubmedParser.setCache(cache); @@ -253,38 +174,20 @@ public class PubmedParserTest extends AnnotationTestFunctions { } - @Test + @Test(expected = InvalidArgumentException.class) public void testRefreshInvalidCacheQuery2() throws Exception { - try { - pubmedParser.refreshCacheQuery(new Object()); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - assertTrue(e.getMessage().contains("Don't know what to do")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + pubmedParser.refreshCacheQuery(new Object()); } @Test public void testGetHtmlFullLinkForId() throws Exception { - try { - String htmlString = pubmedParser.getHtmlFullLinkForId(1234); - assertTrue(htmlString.contains("Change in the kinetics of sulphacetamide tissue distribution")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String htmlString = pubmedParser.getHtmlFullLinkForId(1234); + assertTrue(htmlString.contains("Change in the kinetics of sulphacetamide tissue distribution")); } @Test public void testStatus() throws Exception { - try { - assertEquals(ExternalServiceStatusType.OK, pubmedParser.getServiceStatus().getStatus()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(ExternalServiceStatusType.OK, pubmedParser.getServiceStatus().getStatus()); } @Test @@ -296,9 +199,6 @@ public class PubmedParserTest extends AnnotationTestFunctions { .thenThrow(new IOException()); pubmedParser.setWebPageDownloader(mockDownloader); assertEquals(ExternalServiceStatusType.DOWN, pubmedParser.getServiceStatus().getStatus()); - } catch (Exception e) { - e.printStackTrace(); - throw e; } finally { pubmedParser.setWebPageDownloader(downloader); } @@ -313,9 +213,6 @@ public class PubmedParserTest extends AnnotationTestFunctions { .thenReturn("<responseWrapper><version>" + PubmedParser.SUPPORTED_VERSION + "</version></responseWrapper>"); pubmedParser.setWebPageDownloader(mockDownloader); assertEquals(ExternalServiceStatusType.DOWN, pubmedParser.getServiceStatus().getStatus()); - } catch (Exception e) { - e.printStackTrace(); - throw e; } finally { pubmedParser.setWebPageDownloader(downloader); } @@ -330,9 +227,6 @@ public class PubmedParserTest extends AnnotationTestFunctions { "<responseWrapper><version>" + PubmedParser.SUPPORTED_VERSION + "blabla</version></responseWrapper>"); pubmedParser.setWebPageDownloader(mockDownloader); assertEquals(ExternalServiceStatusType.CHANGED, pubmedParser.getServiceStatus().getStatus()); - } catch (Exception e) { - e.printStackTrace(); - throw e; } finally { pubmedParser.setWebPageDownloader(downloader); } @@ -340,15 +234,10 @@ public class PubmedParserTest extends AnnotationTestFunctions { @Test public void testGetApiVersion() throws Exception { - try { - assertNotNull(pubmedParser.getApiVersion()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertNotNull(pubmedParser.getApiVersion()); } - @Test + @Test(expected = PubmedSearchException.class) public void testGetApiVersionWhenProblemWithExternalDb() throws Exception { WebPageDownloader downloader = pubmedParser.getWebPageDownloader(); pubmedParser.setCache(null); @@ -358,11 +247,6 @@ public class PubmedParserTest extends AnnotationTestFunctions { .thenReturn("unknown response"); pubmedParser.setWebPageDownloader(mockDownloader); pubmedParser.getApiVersion(); - fail("Exception expected"); - } catch (PubmedSearchException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; } finally { pubmedParser.setCache(cache); pubmedParser.setWebPageDownloader(downloader); @@ -378,16 +262,13 @@ public class PubmedParserTest extends AnnotationTestFunctions { when(mockDownloader.getFromNetwork(anyString(), anyString(), nullable(String.class))).thenReturn("<xml/>"); pubmedParser.setWebPageDownloader(mockDownloader); assertNull(pubmedParser.getApiVersion()); - } catch (Exception e) { - e.printStackTrace(); - throw e; } finally { pubmedParser.setCache(cache); pubmedParser.setWebPageDownloader(downloader); } } - @Test + @Test(expected = PubmedSearchException.class) public void testGetApiVersionWhenProblemWithExternalDb2() throws Exception { WebPageDownloader downloader = pubmedParser.getWebPageDownloader(); pubmedParser.setCache(null); @@ -397,11 +278,6 @@ public class PubmedParserTest extends AnnotationTestFunctions { .thenThrow(new IOException()); pubmedParser.setWebPageDownloader(mockDownloader); pubmedParser.getApiVersion(); - fail("Exception expected"); - } catch (PubmedSearchException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; } finally { pubmedParser.setCache(cache); pubmedParser.setWebPageDownloader(downloader); @@ -410,23 +286,17 @@ public class PubmedParserTest extends AnnotationTestFunctions { @Test public void testGetters() throws Exception { - try { - MiriamConnector mc = new MiriamConnector(); - XmlSerializer<Article> serializer = new XmlSerializer<>(Article.class); + MiriamConnector mc = new MiriamConnector(); + XmlSerializer<Article> serializer = new XmlSerializer<>(Article.class); - PubmedParser parser = new PubmedParser(null); + PubmedParser parser = new PubmedParser(null); - parser.setMiriamConnector(mc); - assertEquals(mc, parser.getMiriamConnector()); + parser.setMiriamConnector(mc); + assertEquals(mc, parser.getMiriamConnector()); - parser.setArticleSerializer(serializer); + parser.setArticleSerializer(serializer); - assertEquals(serializer, parser.getArticleSerializer()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(serializer, parser.getArticleSerializer()); } } diff --git a/annotation/src/test/java/lcsb/mapviewer/annotation/services/TaxonomyBackendTest.java b/annotation/src/test/java/lcsb/mapviewer/annotation/services/TaxonomyBackendTest.java index 1f14b9a0be2b2ae8b003cc3d0c3db202819998ee..6c90220d69ccb1d5bb3a4b6a7d0405950ecb19a3 100644 --- a/annotation/src/test/java/lcsb/mapviewer/annotation/services/TaxonomyBackendTest.java +++ b/annotation/src/test/java/lcsb/mapviewer/annotation/services/TaxonomyBackendTest.java @@ -1,25 +1,19 @@ package lcsb.mapviewer.annotation.services; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; -import static org.mockito.ArgumentMatchers.nullable; -import static org.mockito.Matchers.anyString; -import static org.mockito.Mockito.when; +import static org.junit.Assert.*; +import static org.mockito.ArgumentMatchers.*; +import static org.mockito.Mockito.*; import java.io.IOException; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.junit.Test; import org.mockito.Mockito; import org.springframework.beans.factory.annotation.Autowired; import lcsb.mapviewer.annotation.AnnotationTestFunctions; -import lcsb.mapviewer.annotation.cache.GeneralCacheInterface; -import lcsb.mapviewer.annotation.cache.SourceNotAvailable; -import lcsb.mapviewer.annotation.cache.WebPageDownloader; +import lcsb.mapviewer.annotation.cache.*; import lcsb.mapviewer.common.exception.InvalidArgumentException; import lcsb.mapviewer.model.map.MiriamData; import lcsb.mapviewer.model.map.MiriamType; @@ -34,85 +28,49 @@ public class TaxonomyBackendTest extends AnnotationTestFunctions { @Test public void testByName() throws Exception { - try { - MiriamData md = taxonomyBackend.getByName("Human"); - assertTrue(md.equals(TaxonomyBackend.HUMAN_TAXONOMY)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + MiriamData md = taxonomyBackend.getByName("Human"); + assertTrue(md.equals(TaxonomyBackend.HUMAN_TAXONOMY)); } @Test public void testByHumansName() throws Exception { - try { - MiriamData md = taxonomyBackend.getByName("Humans"); - assertTrue(md.equals(TaxonomyBackend.HUMAN_TAXONOMY)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + MiriamData md = taxonomyBackend.getByName("Humans"); + assertTrue(md.equals(TaxonomyBackend.HUMAN_TAXONOMY)); } @Test public void testByComplexName() throws Exception { - try { - assertNotNull(taxonomyBackend.getByName("Aplysia californica (Sea Hare)")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertNotNull(taxonomyBackend.getByName("Aplysia californica (Sea Hare)")); } @Test public void testByCommonName() throws Exception { - try { - assertNotNull(taxonomyBackend.getByName("Rat")); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertNotNull(taxonomyBackend.getByName("Rat")); } @Test public void testByEmptyName() throws Exception { - try { - assertNull(taxonomyBackend.getByName(null)); - assertNull(taxonomyBackend.getByName("")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertNull(taxonomyBackend.getByName(null)); + assertNull(taxonomyBackend.getByName("")); } @Test public void testByAbreviationName() throws Exception { - try { - assertNotNull(taxonomyBackend.getByName("C. elegans")); - assertNotNull(taxonomyBackend.getByName("D. sechellia")); - assertNotNull(taxonomyBackend.getByName("P. pacificus")); - assertNotNull(taxonomyBackend.getByName("T. castaneum")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertNotNull(taxonomyBackend.getByName("C. elegans")); + assertNotNull(taxonomyBackend.getByName("D. sechellia")); + assertNotNull(taxonomyBackend.getByName("P. pacificus")); + assertNotNull(taxonomyBackend.getByName("T. castaneum")); } @Test public void testGetName() throws Exception { - try { - String name = taxonomyBackend.getNameForTaxonomy(new MiriamData(MiriamType.TAXONOMY, "9606")); - logger.debug(name); - assertTrue("Taxonomy id should refer to homo sapien, but this found: " + name, name.contains("Homo sapien")); - assertNotNull(taxonomyBackend.getNameForTaxonomy(new MiriamData(MiriamType.TAXONOMY, "9605"))); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String name = taxonomyBackend.getNameForTaxonomy(new MiriamData(MiriamType.TAXONOMY, "9606")); + logger.debug(name); + assertTrue("Taxonomy id should refer to homo sapien, but this found: " + name, name.contains("Homo sapien")); + assertNotNull(taxonomyBackend.getNameForTaxonomy(new MiriamData(MiriamType.TAXONOMY, "9605"))); } - @Test + @Test(expected = TaxonomySearchException.class) public void testGetNameWhenProblemWithDb() throws Exception { WebPageDownloader downloader = taxonomyBackend.getWebPageDownloader(); try { @@ -122,11 +80,6 @@ public class TaxonomyBackendTest extends AnnotationTestFunctions { taxonomyBackend.setWebPageDownloader(mockDownloader); taxonomyBackend.setCache(null); taxonomyBackend.getNameForTaxonomy(new MiriamData(MiriamType.TAXONOMY, "9606")); - fail("Exception expected"); - } catch (TaxonomySearchException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; } finally { taxonomyBackend.setCache(cache); taxonomyBackend.setWebPageDownloader(downloader); @@ -135,129 +88,70 @@ public class TaxonomyBackendTest extends AnnotationTestFunctions { @Test public void testGetNameForInvalidTax() throws Exception { - try { - String name = taxonomyBackend.getNameForTaxonomy(new MiriamData(MiriamType.TAXONOMY, "-a-")); - assertNull(name); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String name = taxonomyBackend.getNameForTaxonomy(new MiriamData(MiriamType.TAXONOMY, "-a-")); + assertNull(name); } @Test public void testGetNameForInvalidInputData() throws Exception { - try { - String name = taxonomyBackend.getNameForTaxonomy(null); - assertNull(name); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String name = taxonomyBackend.getNameForTaxonomy(null); + assertNull(name); } @Test public void testByName2() throws Exception { - try { - MiriamData md = taxonomyBackend.getByName("homo sapiens"); - assertTrue(md.equals(TaxonomyBackend.HUMAN_TAXONOMY)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + MiriamData md = taxonomyBackend.getByName("homo sapiens"); + assertTrue(md.equals(TaxonomyBackend.HUMAN_TAXONOMY)); } @Test public void testByName3() throws Exception { - try { - MiriamData md = taxonomyBackend.getByName("bla bla kiwi"); - assertNull(md); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + MiriamData md = taxonomyBackend.getByName("bla bla kiwi"); + assertNull(md); } @Test public void testByMusMusculusName() throws Exception { - try { - MiriamData md = taxonomyBackend.getByName("Mus musculus"); - assertTrue(md.equals(new MiriamData(MiriamType.TAXONOMY, "10090"))); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + MiriamData md = taxonomyBackend.getByName("Mus musculus"); + assertTrue(md.equals(new MiriamData(MiriamType.TAXONOMY, "10090"))); } @Test public void testByMouseName() throws Exception { - try { - MiriamData md = taxonomyBackend.getByName("Mouse"); - assertTrue(md.equals(new MiriamData(MiriamType.TAXONOMY, "10090"))); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + MiriamData md = taxonomyBackend.getByName("Mouse"); + assertTrue(md.equals(new MiriamData(MiriamType.TAXONOMY, "10090"))); } @Test public void testRefreshCacheQuery() throws Exception { - try { - String result = taxonomyBackend.refreshCacheQuery(TaxonomyBackend.TAXONOMY_CACHE_PREFIX + "homo sapiens"); - assertNotNull(result); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String result = taxonomyBackend.refreshCacheQuery(TaxonomyBackend.TAXONOMY_CACHE_PREFIX + "homo sapiens"); + assertNotNull(result); } @Test public void testRefreshCacheQuery2() throws Exception { - try { - String result = taxonomyBackend - .refreshCacheQuery(TaxonomyBackend.TAXONOMY_NAME_CACHE_PREFIX + TaxonomyBackend.HUMAN_TAXONOMY.getResource()); - assertNotNull(result); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String result = taxonomyBackend + .refreshCacheQuery(TaxonomyBackend.TAXONOMY_NAME_CACHE_PREFIX + TaxonomyBackend.HUMAN_TAXONOMY.getResource()); + assertNotNull(result); } @Test public void testRefreshCacheQuery3() throws Exception { - try { - String result = taxonomyBackend.refreshCacheQuery("http://google.pl/"); - assertNotNull(result); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String result = taxonomyBackend.refreshCacheQuery("http://google.pl/"); + assertNotNull(result); } - @Test + @Test(expected = InvalidArgumentException.class) public void testRefreshInvalidCacheQuery() throws Exception { - try { - taxonomyBackend.refreshCacheQuery("unk_query"); - } catch (InvalidArgumentException e) { - assertTrue(e.getMessage().contains("Don't know what to")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + taxonomyBackend.refreshCacheQuery("unk_query"); } - @Test + @Test(expected = InvalidArgumentException.class) public void testRefreshInvalidCacheQuery2() throws Exception { - try { - taxonomyBackend.refreshCacheQuery(new Object()); - } catch (InvalidArgumentException e) { - assertTrue(e.getMessage().contains("Don't know what to")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + taxonomyBackend.refreshCacheQuery(new Object()); } - @Test + @Test(expected = SourceNotAvailable.class) public void testRefreshCacheQueryNotAvailable() throws Exception { WebPageDownloader downloader = taxonomyBackend.getWebPageDownloader(); try { @@ -268,11 +162,6 @@ public class TaxonomyBackendTest extends AnnotationTestFunctions { taxonomyBackend.setCache(null); taxonomyBackend.refreshCacheQuery("http://google.pl/"); - fail("Exception expected"); - } catch (SourceNotAvailable e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; } finally { taxonomyBackend.setWebPageDownloader(downloader); taxonomyBackend.setCache(cache); @@ -281,12 +170,7 @@ public class TaxonomyBackendTest extends AnnotationTestFunctions { @Test public void testStatus() throws Exception { - try { - assertEquals(ExternalServiceStatusType.OK, taxonomyBackend.getServiceStatus().getStatus()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(ExternalServiceStatusType.OK, taxonomyBackend.getServiceStatus().getStatus()); } @Test @@ -298,9 +182,6 @@ public class TaxonomyBackendTest extends AnnotationTestFunctions { .thenThrow(new IOException()); taxonomyBackend.setWebPageDownloader(mockDownloader); assertEquals(ExternalServiceStatusType.DOWN, taxonomyBackend.getServiceStatus().getStatus()); - } catch (Exception e) { - e.printStackTrace(); - throw e; } finally { taxonomyBackend.setWebPageDownloader(downloader); } @@ -314,9 +195,6 @@ public class TaxonomyBackendTest extends AnnotationTestFunctions { when(mockDownloader.getFromNetwork(anyString(), anyString(), nullable(String.class))).thenReturn(""); taxonomyBackend.setWebPageDownloader(mockDownloader); assertEquals(ExternalServiceStatusType.CHANGED, taxonomyBackend.getServiceStatus().getStatus()); - } catch (Exception e) { - e.printStackTrace(); - throw e; } finally { taxonomyBackend.setWebPageDownloader(downloader); } @@ -331,9 +209,6 @@ public class TaxonomyBackendTest extends AnnotationTestFunctions { .thenReturn("<em>Taxonomy ID: </em>1234"); taxonomyBackend.setWebPageDownloader(mockDownloader); assertEquals(ExternalServiceStatusType.CHANGED, taxonomyBackend.getServiceStatus().getStatus()); - } catch (Exception e) { - e.printStackTrace(); - throw e; } finally { taxonomyBackend.setWebPageDownloader(downloader); } diff --git a/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/BrendaAnnotatorTest.java b/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/BrendaAnnotatorTest.java index a2c16aa7eea33522a104a6a392b89f34859c8cec..153d02adcc0cdea6a58734774bdb7445afe7d319 100644 --- a/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/BrendaAnnotatorTest.java +++ b/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/BrendaAnnotatorTest.java @@ -42,115 +42,82 @@ public class BrendaAnnotatorTest extends AnnotationTestFunctions { @Test public void testAnnotateFromUniprot() throws Exception { - try { - - Species protein = new GenericProtein("id"); - protein.addMiriamData(new MiriamData(MiriamType.UNIPROT, "P12345")); + Species protein = new GenericProtein("id"); + protein.addMiriamData(new MiriamData(MiriamType.UNIPROT, "P12345")); - brendaAnnotator.annotateElement(protein); + brendaAnnotator.annotateElement(protein); - int cntMds = 0; + int cntMds = 0; - for (MiriamData md : protein.getMiriamData()) { - if (md.getDataType().equals(MiriamType.BRENDA)) { - cntMds++; - assertTrue("Invalid BRENDA annotation extracted from BRENDA annotator", - md.getResource().equals("2.6.1.1") || md.getResource().equals("2.6.1.7")); - } + for (MiriamData md : protein.getMiriamData()) { + if (md.getDataType().equals(MiriamType.BRENDA)) { + cntMds++; + assertTrue("Invalid BRENDA annotation extracted from BRENDA annotator", + md.getResource().equals("2.6.1.1") || md.getResource().equals("2.6.1.7")); } - - assertTrue("Incorrect BRENDA annotations extracted from BRENDA annotator", cntMds == 2); - - } catch (Exception e) { - e.printStackTrace(); - throw e; } + + assertTrue("Incorrect BRENDA annotations extracted from BRENDA annotator", cntMds == 2); } @Test @Ignore("TAIR DB restricts queries by IP") public void testAnnotateFromTair() throws Exception { - try { + Species protein = new GenericProtein("id"); + protein.setName("bla"); + protein.addMiriamData(new MiriamData(MiriamType.TAIR_LOCUS, "AT5G48930")); - Species protein = new GenericProtein("id"); - protein.setName("bla"); - protein.addMiriamData(new MiriamData(MiriamType.TAIR_LOCUS, "AT5G48930")); - - // this is slow because accessing - // https://arabidopsis.org/servlets/TairObject?type=locus&name=AT5G48930 - // is very slow - brendaAnnotator.annotateElement(protein); + // this is slow because accessing + // https://arabidopsis.org/servlets/TairObject?type=locus&name=AT5G48930 + // is very slow + brendaAnnotator.annotateElement(protein); - MiriamData mdBrenda = null; + MiriamData mdBrenda = null; - for (MiriamData md : protein.getMiriamData()) { - if (md.getDataType().equals(MiriamType.BRENDA)) { - mdBrenda = md; // there should be only one EC number for that TAIR<->UNIPROT record - } + for (MiriamData md : protein.getMiriamData()) { + if (md.getDataType().equals(MiriamType.BRENDA)) { + mdBrenda = md; // there should be only one EC number for that TAIR<->UNIPROT record } - - assertTrue("No BRENDA annotation extracted from BRENDA annotator", mdBrenda != null); - assertTrue("Invalid BRENDA annotation extracted from BRENDA annotator based on TAIR", - mdBrenda.getResource().equals("2.3.1.133")); - - } catch (Exception e) { - e.printStackTrace(); - throw e; } + + assertTrue("No BRENDA annotation extracted from BRENDA annotator", mdBrenda != null); + assertTrue("Invalid BRENDA annotation extracted from BRENDA annotator based on TAIR", + mdBrenda.getResource().equals("2.3.1.133")); } @Test public void testAnnotateMultipleUniprots() throws Exception { - try { - - Species protein = new GenericProtein("id"); - protein.setName("bla"); - protein.addMiriamData(new MiriamData(MiriamType.UNIPROT, "Q9SG95")); - protein.addMiriamData(new MiriamData(MiriamType.UNIPROT, "Q12540")); - - brendaAnnotator.annotateElement(protein); + Species protein = new GenericProtein("id"); + protein.setName("bla"); + protein.addMiriamData(new MiriamData(MiriamType.UNIPROT, "Q9SG95")); + protein.addMiriamData(new MiriamData(MiriamType.UNIPROT, "Q12540")); - assertTrue("Wrong number of BRENDA identifiers extracted from BRENDA annotator", - protein.getMiriamData().size() == 4); + brendaAnnotator.annotateElement(protein); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertTrue("Wrong number of BRENDA identifiers extracted from BRENDA annotator", + protein.getMiriamData().size() == 4); } @Test public void testAnnotateMultipleUniprotsWithIdenticalEC() throws Exception { - try { + Species protein = new GenericProtein("id"); + protein.setName("bla"); + protein.addMiriamData(new MiriamData(MiriamType.UNIPROT, "Q9SG95")); + protein.addMiriamData(new MiriamData(MiriamType.UNIPROT, "Q8L5J1")); - Species protein = new GenericProtein("id"); - protein.setName("bla"); - protein.addMiriamData(new MiriamData(MiriamType.UNIPROT, "Q9SG95")); - protein.addMiriamData(new MiriamData(MiriamType.UNIPROT, "Q8L5J1")); - - brendaAnnotator.annotateElement(protein); + brendaAnnotator.annotateElement(protein); - assertTrue("Wrong number of BRENDA identifiers extracted from BRENDA annotator", - protein.getMiriamData().size() == 3); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertTrue("Wrong number of BRENDA identifiers extracted from BRENDA annotator", + protein.getMiriamData().size() == 3); } @Test public void testAnnotateInvalidEmpty() throws Exception { - try { - Species protein = new GenericProtein("id"); - protein.setName("bla"); - brendaAnnotator.annotateElement(protein); + Species protein = new GenericProtein("id"); + protein.setName("bla"); + brendaAnnotator.annotateElement(protein); - assertEquals(0, protein.getMiriamData().size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, protein.getMiriamData().size()); } @Test @@ -170,10 +137,6 @@ public class BrendaAnnotatorTest extends AnnotationTestFunctions { assertEquals(1, protein.getMiriamData().size()); assertEquals(1, getWarnings().size()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; } finally { uniprotAnnotator.setWebPageDownloader(downloader); } @@ -181,54 +144,15 @@ public class BrendaAnnotatorTest extends AnnotationTestFunctions { @Test public void testAnnotateInvalidTair() throws Exception { - try { - Species protein = new GenericProtein("id"); - protein.addMiriamData(new MiriamData(MiriamType.TAIR_LOCUS, "bla")); - brendaAnnotator.annotateElement(protein); - - assertEquals(1, protein.getMiriamData().size()); + Species protein = new GenericProtein("id"); + protein.addMiriamData(new MiriamData(MiriamType.TAIR_LOCUS, "bla")); + brendaAnnotator.annotateElement(protein); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(1, protein.getMiriamData().size()); } @Test public void testStatus() throws Exception { - try { - assertEquals(ExternalServiceStatusType.OK, brendaAnnotator.getServiceStatus().getStatus()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(ExternalServiceStatusType.OK, brendaAnnotator.getServiceStatus().getStatus()); } - - /* - * Relying on uniprot and tair annotators which have their own tests - * - * @Test public void testSimulateDownStatus() throws Exception { - * WebPageDownloader downloader = brendaAnnotator.getWebPageDownloader(); try { - * WebPageDownloader mockDownloader = Mockito.mock(WebPageDownloader.class); - * when(mockDownloader.getFromNetwork(anyString(), anyString(), - * anyString())).thenThrow(new IOException()); - * brendaAnnotator.setWebPageDownloader(mockDownloader); - * assertEquals(ExternalServiceStatusType.DOWN, - * brendaAnnotator.getServiceStatus().getStatus()); } catch (Exception e) { - * e.printStackTrace(); throw e; } finally { - * brendaAnnotator.setWebPageDownloader(downloader); } } - * - * - * @Test public void testSimulateChangedStatus() throws Exception { - * WebPageDownloader downloader = brendaAnnotator.getWebPageDownloader(); try { - * WebPageDownloader mockDownloader = Mockito.mock(WebPageDownloader.class); - * when(mockDownloader.getFromNetwork(anyString(), anyString(), - * anyString())).thenReturn("GN Name=ACSS2; Synonyms=ACAS2;"); - * brendaAnnotator.setWebPageDownloader(mockDownloader); - * assertEquals(ExternalServiceStatusType.CHANGED, - * brendaAnnotator.getServiceStatus().getStatus()); } catch (Exception e) { - * e.printStackTrace(); throw e; } finally { - * brendaAnnotator.setWebPageDownloader(downloader); } } - */ - } diff --git a/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/CazyAnnotatorTest.java b/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/CazyAnnotatorTest.java index 2926eea5ed2bca152ac99042baa3688f238a179f..feea977aa6cff035ec22092c72cceacbb88b991d 100644 --- a/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/CazyAnnotatorTest.java +++ b/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/CazyAnnotatorTest.java @@ -1,19 +1,12 @@ package lcsb.mapviewer.annotation.services.annotators; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.ArgumentMatchers.nullable; -import static org.mockito.Mockito.when; +import static org.junit.Assert.*; +import static org.mockito.ArgumentMatchers.*; +import static org.mockito.Mockito.*; import java.io.IOException; -import org.junit.After; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; +import org.junit.*; import org.mockito.Mockito; import org.springframework.beans.factory.annotation.Autowired; @@ -41,174 +34,114 @@ public class CazyAnnotatorTest extends AnnotationTestFunctions { @Test public void testUniprotToCazy() throws Exception { - try { - assertEquals(new MiriamData(MiriamType.CAZY, "GH5_7"), - cazyAnnotator.uniprotToCazy(new MiriamData(MiriamType.UNIPROT, "Q9SG95"))); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(new MiriamData(MiriamType.CAZY, "GH5_7"), + cazyAnnotator.uniprotToCazy(new MiriamData(MiriamType.UNIPROT, "Q9SG95"))); } @Test public void testAnnotateFromUniprot() throws Exception { - try { - - Species protein = new GenericProtein("id"); - protein.setName("bla"); - protein.addMiriamData(new MiriamData(MiriamType.UNIPROT, "Q9SG95")); + Species protein = new GenericProtein("id"); + protein.setName("bla"); + protein.addMiriamData(new MiriamData(MiriamType.UNIPROT, "Q9SG95")); - cazyAnnotator.annotateElement(protein); + cazyAnnotator.annotateElement(protein); - MiriamData mdCazy = null; + MiriamData mdCazy = null; - for (MiriamData md : protein.getMiriamData()) { - if (md.getDataType().equals(MiriamType.CAZY)) { - mdCazy = md; - } + for (MiriamData md : protein.getMiriamData()) { + if (md.getDataType().equals(MiriamType.CAZY)) { + mdCazy = md; } - - assertTrue("No UNIPROT annotation extracted from TAIR annotator", mdCazy != null); - assertTrue("Invalid UNIPROT annotation extracted from TAIR annotator", - mdCazy.getResource().equalsIgnoreCase("GH5_7")); - - } catch (Exception e) { - e.printStackTrace(); - throw e; } + + assertTrue("No UNIPROT annotation extracted from TAIR annotator", mdCazy != null); + assertTrue("Invalid UNIPROT annotation extracted from TAIR annotator", + mdCazy.getResource().equalsIgnoreCase("GH5_7")); } @Test @Ignore("TAIR DB restricts queries by IP") public void testAnnotateFromTair() throws Exception { - try { + Species protein = new GenericProtein("id"); + protein.setName("bla"); + protein.addMiriamData(new MiriamData(MiriamType.TAIR_LOCUS, "AT3G53010")); - Species protein = new GenericProtein("id"); - protein.setName("bla"); - protein.addMiriamData(new MiriamData(MiriamType.TAIR_LOCUS, "AT3G53010")); + cazyAnnotator.annotateElement(protein); - cazyAnnotator.annotateElement(protein); + MiriamData mdCazy = null; - MiriamData mdCazy = null; - - for (MiriamData md : protein.getMiriamData()) { - if (md.getDataType().equals(MiriamType.CAZY)) { - mdCazy = md; - } + for (MiriamData md : protein.getMiriamData()) { + if (md.getDataType().equals(MiriamType.CAZY)) { + mdCazy = md; } - - assertTrue("No CAZy annotation extracted from CAZy annotator", mdCazy != null); - assertTrue("Invalid CAZy annotation extracted from CAZy annotator", mdCazy.getResource().equalsIgnoreCase("CE6")); - - } catch (Exception e) { - e.printStackTrace(); - throw e; } + assertTrue("No CAZy annotation extracted from CAZy annotator", mdCazy != null); + assertTrue("Invalid CAZy annotation extracted from CAZy annotator", mdCazy.getResource().equalsIgnoreCase("CE6")); } @Test public void testAnnotateMultipleUniprots() throws Exception { - try { + Species protein = new GenericProtein("id"); + protein.setName("bla"); + protein.addMiriamData(new MiriamData(MiriamType.UNIPROT, "Q9SG95")); + protein.addMiriamData(new MiriamData(MiriamType.UNIPROT, "Q12540")); - Species protein = new GenericProtein("id"); - protein.setName("bla"); - protein.addMiriamData(new MiriamData(MiriamType.UNIPROT, "Q9SG95")); - protein.addMiriamData(new MiriamData(MiriamType.UNIPROT, "Q12540")); + cazyAnnotator.annotateElement(protein); - cazyAnnotator.annotateElement(protein); + int cntMDs = 0; - int cntMDs = 0; - - for (MiriamData md : protein.getMiriamData()) { - if (md.getDataType().equals(MiriamType.CAZY)) { - cntMDs++; - } + for (MiriamData md : protein.getMiriamData()) { + if (md.getDataType().equals(MiriamType.CAZY)) { + cntMDs++; } - - assertTrue("Wrong number of CAZy identifiers extracted from CAZy annotator", cntMDs == 2); - - } catch (Exception e) { - e.printStackTrace(); - throw e; } + + assertTrue("Wrong number of CAZy identifiers extracted from CAZy annotator", cntMDs == 2); } @Test public void testAnnotateInvalidEmpty() throws Exception { - try { - Species protein = new GenericProtein("id"); - protein.setName("bla"); - cazyAnnotator.annotateElement(protein); - - assertEquals(0, protein.getMiriamData().size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Species protein = new GenericProtein("id"); + protein.setName("bla"); + cazyAnnotator.annotateElement(protein); + + assertEquals(0, protein.getMiriamData().size()); } @Test public void testAnnotateInvalidUniprot() throws Exception { - try { - Species protein = new GenericProtein("id"); - protein.addMiriamData(new MiriamData(MiriamType.UNIPROT, "bla")); - cazyAnnotator.annotateElement(protein); + Species protein = new GenericProtein("id"); + protein.addMiriamData(new MiriamData(MiriamType.UNIPROT, "bla")); + cazyAnnotator.annotateElement(protein); - assertEquals(1, protein.getMiriamData().size()); + assertEquals(1, protein.getMiriamData().size()); - assertEquals(1, getWarnings().size()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(1, getWarnings().size()); } @Test public void testAnnotateInvalidTair() throws Exception { - try { - Species protein = new GenericProtein("id"); - protein.addMiriamData(new MiriamData(MiriamType.TAIR_LOCUS, "bla")); - cazyAnnotator.annotateElement(protein); - - assertEquals(1, protein.getMiriamData().size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Species protein = new GenericProtein("id"); + protein.addMiriamData(new MiriamData(MiriamType.TAIR_LOCUS, "bla")); + cazyAnnotator.annotateElement(protein); + + assertEquals(1, protein.getMiriamData().size()); } @Test public void testInvalidUniprotToCazyNull() throws Exception { - try { - assertNull(cazyAnnotator.uniprotToCazy(null)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertNull(cazyAnnotator.uniprotToCazy(null)); } - @Test + @Test(expected = InvalidArgumentException.class) public void testInvalidUniprotToCazyWrongMd() throws Exception { - try { - cazyAnnotator.uniprotToCazy(new MiriamData(MiriamType.WIKIPEDIA, "bla")); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + cazyAnnotator.uniprotToCazy(new MiriamData(MiriamType.WIKIPEDIA, "bla")); } @Test public void testStatus() throws Exception { - try { - assertEquals(ExternalServiceStatusType.OK, cazyAnnotator.getServiceStatus().getStatus()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(ExternalServiceStatusType.OK, cazyAnnotator.getServiceStatus().getStatus()); } @Test @@ -220,9 +153,6 @@ public class CazyAnnotatorTest extends AnnotationTestFunctions { .thenThrow(new IOException()); cazyAnnotator.setWebPageDownloader(mockDownloader); assertEquals(ExternalServiceStatusType.DOWN, cazyAnnotator.getServiceStatus().getStatus()); - } catch (Exception e) { - e.printStackTrace(); - throw e; } finally { cazyAnnotator.setWebPageDownloader(downloader); } @@ -237,9 +167,6 @@ public class CazyAnnotatorTest extends AnnotationTestFunctions { .thenReturn("GN Name=ACSS2; Synonyms=ACAS2;"); cazyAnnotator.setWebPageDownloader(mockDownloader); assertEquals(ExternalServiceStatusType.CHANGED, cazyAnnotator.getServiceStatus().getStatus()); - } catch (Exception e) { - e.printStackTrace(); - throw e; } finally { cazyAnnotator.setWebPageDownloader(downloader); } diff --git a/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/ChebiAnnotatorTest.java b/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/ChebiAnnotatorTest.java index 831d19ba7fa346797cb0a047525dbe2ed7921810..4af51cf203f7b340e211c8cccf8b7c1f72663fb2 100644 --- a/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/ChebiAnnotatorTest.java +++ b/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/ChebiAnnotatorTest.java @@ -1,44 +1,26 @@ package lcsb.mapviewer.annotation.services.annotators; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.ArgumentMatchers.nullable; -import static org.mockito.Mockito.when; +import static org.junit.Assert.*; +import static org.mockito.ArgumentMatchers.*; +import static org.mockito.Mockito.*; import java.util.List; -import org.apache.logging.log4j.*; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.junit.*; import org.mockito.Mockito; import org.springframework.beans.factory.annotation.Autowired; import lcsb.mapviewer.annotation.AnnotationTestFunctions; -import lcsb.mapviewer.annotation.cache.GeneralCacheInterface; -import lcsb.mapviewer.annotation.cache.PermanentDatabaseLevelCacheInterface; -import lcsb.mapviewer.annotation.cache.SourceNotAvailable; +import lcsb.mapviewer.annotation.cache.*; import lcsb.mapviewer.annotation.data.Chebi; import lcsb.mapviewer.annotation.services.ExternalServiceStatusType; import lcsb.mapviewer.common.exception.InvalidArgumentException; -import lcsb.mapviewer.model.map.MiriamData; -import lcsb.mapviewer.model.map.MiriamRelationType; -import lcsb.mapviewer.model.map.MiriamType; +import lcsb.mapviewer.model.map.*; import lcsb.mapviewer.model.map.species.SimpleMolecule; import uk.ac.ebi.chebi.webapps.chebiWS.client.ChebiWebServiceClient; -import uk.ac.ebi.chebi.webapps.chebiWS.model.ChebiWebServiceFault_Exception; -import uk.ac.ebi.chebi.webapps.chebiWS.model.DataItem; -import uk.ac.ebi.chebi.webapps.chebiWS.model.Entity; -import uk.ac.ebi.chebi.webapps.chebiWS.model.LiteEntity; -import uk.ac.ebi.chebi.webapps.chebiWS.model.LiteEntityList; -import uk.ac.ebi.chebi.webapps.chebiWS.model.OntologyDataItem; -import uk.ac.ebi.chebi.webapps.chebiWS.model.SearchCategory; +import uk.ac.ebi.chebi.webapps.chebiWS.model.*; public class ChebiAnnotatorTest extends AnnotationTestFunctions { static Logger logger = LogManager.getLogger(ChebiAnnotatorTest.class); @@ -62,49 +44,34 @@ public class ChebiAnnotatorTest extends AnnotationTestFunctions { @Test public void testGetIdByName() throws Exception { - try { - MiriamData id = backend.getChebiForChebiName("adenine"); - assertEquals(new MiriamData(MiriamType.CHEBI, "CHEBI:16708"), id); - id = backend.getChebiForChebiName("asdf bvclcx lcxj vxlcvkj"); - assertNull(id); - assertNull(backend.getChebiForChebiName(null)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + MiriamData id = backend.getChebiForChebiName("adenine"); + assertEquals(new MiriamData(MiriamType.CHEBI, "CHEBI:16708"), id); + id = backend.getChebiForChebiName("asdf bvclcx lcxj vxlcvkj"); + assertNull(id); + assertNull(backend.getChebiForChebiName(null)); } @Test public void testNameById() throws Exception { - try { - String name = backend.getChebiNameForChebiId(new MiriamData(MiriamType.CHEBI, "CHEBI:16708")); - assertEquals("adenine", name); - name = backend.getChebiNameForChebiId(new MiriamData(MiriamType.CHEBI, "16708")); - assertEquals("adenine", name); - name = backend.getChebiNameForChebiId(new MiriamData(MiriamType.CHEBI, "CHEBI:16708a")); - assertNull(name); - name = backend.getChebiNameForChebiId(null); - assertNull(name); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String name = backend.getChebiNameForChebiId(new MiriamData(MiriamType.CHEBI, "CHEBI:16708")); + assertEquals("adenine", name); + name = backend.getChebiNameForChebiId(new MiriamData(MiriamType.CHEBI, "16708")); + assertEquals("adenine", name); + name = backend.getChebiNameForChebiId(new MiriamData(MiriamType.CHEBI, "CHEBI:16708a")); + assertNull(name); + name = backend.getChebiNameForChebiId(null); + assertNull(name); } @Test public void testChebiById() throws Exception { - try { - Chebi chebi = backend.getChebiElementForChebiId(new MiriamData(MiriamType.CHEBI, "CHEBI:16708")); - assertNotNull(chebi); - assertEquals("adenine", chebi.getName()); - assertEquals("Nc1ncnc2[nH]cnc12", chebi.getSmiles()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Chebi chebi = backend.getChebiElementForChebiId(new MiriamData(MiriamType.CHEBI, "CHEBI:16708")); + assertNotNull(chebi); + assertEquals("adenine", chebi.getName()); + assertEquals("Nc1ncnc2[nH]cnc12", chebi.getSmiles()); } - @Test + @Test(expected = ChebiSearchException.class) public void testChebiByIdWhenConnectionFails() throws Exception { try { cache = backend.getCache(); @@ -127,13 +94,6 @@ public class ChebiAnnotatorTest extends AnnotationTestFunctions { backend.setClient(chebiWebServiceClient); backend.getChebiElementForChebiId(new MiriamData(MiriamType.CHEBI, "CHEBI:16708")); - fail("Exception expected"); - - } catch (ChebiSearchException e) { - assertTrue(e.getMessage().contains("Problem with chebi")); - } catch (Exception e) { - e.printStackTrace(); - throw e; } finally { // restore cache for other tests backend.setCache(cache); @@ -142,200 +102,137 @@ public class ChebiAnnotatorTest extends AnnotationTestFunctions { } } - @Test + @Test(expected = InvalidArgumentException.class) public void testChebiByInvalidId() throws Exception { - try { - backend.getChebiElementForChebiId(new MiriamData(MiriamType.WIKIPEDIA, "water")); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + backend.getChebiElementForChebiId(new MiriamData(MiriamType.WIKIPEDIA, "water")); } @Test public void testChebi() throws Exception { - try { - - Chebi chebi = backend.getChebiElementForChebiId(new MiriamData(MiriamType.CHEBI, "CHEBI:16708")); - assertNotNull(chebi); - assertEquals("adenine", chebi.getName()); - assertEquals("Nc1ncnc2[nH]cnc12", chebi.getSmiles()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Chebi chebi = backend.getChebiElementForChebiId(new MiriamData(MiriamType.CHEBI, "CHEBI:16708")); + assertNotNull(chebi); + assertEquals("adenine", chebi.getName()); + assertEquals("Nc1ncnc2[nH]cnc12", chebi.getSmiles()); } @Test public void testChebiOntologyForWater() throws Exception { - try { - - Chebi chebi = backend.getChebiElementForChebiId(new MiriamData(MiriamType.CHEBI, "CHEBI:15377")); - assertNotNull(chebi); - assertTrue(chebi.getIncomingChebi().size() > 0); - assertTrue(chebi.getOutgoingChebi().size() > 0); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Chebi chebi = backend.getChebiElementForChebiId(new MiriamData(MiriamType.CHEBI, "CHEBI:15377")); + assertNotNull(chebi); + assertTrue(chebi.getIncomingChebi().size() > 0); + assertTrue(chebi.getOutgoingChebi().size() > 0); } @Test(timeout = 15000) public void testCachableInterfaceById() throws Exception { String query = "id: CHEBI:28423"; String newRes = "hello"; - try { - cache.setCachedQuery(query, backend.getCacheType(), newRes); - cache.invalidateByQuery(query, backend.getCacheType()); + cache.setCachedQuery(query, backend.getCacheType(), newRes); + cache.invalidateByQuery(query, backend.getCacheType()); - permanentDatabaseLevelCache.waitToFinishTasks(); + permanentDatabaseLevelCache.waitToFinishTasks(); - String res = cache.getStringByQuery(query, backend.getCacheType()); + String res = cache.getStringByQuery(query, backend.getCacheType()); - assertNotNull(res); + assertNotNull(res); - assertFalse("Value wasn't refreshed from db", newRes.equals(res)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertFalse("Value wasn't refreshed from db", newRes.equals(res)); } @Test(timeout = 15000) public void testCachableInterfaceByName() throws Exception { String query = "name: water"; String newRes = "hello"; - try { - cache.setCachedQuery(query, backend.getCacheType(), newRes); - cache.invalidateByQuery(query, backend.getCacheType()); + cache.setCachedQuery(query, backend.getCacheType(), newRes); + cache.invalidateByQuery(query, backend.getCacheType()); - permanentDatabaseLevelCache.waitToFinishTasks(); + permanentDatabaseLevelCache.waitToFinishTasks(); - String res = cache.getStringByQuery(query, backend.getCacheType()); + String res = cache.getStringByQuery(query, backend.getCacheType()); - assertNotNull(res); + assertNotNull(res); - assertFalse("Value wasn't refreshed from db", newRes.equals(res)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertFalse("Value wasn't refreshed from db", newRes.equals(res)); } @Test public void testChebiNameToId1() throws Exception { - try { - // easy tests with some molecule - MiriamData result = backend.getChebiForChebiName("L-glutamate(2-)"); - assertNotNull(result); - assertTrue(result.getResource().contains("CHEBI:29988")); - // unknown molecule - MiriamData string = backend.getChebiForChebiName("blablasblasblsabsal"); - assertNull(string); + // easy tests with some molecule + MiriamData result = backend.getChebiForChebiName("L-glutamate(2-)"); + assertNotNull(result); + assertTrue(result.getResource().contains("CHEBI:29988")); + // unknown molecule + MiriamData string = backend.getChebiForChebiName("blablasblasblsabsal"); + assertNull(string); - // and water - result = backend.getChebiForChebiName("H2O"); - assertNotNull(result); - assertTrue(result.getResource().contains("CHEBI:15377")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + // and water + result = backend.getChebiForChebiName("H2O"); + assertNotNull(result); + assertTrue(result.getResource().contains("CHEBI:15377")); } @Test public void testChebiNameToId4() throws Exception { - try { - // easy tests with some molecule - MiriamData result = backend.getChebiForChebiName("Ca2+"); - assertEquals(new MiriamData(MiriamType.CHEBI, "CHEBI:29108"), result); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + // easy tests with some molecule + MiriamData result = backend.getChebiForChebiName("Ca2+"); + assertEquals(new MiriamData(MiriamType.CHEBI, "CHEBI:29108"), result); } @Test public void testChebiOntologyIds() throws Exception { - try { - // unknown molecule - List<MiriamData> res = backend.getOntologyChebiIdsForChebiName("blablasblasblsabsal"); - assertNotNull(res); - assertEquals(0, res.size()); - - // and water - res = backend.getOntologyChebiIdsForChebiName("h2o"); - assertNotNull(res); - assertTrue(res.size() > 1); - assertTrue(res.contains(new MiriamData(MiriamRelationType.BQ_BIOL_IS_DESCRIBED_BY, MiriamType.CHEBI, - "CHEBI:24431"))); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + // unknown molecule + List<MiriamData> res = backend.getOntologyChebiIdsForChebiName("blablasblasblsabsal"); + assertNotNull(res); + assertEquals(0, res.size()); + + // and water + res = backend.getOntologyChebiIdsForChebiName("h2o"); + assertNotNull(res); + assertTrue(res.size() > 1); + assertTrue(res.contains(new MiriamData(MiriamRelationType.BQ_BIOL_IS_DESCRIBED_BY, MiriamType.CHEBI, + "CHEBI:24431"))); } @Test public void testChebiNameToId2() throws Exception { - try { - // and now tests more complicated (how to find hydron?) - MiriamData md = backend.getChebiForChebiName("hydron"); - assertNotNull(md); - assertTrue(md.getResource().contains("CHEBI:15378")); - md = backend.getChebiForChebiName("H+"); - assertNotNull(md); - assertTrue(md.getResource().contains("CHEBI:15378")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + // and now tests more complicated (how to find hydron?) + MiriamData md = backend.getChebiForChebiName("hydron"); + assertNotNull(md); + assertTrue(md.getResource().contains("CHEBI:15378")); + md = backend.getChebiForChebiName("H+"); + assertNotNull(md); + assertTrue(md.getResource().contains("CHEBI:15378")); } @Test public void testChebiNameToId3() throws Exception { - try { - // and the tricky one - I couldn't find it via chebi online search tool... - // But java API do the trick... - // assertEquals("CHEBI:456214",converter.chebiNameToId("NADP+")); - // however manual mapping done by chemist says different...: - MiriamData md = backend.getChebiForChebiName("NADP+"); - assertNotNull(md); - assertTrue(md.getResource().contains("CHEBI:18009")); - md = backend.getChebiForChebiName("NADP(+)"); - assertNotNull(md); - assertTrue(md.getResource().contains("CHEBI:18009")); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + // and the tricky one - I couldn't find it via chebi online search tool... + // But java API do the trick... + // assertEquals("CHEBI:456214",converter.chebiNameToId("NADP+")); + // however manual mapping done by chemist says different...: + MiriamData md = backend.getChebiForChebiName("NADP+"); + assertNotNull(md); + assertTrue(md.getResource().contains("CHEBI:18009")); + md = backend.getChebiForChebiName("NADP(+)"); + assertNotNull(md); + assertTrue(md.getResource().contains("CHEBI:18009")); } @Test public void testAnnotateChemical() throws Exception { - try { - SimpleMolecule simpleMolecule = new SimpleMolecule("id"); - simpleMolecule.setName("water"); + SimpleMolecule simpleMolecule = new SimpleMolecule("id"); + simpleMolecule.setName("water"); - backend.annotateElement(simpleMolecule); - - assertFalse(simpleMolecule.getFullName().equals("")); - assertFalse(simpleMolecule.getInChI().equals("")); - assertFalse(simpleMolecule.getInChIKey().equals("")); - assertFalse(simpleMolecule.getSmiles().equals("")); - assertFalse(simpleMolecule.getSynonyms().size() == 0); + backend.annotateElement(simpleMolecule); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertFalse(simpleMolecule.getFullName().equals("")); + assertFalse(simpleMolecule.getInChI().equals("")); + assertFalse(simpleMolecule.getInChIKey().equals("")); + assertFalse(simpleMolecule.getSmiles().equals("")); + assertFalse(simpleMolecule.getSynonyms().size() == 0); } - @Test + @Test(expected = AnnotatorException.class) public void testAnnotateWhenConnectionFails() throws Exception { try { SimpleMolecule simpleMolecule = new SimpleMolecule("id"); @@ -359,13 +256,6 @@ public class ChebiAnnotatorTest extends AnnotationTestFunctions { backend.setCache(null); backend.annotateElement(simpleMolecule); - - fail("Exception expected"); - } catch (AnnotatorException e) { - assertTrue(e.getMessage().contains("Problem with getting information about chebi")); - } catch (Exception e) { - e.printStackTrace(); - throw e; } finally { backend.setCache(cache); backend.setClient(null); @@ -374,73 +264,50 @@ public class ChebiAnnotatorTest extends AnnotationTestFunctions { @Test public void testAnnotateChemicalWithInvalidName() throws Exception { - try { - SimpleMolecule simpleMolecule = new SimpleMolecule("id"); - simpleMolecule.setName("blasdh"); + SimpleMolecule simpleMolecule = new SimpleMolecule("id"); + simpleMolecule.setName("blasdh"); - backend.annotateElement(simpleMolecule); + backend.annotateElement(simpleMolecule); - assertEquals(1, getWarnings().size()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(1, getWarnings().size()); } @Test public void testUpdateChemicalFromDb() throws Exception { - try { - SimpleMolecule simpleMolecule = new SimpleMolecule("id"); - simpleMolecule - .addMiriamData(new MiriamData(MiriamRelationType.BQ_BIOL_IS_DESCRIBED_BY, MiriamType.CHEBI, "CHEBI:15377")); + SimpleMolecule simpleMolecule = new SimpleMolecule("id"); + simpleMolecule + .addMiriamData(new MiriamData(MiriamRelationType.BQ_BIOL_IS_DESCRIBED_BY, MiriamType.CHEBI, "CHEBI:15377")); - backend.annotateElement(simpleMolecule); + backend.annotateElement(simpleMolecule); - assertFalse("".equals(simpleMolecule.getFullName())); - assertFalse(simpleMolecule.getInChI().equals("")); - assertFalse(simpleMolecule.getInChIKey().equals("")); - assertFalse(simpleMolecule.getSmiles().equals("")); - assertFalse(simpleMolecule.getSynonyms().size() == 0); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertFalse("".equals(simpleMolecule.getFullName())); + assertFalse(simpleMolecule.getInChI().equals("")); + assertFalse(simpleMolecule.getInChIKey().equals("")); + assertFalse(simpleMolecule.getSmiles().equals("")); + assertFalse(simpleMolecule.getSynonyms().size() == 0); } @Test public void testUpdateChemicalFromDbWithDifferentData() throws Exception { - try { - SimpleMolecule simpleMolecule = new SimpleMolecule("id"); - simpleMolecule.setName("water"); - simpleMolecule.setFullName("xxx"); - simpleMolecule.setInChI("x"); - simpleMolecule.setInChIKey("x"); - simpleMolecule.setSmiles("x"); - simpleMolecule.addSynonym("x"); - simpleMolecule - .addMiriamData(new MiriamData(MiriamRelationType.BQ_BIOL_IS_DESCRIBED_BY, MiriamType.CHEBI, "CHEBI:15377")); - - backend.annotateElement(simpleMolecule); + SimpleMolecule simpleMolecule = new SimpleMolecule("id"); + simpleMolecule.setName("water"); + simpleMolecule.setFullName("xxx"); + simpleMolecule.setInChI("x"); + simpleMolecule.setInChIKey("x"); + simpleMolecule.setSmiles("x"); + simpleMolecule.addSynonym("x"); + simpleMolecule + .addMiriamData(new MiriamData(MiriamRelationType.BQ_BIOL_IS_DESCRIBED_BY, MiriamType.CHEBI, "CHEBI:15377")); - assertEquals(5, getWarnings().size()); + backend.annotateElement(simpleMolecule); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(5, getWarnings().size()); } @Test public void testGetters() throws Exception { - try { - assertNotNull(backend.getCommonName()); - assertNotNull(backend.getUrl()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertNotNull(backend.getCommonName()); + assertNotNull(backend.getUrl()); } @Test @@ -468,10 +335,6 @@ public class ChebiAnnotatorTest extends AnnotationTestFunctions { String result = backend.refreshCacheQuery(query); assertNotNull(result); assertTrue(result.contains("CHEBI:18008")); - - } catch (Exception e) { - e.printStackTrace(); - throw e; } finally { // restore cache for other tests backend.setCache(cache); @@ -516,10 +379,6 @@ public class ChebiAnnotatorTest extends AnnotationTestFunctions { MiriamData result = backend.getChebiForChebiName(name); assertNotNull(result); assertEquals(chebiId, result.getResource()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; } finally { // restore cache for other tests backend.setCache(cache); @@ -568,10 +427,6 @@ public class ChebiAnnotatorTest extends AnnotationTestFunctions { MiriamData result = backend.getChebiForChebiName(name); assertNotNull(result); assertEquals(chebiId, result.getResource()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; } finally { // restore cache for other tests backend.setCache(cache); @@ -616,10 +471,6 @@ public class ChebiAnnotatorTest extends AnnotationTestFunctions { MiriamData result = backend.getChebiForChebiName(name); assertNotNull(result); assertEquals(chebiId, result.getResource()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; } finally { // restore cache for other tests backend.setCache(cache); @@ -668,10 +519,6 @@ public class ChebiAnnotatorTest extends AnnotationTestFunctions { MiriamData result = backend.getChebiForChebiName(name); assertNotNull(result); assertEquals(chebiId, result.getResource()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; } finally { // restore cache for other tests backend.setCache(cache); @@ -701,10 +548,6 @@ public class ChebiAnnotatorTest extends AnnotationTestFunctions { } catch (ChebiSearchException e) { assertTrue(e.getMessage().contains("Problem with chebi connection")); - - } catch (Exception e) { - e.printStackTrace(); - throw e; } finally { // restore cache for other tests backend.setCache(cache); @@ -713,7 +556,7 @@ public class ChebiAnnotatorTest extends AnnotationTestFunctions { } } - @Test + @Test(expected = SourceNotAvailable.class) public void testRefreshWhenProblemWithConnnector() throws Exception { cache = backend.getCache(); try { @@ -737,12 +580,6 @@ public class ChebiAnnotatorTest extends AnnotationTestFunctions { String query = ChebiAnnotator.ONTOLOGY_PREFIX + "CHEBI:18009"; backend.refreshCacheQuery(query); - fail("Exception expected"); - - } catch (SourceNotAvailable e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; } finally { // restore cache for other tests backend.setCache(cache); @@ -751,42 +588,19 @@ public class ChebiAnnotatorTest extends AnnotationTestFunctions { } } - @Test + @Test(expected = InvalidArgumentException.class) public void testRefreshInvalidQuery() throws Exception { - try { - backend.refreshCacheQuery("invalid string"); - - fail("Exception expected"); - } catch (InvalidArgumentException e) { - assertTrue(e.getMessage().contains("Don't know what to do")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + backend.refreshCacheQuery("invalid string"); } - @Test + @Test(expected = InvalidArgumentException.class) public void testRefreshInvalidQuery2() throws Exception { - try { - backend.refreshCacheQuery(new Object()); - - fail("Exception expected"); - } catch (InvalidArgumentException e) { - assertTrue(e.getMessage().contains("Don't know what to do")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + backend.refreshCacheQuery(new Object()); } @Test public void testStatus() throws Exception { - try { - assertEquals(ExternalServiceStatusType.OK, backend.getServiceStatus().getStatus()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(ExternalServiceStatusType.OK, backend.getServiceStatus().getStatus()); } @Test @@ -798,9 +612,6 @@ public class ChebiAnnotatorTest extends AnnotationTestFunctions { any())).thenThrow(new ChebiWebServiceFault_Exception(null, null)); backend.setClient(chebiWebServiceClient); assertEquals(ExternalServiceStatusType.DOWN, backend.getServiceStatus().getStatus()); - } catch (Exception e) { - e.printStackTrace(); - throw e; } finally { backend.setCache(cache); backend.setClient(null); @@ -841,9 +652,6 @@ public class ChebiAnnotatorTest extends AnnotationTestFunctions { eq(ChebiAnnotator.MAX_SEARCH_RESULTS_FROM_CHEBI_API), any())).thenReturn(liteEntityList); assertEquals(ExternalServiceStatusType.CHANGED, backend.getServiceStatus().getStatus()); - } catch (Exception e) { - e.printStackTrace(); - throw e; } finally { backend.setCache(cache); backend.setClient(null); diff --git a/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/ElementAnnotatorTest.java b/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/ElementAnnotatorTest.java index 90c0f42cf5d962f3c03584968758fa5d4c49742e..c2b91fbff508dade8b110aafcebb5a7415de0ef5 100644 --- a/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/ElementAnnotatorTest.java +++ b/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/ElementAnnotatorTest.java @@ -1,36 +1,25 @@ package lcsb.mapviewer.annotation.services.annotators; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.ArgumentMatchers.nullable; -import static org.mockito.Mockito.when; +import static org.junit.Assert.*; +import static org.mockito.ArgumentMatchers.*; +import static org.mockito.Mockito.*; import java.io.IOException; import java.util.Arrays; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.mockito.Mockito; import org.springframework.beans.factory.annotation.Autowired; import lcsb.mapviewer.annotation.AnnotationTestFunctions; -import lcsb.mapviewer.annotation.cache.GeneralCacheInterface; -import lcsb.mapviewer.annotation.cache.SourceNotAvailable; -import lcsb.mapviewer.annotation.cache.WebPageDownloader; +import lcsb.mapviewer.annotation.cache.*; import lcsb.mapviewer.common.exception.InvalidArgumentException; import lcsb.mapviewer.model.map.MiriamData; import lcsb.mapviewer.model.map.MiriamType; import lcsb.mapviewer.model.map.reaction.Reaction; import lcsb.mapviewer.model.map.species.GenericProtein; import lcsb.mapviewer.model.map.species.Ion; -import lcsb.mapviewer.model.user.annotator.AnnotatorData; -import lcsb.mapviewer.model.user.annotator.AnnotatorOutputParameter; -import lcsb.mapviewer.model.user.annotator.BioEntityField; +import lcsb.mapviewer.model.user.annotator.*; public class ElementAnnotatorTest extends AnnotationTestFunctions { @@ -172,16 +161,11 @@ public class ElementAnnotatorTest extends AnnotationTestFunctions { @Test public void testSetTheSameMcs() throws Exception { - try { - Reaction reaction = new Reaction(); - reaction.setMechanicalConfidenceScore(4); - ElementAnnotator.BioEntityProxy proxy = annotator.new BioEntityProxy(reaction, allOutputFieldsAndAnnotations); - proxy.setMechanicalConfidenceScore("4"); - assertEquals(0, getWarnings().size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Reaction reaction = new Reaction(); + reaction.setMechanicalConfidenceScore(4); + ElementAnnotator.BioEntityProxy proxy = annotator.new BioEntityProxy(reaction, allOutputFieldsAndAnnotations); + proxy.setMechanicalConfidenceScore("4"); + assertEquals(0, getWarnings().size()); } @Test @@ -215,42 +199,21 @@ public class ElementAnnotatorTest extends AnnotationTestFunctions { @Test public void testRefreshCacheQuery() throws Exception { - try { - Object res = autowiredAnnotator.refreshCacheQuery("http://google.cz/"); - assertNotNull(res); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Object res = autowiredAnnotator.refreshCacheQuery("http://google.cz/"); + assertNotNull(res); } - @Test + @Test(expected = InvalidArgumentException.class) public void testRefreshInvalidCacheQuery() throws Exception { - try { - autowiredAnnotator.refreshCacheQuery("invalid_query"); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - assertTrue(e.getMessage().contains("Don't know what to do")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + autowiredAnnotator.refreshCacheQuery("invalid_query"); } - @Test + @Test(expected = InvalidArgumentException.class) public void testRefreshInvalidCacheQuery2() throws Exception { - try { - autowiredAnnotator.refreshCacheQuery(new Object()); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - assertTrue(e.getMessage().contains("Don't know what to do")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + autowiredAnnotator.refreshCacheQuery(new Object()); } - @Test + @Test(expected = SourceNotAvailable.class) public void testRefreshCacheQueryNotAvailable() throws Exception { WebPageDownloader downloader = autowiredAnnotator.getWebPageDownloader(); GeneralCacheInterface originalCache = autowiredAnnotator.getCache(); @@ -263,11 +226,6 @@ public class ElementAnnotatorTest extends AnnotationTestFunctions { .thenThrow(new IOException()); autowiredAnnotator.setWebPageDownloader(mockDownloader); autowiredAnnotator.refreshCacheQuery("http://google.pl/"); - fail("Exception expected"); - } catch (SourceNotAvailable e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; } finally { autowiredAnnotator.setWebPageDownloader(downloader); autowiredAnnotator.setCache(originalCache); diff --git a/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/EnsemblAnnotatorTest.java b/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/EnsemblAnnotatorTest.java index 4c7bd250874b5fb1109f93b0c1071353d5609f8c..78a2dd104c0aa2f8cf03e1f034e9b81602f325f1 100644 --- a/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/EnsemblAnnotatorTest.java +++ b/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/EnsemblAnnotatorTest.java @@ -1,27 +1,17 @@ package lcsb.mapviewer.annotation.services.annotators; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.ArgumentMatchers.nullable; -import static org.mockito.Mockito.when; +import static org.junit.Assert.*; +import static org.mockito.ArgumentMatchers.*; +import static org.mockito.Mockito.*; import java.io.IOException; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.mockito.Mockito; import org.springframework.beans.factory.annotation.Autowired; import lcsb.mapviewer.annotation.AnnotationTestFunctions; -import lcsb.mapviewer.annotation.cache.GeneralCacheInterface; -import lcsb.mapviewer.annotation.cache.PermanentDatabaseLevelCacheInterface; -import lcsb.mapviewer.annotation.cache.SourceNotAvailable; -import lcsb.mapviewer.annotation.cache.WebPageDownloader; +import lcsb.mapviewer.annotation.cache.*; import lcsb.mapviewer.annotation.services.ExternalServiceStatusType; import lcsb.mapviewer.annotation.services.WrongResponseCodeIOException; import lcsb.mapviewer.model.map.MiriamData; @@ -47,126 +37,91 @@ public class EnsemblAnnotatorTest extends AnnotationTestFunctions { @Test public void testGetAnnotationsForEnsemblId() throws Exception { - try { - MiriamData nsmf = new MiriamData(MiriamType.ENSEMBL, "ENSG00000157764"); - GenericProtein proteinAlias = new GenericProtein("id"); - proteinAlias.addMiriamData(nsmf); - ensemblAnnotator.annotateElement(proteinAlias); - assertNotNull(proteinAlias.getSymbol()); - assertNotNull(proteinAlias.getFullName()); - assertTrue(proteinAlias.getMiriamData().size() > 1); - assertTrue(proteinAlias.getSynonyms().size() > 0); - - boolean ensemble = false; - boolean hgncId = false; - boolean hgncSymbol = false; - boolean entrez = false; - for (MiriamData md : proteinAlias.getMiriamData()) { - if (MiriamType.ENSEMBL.equals(md.getDataType())) { - ensemble = true; - } else if (MiriamType.HGNC.equals(md.getDataType())) { - hgncId = true; - } else if (MiriamType.HGNC_SYMBOL.equals(md.getDataType())) { - hgncSymbol = true; - } else if (MiriamType.ENTREZ.equals(md.getDataType())) { - entrez = true; - } + MiriamData nsmf = new MiriamData(MiriamType.ENSEMBL, "ENSG00000157764"); + GenericProtein proteinAlias = new GenericProtein("id"); + proteinAlias.addMiriamData(nsmf); + ensemblAnnotator.annotateElement(proteinAlias); + assertNotNull(proteinAlias.getSymbol()); + assertNotNull(proteinAlias.getFullName()); + assertTrue(proteinAlias.getMiriamData().size() > 1); + assertTrue(proteinAlias.getSynonyms().size() > 0); + + boolean ensemble = false; + boolean hgncId = false; + boolean hgncSymbol = false; + boolean entrez = false; + for (MiriamData md : proteinAlias.getMiriamData()) { + if (MiriamType.ENSEMBL.equals(md.getDataType())) { + ensemble = true; + } else if (MiriamType.HGNC.equals(md.getDataType())) { + hgncId = true; + } else if (MiriamType.HGNC_SYMBOL.equals(md.getDataType())) { + hgncSymbol = true; + } else if (MiriamType.ENTREZ.equals(md.getDataType())) { + entrez = true; } + } - assertTrue("Ensemble symbol cannot be found", ensemble); - assertTrue("Hgnc id cannot be found", hgncId); - assertTrue("Hgnc symbol cannot be found", hgncSymbol); - assertTrue("Entrez cannot be found", entrez); - - assertEquals(0, getWarnings().size()); + assertTrue("Ensemble symbol cannot be found", ensemble); + assertTrue("Hgnc id cannot be found", hgncId); + assertTrue("Hgnc symbol cannot be found", hgncSymbol); + assertTrue("Entrez cannot be found", entrez); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, getWarnings().size()); } @Test public void testGetAnnotationsWhenMoreThanOneId() throws Exception { - try { - MiriamData nsmf = new MiriamData(MiriamType.ENSEMBL, "ENSG00000157764"); - MiriamData nsmf1 = new MiriamData(MiriamType.ENSEMBL, "ENSG00000157765"); - GenericProtein proteinAlias = new GenericProtein("id"); - proteinAlias.addMiriamData(nsmf); - proteinAlias.addMiriamData(nsmf1); - ensemblAnnotator.annotateElement(proteinAlias); - - assertEquals(3, getWarnings().size()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + MiriamData nsmf = new MiriamData(MiriamType.ENSEMBL, "ENSG00000157764"); + MiriamData nsmf1 = new MiriamData(MiriamType.ENSEMBL, "ENSG00000157765"); + GenericProtein proteinAlias = new GenericProtein("id"); + proteinAlias.addMiriamData(nsmf); + proteinAlias.addMiriamData(nsmf1); + ensemblAnnotator.annotateElement(proteinAlias); + + assertEquals(3, getWarnings().size()); } @Test public void testGetAnnotationsWhenNoIdFound() throws Exception { - try { - GenericProtein proteinAlias = new GenericProtein("id"); - ensemblAnnotator.annotateElement(proteinAlias); + GenericProtein proteinAlias = new GenericProtein("id"); + ensemblAnnotator.annotateElement(proteinAlias); - assertEquals(0, getWarnings().size()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, getWarnings().size()); } @Test public void testGetAnnotationsForInvalid() throws Exception { - try { - MiriamData nsmf = new MiriamData(MiriamType.ENSEMBL, "blabla"); - GenericProtein proteinAlias = new GenericProtein("id"); - proteinAlias.addMiriamData(nsmf); - ensemblAnnotator.annotateElement(proteinAlias); - - assertEquals("There should be warning about invalid ensembl identifier", 1, getWarnings().size()); + MiriamData nsmf = new MiriamData(MiriamType.ENSEMBL, "blabla"); + GenericProtein proteinAlias = new GenericProtein("id"); + proteinAlias.addMiriamData(nsmf); + ensemblAnnotator.annotateElement(proteinAlias); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals("There should be warning about invalid ensembl identifier", 1, getWarnings().size()); } @Test(timeout = 15000) public void testCachableInterfaceInvalidate() throws Exception { String query = "http://google.pl/"; - try { - String newRes = "hello"; - - cache.setCachedQuery(query, ensemblAnnotator.getCacheType(), newRes); - String res = cache.getStringByQuery(query, ensemblAnnotator.getCacheType()); - assertEquals(newRes, res); - cache.invalidateByQuery(query, ensemblAnnotator.getCacheType()); + String newRes = "hello"; - permanentDatabaseLevelCache.waitToFinishTasks(); + cache.setCachedQuery(query, ensemblAnnotator.getCacheType(), newRes); + String res = cache.getStringByQuery(query, ensemblAnnotator.getCacheType()); + assertEquals(newRes, res); + cache.invalidateByQuery(query, ensemblAnnotator.getCacheType()); - res = cache.getStringByQuery(query, ensemblAnnotator.getCacheType()); + permanentDatabaseLevelCache.waitToFinishTasks(); - assertNotNull(res); + res = cache.getStringByQuery(query, ensemblAnnotator.getCacheType()); - assertFalse("Value wasn't refreshed from db", newRes.equals(res)); + assertNotNull(res); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertFalse("Value wasn't refreshed from db", newRes.equals(res)); } @Test public void testStatus() throws Exception { - try { - assertEquals(ExternalServiceStatusType.OK, ensemblAnnotator.getServiceStatus().getStatus()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(ExternalServiceStatusType.OK, ensemblAnnotator.getServiceStatus().getStatus()); } @Test @@ -182,9 +137,6 @@ public class EnsemblAnnotatorTest extends AnnotationTestFunctions { .thenThrow(new IOException()); ensemblAnnotator.setWebPageDownloader(mockDownloader); assertEquals(ExternalServiceStatusType.DOWN, ensemblAnnotator.getServiceStatus().getStatus()); - } catch (Exception e) { - e.printStackTrace(); - throw e; } finally { ensemblAnnotator.setWebPageDownloader(downloader); ensemblAnnotator.setCache(originalCache); @@ -206,9 +158,6 @@ public class EnsemblAnnotatorTest extends AnnotationTestFunctions { .thenReturn(versionXml); ensemblAnnotator.setWebPageDownloader(mockDownloader); assertEquals(ExternalServiceStatusType.CHANGED, ensemblAnnotator.getServiceStatus().getStatus()); - } catch (Exception e) { - e.printStackTrace(); - throw e; } finally { ensemblAnnotator.setWebPageDownloader(downloader); ensemblAnnotator.setCache(originalCache); @@ -230,9 +179,6 @@ public class EnsemblAnnotatorTest extends AnnotationTestFunctions { .thenReturn(versionXml); ensemblAnnotator.setWebPageDownloader(mockDownloader); assertEquals(ExternalServiceStatusType.CHANGED, ensemblAnnotator.getServiceStatus().getStatus()); - } catch (Exception e) { - e.printStackTrace(); - throw e; } finally { ensemblAnnotator.setWebPageDownloader(downloader); ensemblAnnotator.setCache(originalCache); @@ -251,15 +197,12 @@ public class EnsemblAnnotatorTest extends AnnotationTestFunctions { proteinAlias.addMiriamData(new MiriamData(MiriamType.ENSEMBL, "1234")); ensemblAnnotator.annotateElement(proteinAlias); assertEquals(1, getWarnings().size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; } finally { ensemblAnnotator.setWebPageDownloader(downloader); } } - @Test + @Test(expected = SourceNotAvailable.class) public void testRefreshCacheQueryNotAvailable() throws Exception { WebPageDownloader downloader = ensemblAnnotator.getWebPageDownloader(); GeneralCacheInterface originalCache = ensemblAnnotator.getCache(); @@ -272,11 +215,6 @@ public class EnsemblAnnotatorTest extends AnnotationTestFunctions { .thenThrow(new IOException()); ensemblAnnotator.setWebPageDownloader(mockDownloader); ensemblAnnotator.refreshCacheQuery("http://google.pl/"); - fail("Exception expected"); - } catch (SourceNotAvailable e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; } finally { ensemblAnnotator.setWebPageDownloader(downloader); ensemblAnnotator.setCache(originalCache); diff --git a/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/EntrezAnnotatorTest.java b/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/EntrezAnnotatorTest.java index ea1b3ec5da2a62d9634a46f7325273cfd79d4f5d..819b0363c379ae38e39b02dbeeb7ca9a21de1d8a 100644 --- a/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/EntrezAnnotatorTest.java +++ b/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/EntrezAnnotatorTest.java @@ -1,29 +1,17 @@ package lcsb.mapviewer.annotation.services.annotators; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.ArgumentMatchers.nullable; -import static org.mockito.Mockito.when; +import static org.junit.Assert.*; +import static org.mockito.ArgumentMatchers.*; +import static org.mockito.Mockito.*; import java.io.IOException; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.mockito.Mockito; import org.springframework.beans.factory.annotation.Autowired; import lcsb.mapviewer.annotation.AnnotationTestFunctions; -import lcsb.mapviewer.annotation.cache.GeneralCacheInterface; -import lcsb.mapviewer.annotation.cache.PermanentDatabaseLevelCacheInterface; -import lcsb.mapviewer.annotation.cache.SourceNotAvailable; -import lcsb.mapviewer.annotation.cache.WebPageDownloader; -import lcsb.mapviewer.annotation.cache.XmlSerializer; +import lcsb.mapviewer.annotation.cache.*; import lcsb.mapviewer.annotation.data.EntrezData; import lcsb.mapviewer.annotation.services.ExternalServiceStatusType; import lcsb.mapviewer.annotation.services.WrongResponseCodeIOException; @@ -51,90 +39,67 @@ public class EntrezAnnotatorTest extends AnnotationTestFunctions { @Test public void testGetAnnotationsForEntrezId() throws Exception { - try { - MiriamData nsmf = new MiriamData(MiriamType.ENTREZ, "6647"); - GenericProtein proteinAlias = new GenericProtein("id"); - proteinAlias.addMiriamData(nsmf); - entrezAnnotator.annotateElement(proteinAlias); - assertNotNull(proteinAlias.getSymbol()); - assertNotNull(proteinAlias.getFullName()); - assertNotNull(proteinAlias.getNotes()); - assertFalse(proteinAlias.getNotes().isEmpty()); - assertTrue(proteinAlias.getMiriamData().size() > 1); - assertTrue(proteinAlias.getSynonyms().size() > 0); - - boolean ensemble = false; - boolean hgncId = false; - boolean entrez = false; - for (MiriamData md : proteinAlias.getMiriamData()) { - if (MiriamType.ENSEMBL.equals(md.getDataType())) { - ensemble = true; - } else if (MiriamType.HGNC.equals(md.getDataType())) { - hgncId = true; - } else if (MiriamType.ENTREZ.equals(md.getDataType())) { - entrez = true; - } + MiriamData nsmf = new MiriamData(MiriamType.ENTREZ, "6647"); + GenericProtein proteinAlias = new GenericProtein("id"); + proteinAlias.addMiriamData(nsmf); + entrezAnnotator.annotateElement(proteinAlias); + assertNotNull(proteinAlias.getSymbol()); + assertNotNull(proteinAlias.getFullName()); + assertNotNull(proteinAlias.getNotes()); + assertFalse(proteinAlias.getNotes().isEmpty()); + assertTrue(proteinAlias.getMiriamData().size() > 1); + assertTrue(proteinAlias.getSynonyms().size() > 0); + + boolean ensemble = false; + boolean hgncId = false; + boolean entrez = false; + for (MiriamData md : proteinAlias.getMiriamData()) { + if (MiriamType.ENSEMBL.equals(md.getDataType())) { + ensemble = true; + } else if (MiriamType.HGNC.equals(md.getDataType())) { + hgncId = true; + } else if (MiriamType.ENTREZ.equals(md.getDataType())) { + entrez = true; } - - assertTrue("Ensemble symbol cannot be found", ensemble); - assertTrue("Hgnc id cannot be found", hgncId); - assertTrue("Entrez cannot be found", entrez); - - } catch (Exception e) { - e.printStackTrace(); - throw e; } + + assertTrue("Ensemble symbol cannot be found", ensemble); + assertTrue("Hgnc id cannot be found", hgncId); + assertTrue("Entrez cannot be found", entrez); } @Test(timeout = 15000) public void testGetAnnotationsForInvalid() throws Exception { - try { - MiriamData nsmf = new MiriamData(MiriamType.ENTREZ, "blabla"); - GenericProtein proteinAlias = new GenericProtein("id"); - proteinAlias.addMiriamData(nsmf); - entrezAnnotator.annotateElement(proteinAlias); + MiriamData nsmf = new MiriamData(MiriamType.ENTREZ, "blabla"); + GenericProtein proteinAlias = new GenericProtein("id"); + proteinAlias.addMiriamData(nsmf); + entrezAnnotator.annotateElement(proteinAlias); - assertEquals(1, getWarnings().size()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(1, getWarnings().size()); } @Test(timeout = 15000) public void testCachableInterfaceInvalidate() throws Exception { String query = "http://google.pl/"; - try { - String newRes = "hello"; - - cache.setCachedQuery(query, entrezAnnotator.getCacheType(), newRes); - String res = cache.getStringByQuery(query, entrezAnnotator.getCacheType()); - assertEquals(newRes, res); - cache.invalidateByQuery(query, entrezAnnotator.getCacheType()); + String newRes = "hello"; - permanentDatabaseLevelCache.waitToFinishTasks(); + cache.setCachedQuery(query, entrezAnnotator.getCacheType(), newRes); + String res = cache.getStringByQuery(query, entrezAnnotator.getCacheType()); + assertEquals(newRes, res); + cache.invalidateByQuery(query, entrezAnnotator.getCacheType()); - res = cache.getStringByQuery(query, entrezAnnotator.getCacheType()); + permanentDatabaseLevelCache.waitToFinishTasks(); - assertNotNull(res); + res = cache.getStringByQuery(query, entrezAnnotator.getCacheType()); - assertFalse("Value wasn't refreshed from db", newRes.equals(res)); + assertNotNull(res); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertFalse("Value wasn't refreshed from db", newRes.equals(res)); } @Test public void testStatus() throws Exception { - try { - assertEquals(ExternalServiceStatusType.OK, entrezAnnotator.getServiceStatus().getStatus()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(ExternalServiceStatusType.OK, entrezAnnotator.getServiceStatus().getStatus()); } @Test @@ -146,9 +111,6 @@ public class EntrezAnnotatorTest extends AnnotationTestFunctions { .thenThrow(new IOException()); entrezAnnotator.setWebPageDownloader(mockDownloader); assertEquals(ExternalServiceStatusType.DOWN, entrezAnnotator.getServiceStatus().getStatus()); - } catch (Exception e) { - e.printStackTrace(); - throw e; } finally { entrezAnnotator.setWebPageDownloader(downloader); } @@ -163,51 +125,27 @@ public class EntrezAnnotatorTest extends AnnotationTestFunctions { when(mockSerializer.xmlToObject(any())).thenReturn(new EntrezData()); entrezAnnotator.setEntrezSerializer(mockSerializer); assertEquals(ExternalServiceStatusType.CHANGED, entrezAnnotator.getServiceStatus().getStatus()); - } catch (Exception e) { - e.printStackTrace(); - throw e; } finally { entrezAnnotator.setEntrezSerializer(entrezSerializer); } } - @Test + @Test(expected = InvalidArgumentException.class) public void testRefreshInvalidCacheQuery() throws Exception { - try { - entrezAnnotator.refreshCacheQuery("invalid_query"); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - assertTrue(e.getMessage().contains("Don't know what to do")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + entrezAnnotator.refreshCacheQuery("invalid_query"); } - @Test + @Test(expected = InvalidArgumentException.class) public void testRefreshInvalidCacheQuery2() throws Exception { - try { - entrezAnnotator.refreshCacheQuery(new Object()); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - assertTrue(e.getMessage().contains("Don't know what to do")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + entrezAnnotator.refreshCacheQuery(new Object()); } @Test(timeout = 15000) public void testRefreshEntrezData() throws Exception { - try { - assertNotNull(entrezAnnotator.refreshCacheQuery(EntrezAnnotator.ENTREZ_DATA_PREFIX + "6647")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertNotNull(entrezAnnotator.refreshCacheQuery(EntrezAnnotator.ENTREZ_DATA_PREFIX + "6647")); } - @Test + @Test(expected = SourceNotAvailable.class) public void testRefreshCacheQueryNotAvailable() throws Exception { WebPageDownloader downloader = entrezAnnotator.getWebPageDownloader(); GeneralCacheInterface originalCache = entrezAnnotator.getCache(); @@ -220,18 +158,13 @@ public class EntrezAnnotatorTest extends AnnotationTestFunctions { .thenThrow(new IOException()); entrezAnnotator.setWebPageDownloader(mockDownloader); entrezAnnotator.refreshCacheQuery("http://google.pl/"); - fail("Exception expected"); - } catch (SourceNotAvailable e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; } finally { entrezAnnotator.setWebPageDownloader(downloader); entrezAnnotator.setCache(originalCache); } } - @Test + @Test(expected = SourceNotAvailable.class) public void testRefreshCacheQueryWithInvalidEntrezServerResponse() throws Exception { WebPageDownloader downloader = entrezAnnotator.getWebPageDownloader(); GeneralCacheInterface originalCache = entrezAnnotator.getCache(); @@ -244,11 +177,6 @@ public class EntrezAnnotatorTest extends AnnotationTestFunctions { .thenThrow(new IOException()); entrezAnnotator.setWebPageDownloader(mockDownloader); entrezAnnotator.refreshCacheQuery(EntrezAnnotator.ENTREZ_DATA_PREFIX + "6647"); - fail("Exception expected"); - } catch (SourceNotAvailable e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; } finally { entrezAnnotator.setWebPageDownloader(downloader); entrezAnnotator.setCache(originalCache); @@ -257,34 +185,22 @@ public class EntrezAnnotatorTest extends AnnotationTestFunctions { @Test public void testAnnotateElementWithTwoEntrez() throws Exception { - try { - Species proteinAlias = new GenericProtein("id"); - proteinAlias.addMiriamData(new MiriamData(MiriamType.ENTREZ, "6647")); - proteinAlias.addMiriamData(new MiriamData(MiriamType.ENTREZ, "6648")); - entrezAnnotator.annotateElement(proteinAlias); + Species proteinAlias = new GenericProtein("id"); + proteinAlias.addMiriamData(new MiriamData(MiriamType.ENTREZ, "6647")); + proteinAlias.addMiriamData(new MiriamData(MiriamType.ENTREZ, "6648")); + entrezAnnotator.annotateElement(proteinAlias); - assertEquals(3, getWarnings().size()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(3, getWarnings().size()); } @Test public void testAnnotateElementWithEncodedSynonyms() throws Exception { - try { - Species proteinAlias = new GenericProtein("id"); - proteinAlias.addMiriamData(new MiriamData(MiriamType.ENTREZ, "834106")); - entrezAnnotator.annotateElement(proteinAlias); - - for (String synonym : proteinAlias.getSynonyms()) { - assertFalse("Invalid character found in synonym: " + synonym, synonym.contains("&")); - } + Species proteinAlias = new GenericProtein("id"); + proteinAlias.addMiriamData(new MiriamData(MiriamType.ENTREZ, "834106")); + entrezAnnotator.annotateElement(proteinAlias); - } catch (Exception e) { - e.printStackTrace(); - throw e; + for (String synonym : proteinAlias.getSynonyms()) { + assertFalse("Invalid character found in synonym: " + synonym, synonym.contains("&")); } } @@ -313,17 +229,13 @@ public class EntrezAnnotatorTest extends AnnotationTestFunctions { assertTrue(hgnc); assertNotNull(data.getDescription()); assertFalse(data.getDescription().isEmpty()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; } finally { entrezAnnotator.setWebPageDownloader(downloader); entrezAnnotator.setCache(cache); } } - @Test + @Test(expected = AnnotatorException.class) public void testParseInvalidEntrezResponse() throws Exception { WebPageDownloader downloader = entrezAnnotator.getWebPageDownloader(); GeneralCacheInterface cache = entrezAnnotator.getCache(); @@ -334,11 +246,6 @@ public class EntrezAnnotatorTest extends AnnotationTestFunctions { when(mockDownloader.getFromNetwork(anyString(), anyString(), nullable(String.class))).thenReturn(response); entrezAnnotator.setWebPageDownloader(mockDownloader); entrezAnnotator.getEntrezForMiriamData(new MiriamData(), ""); - fail("Exception expected"); - } catch (AnnotatorException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; } finally { entrezAnnotator.setWebPageDownloader(downloader); entrezAnnotator.setCache(cache); @@ -346,7 +253,7 @@ public class EntrezAnnotatorTest extends AnnotationTestFunctions { } - @Test + @Test(expected = AnnotatorException.class) public void testParseInvalidEntrezResponse2() throws Exception { WebPageDownloader downloader = entrezAnnotator.getWebPageDownloader(); GeneralCacheInterface cache = entrezAnnotator.getCache(); @@ -357,11 +264,6 @@ public class EntrezAnnotatorTest extends AnnotationTestFunctions { .thenThrow(new WrongResponseCodeIOException(null, 404)); entrezAnnotator.setWebPageDownloader(mockDownloader); entrezAnnotator.getEntrezForMiriamData(new MiriamData(), ""); - fail("Exception expected"); - } catch (AnnotatorException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; } finally { entrezAnnotator.setWebPageDownloader(downloader); entrezAnnotator.setCache(cache); diff --git a/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/GoAnnotatorTest.java b/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/GoAnnotatorTest.java index 2cfc526f913e11bdbd0814a23c4825b08d783b84..e907c3753211f45377ed6a897808430f8065f896 100644 --- a/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/GoAnnotatorTest.java +++ b/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/GoAnnotatorTest.java @@ -1,34 +1,23 @@ package lcsb.mapviewer.annotation.services.annotators; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.ArgumentMatchers.nullable; -import static org.mockito.Mockito.when; +import static org.junit.Assert.*; +import static org.mockito.ArgumentMatchers.*; +import static org.mockito.Mockito.*; import java.io.IOException; -import org.apache.logging.log4j.*; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.junit.*; import org.mockito.Mockito; import org.springframework.beans.factory.annotation.Autowired; import lcsb.mapviewer.annotation.AnnotationTestFunctions; -import lcsb.mapviewer.annotation.cache.GeneralCacheInterface; -import lcsb.mapviewer.annotation.cache.PermanentDatabaseLevelCacheInterface; -import lcsb.mapviewer.annotation.cache.SourceNotAvailable; -import lcsb.mapviewer.annotation.cache.WebPageDownloader; +import lcsb.mapviewer.annotation.cache.*; import lcsb.mapviewer.annotation.data.Go; import lcsb.mapviewer.annotation.services.ExternalServiceStatusType; import lcsb.mapviewer.common.exception.InvalidArgumentException; -import lcsb.mapviewer.model.map.MiriamData; -import lcsb.mapviewer.model.map.MiriamRelationType; -import lcsb.mapviewer.model.map.MiriamType; +import lcsb.mapviewer.model.map.*; import lcsb.mapviewer.model.map.compartment.Compartment; public class GoAnnotatorTest extends AnnotationTestFunctions { @@ -50,75 +39,52 @@ public class GoAnnotatorTest extends AnnotationTestFunctions { @Test public void testContent() throws Exception { - try { - Compartment compartmentAlias = new Compartment("id"); - compartmentAlias - .addMiriamData(new MiriamData(MiriamRelationType.BQ_BIOL_IS_DESCRIBED_BY, MiriamType.GO, "GO:0046902")); - goAnnotator.annotateElement(compartmentAlias); - assertFalse(compartmentAlias.getFullName().equals("")); - assertFalse(compartmentAlias.getNotes().equals("")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Compartment compartmentAlias = new Compartment("id"); + compartmentAlias + .addMiriamData(new MiriamData(MiriamRelationType.BQ_BIOL_IS_DESCRIBED_BY, MiriamType.GO, "GO:0046902")); + goAnnotator.annotateElement(compartmentAlias); + assertFalse(compartmentAlias.getFullName().equals("")); + assertFalse(compartmentAlias.getNotes().equals("")); } @Test public void testGetGoData() throws Exception { - try { - MiriamData md = new MiriamData(MiriamRelationType.BQ_BIOL_IS_DESCRIBED_BY, MiriamType.GO, "GO:0042644"); - Go go = goAnnotator.getGoElement(md); - assertEquals("GO:0042644", go.getGoTerm()); - assertNotNull(go.getCommonName()); - assertNotNull(go.getDescription()); - assertTrue(go.getCommonName().toLowerCase().contains("chloroplast nucleoid")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + MiriamData md = new MiriamData(MiriamRelationType.BQ_BIOL_IS_DESCRIBED_BY, MiriamType.GO, "GO:0042644"); + Go go = goAnnotator.getGoElement(md); + assertEquals("GO:0042644", go.getGoTerm()); + assertNotNull(go.getCommonName()); + assertNotNull(go.getDescription()); + assertTrue(go.getCommonName().toLowerCase().contains("chloroplast nucleoid")); } - @Test + @Test(expected = GoSearchException.class) public void testAnnotateWhenProblemWithNetworkResponse() throws Exception { - try { - MiriamData md = new MiriamData(MiriamRelationType.BQ_BIOL_IS_DESCRIBED_BY, MiriamType.GO, "GO:0042644"); - GoAnnotator annotator = new GoAnnotator(null); - annotator.setMc(goAnnotator.getMc()); - WebPageDownloader downloader = Mockito.mock(WebPageDownloader.class); - when(downloader.getFromNetwork(anyString(), anyString(), nullable(String.class))).thenReturn(""); - annotator.setWebPageDownloader(downloader); - annotator.getGoElement(md); - fail("Exception expected"); - } catch (GoSearchException e) { - assertTrue(e.getMessage().contains("Problem with accesing go database")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + MiriamData md = new MiriamData(MiriamRelationType.BQ_BIOL_IS_DESCRIBED_BY, MiriamType.GO, "GO:0042644"); + GoAnnotator annotator = new GoAnnotator(null); + annotator.setMc(goAnnotator.getMc()); + WebPageDownloader downloader = Mockito.mock(WebPageDownloader.class); + when(downloader.getFromNetwork(anyString(), anyString(), nullable(String.class))).thenReturn(""); + annotator.setWebPageDownloader(downloader); + annotator.getGoElement(md); } @Test(timeout = 15000) public void testCachableInterface() throws Exception { String query = GoAnnotator.GO_TERM_CACHE_PREFIX + "GO:0046902"; String newRes = "hello"; - try { - cache.setCachedQuery(query, goAnnotator.getCacheType(), newRes); - cache.invalidateByQuery(query, goAnnotator.getCacheType()); + cache.setCachedQuery(query, goAnnotator.getCacheType(), newRes); + cache.invalidateByQuery(query, goAnnotator.getCacheType()); - permanentDatabaseLevelCache.waitToFinishTasks(); + permanentDatabaseLevelCache.waitToFinishTasks(); - String res = cache.getStringByQuery(query, goAnnotator.getCacheType()); + String res = cache.getStringByQuery(query, goAnnotator.getCacheType()); - assertNotNull(res); + assertNotNull(res); - assertFalse("Value wasn't refreshed from db", newRes.equals(res)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertFalse("Value wasn't refreshed from db", newRes.equals(res)); } - @Test + @Test(expected = SourceNotAvailable.class) public void testRefreshCacheQueryNotAvailable() throws Exception { WebPageDownloader downloader = goAnnotator.getWebPageDownloader(); GeneralCacheInterface originalCache = goAnnotator.getCache(); @@ -131,62 +97,31 @@ public class GoAnnotatorTest extends AnnotationTestFunctions { .thenThrow(new IOException()); goAnnotator.setWebPageDownloader(mockDownloader); goAnnotator.refreshCacheQuery("http://google.pl/"); - fail("Exception expected"); - } catch (SourceNotAvailable e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; } finally { goAnnotator.setWebPageDownloader(downloader); goAnnotator.setCache(originalCache); } } - @Test + @Test(expected = InvalidArgumentException.class) public void testRefreshInvalidCacheQuery() throws Exception { - try { - goAnnotator.refreshCacheQuery("invalid_query"); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - assertTrue(e.getMessage().contains("Don't know what to do")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + goAnnotator.refreshCacheQuery("invalid_query"); } - @Test + @Test(expected = InvalidArgumentException.class) public void testRefreshInvalidCacheQuery2() throws Exception { - try { - goAnnotator.refreshCacheQuery(new Object()); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - assertTrue(e.getMessage().contains("Don't know what to do")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + goAnnotator.refreshCacheQuery(new Object()); } @Test public void testRefreshCacheQuery() throws Exception { - try { - String res = goAnnotator.refreshCacheQuery("http://google.pl/"); - assertNotNull(res); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String res = goAnnotator.refreshCacheQuery("http://google.pl/"); + assertNotNull(res); } @Test(timeout = 15000) public void testStatus() throws Exception { - try { - assertEquals(ExternalServiceStatusType.OK, goAnnotator.getServiceStatus().getStatus()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(ExternalServiceStatusType.OK, goAnnotator.getServiceStatus().getStatus()); } @Test @@ -198,9 +133,6 @@ public class GoAnnotatorTest extends AnnotationTestFunctions { .thenThrow(new IOException()); goAnnotator.setWebPageDownloader(mockDownloader); assertEquals(ExternalServiceStatusType.DOWN, goAnnotator.getServiceStatus().getStatus()); - } catch (Exception e) { - e.printStackTrace(); - throw e; } finally { goAnnotator.setWebPageDownloader(downloader); } @@ -215,9 +147,6 @@ public class GoAnnotatorTest extends AnnotationTestFunctions { .thenReturn("{\"numberOfHits\": 1,\"results\": [{\"name\":\"x\"}]}"); goAnnotator.setWebPageDownloader(mockDownloader); assertEquals(ExternalServiceStatusType.CHANGED, goAnnotator.getServiceStatus().getStatus()); - } catch (Exception e) { - e.printStackTrace(); - throw e; } finally { goAnnotator.setWebPageDownloader(downloader); } @@ -232,9 +161,6 @@ public class GoAnnotatorTest extends AnnotationTestFunctions { .thenReturn("{\"numberOfHits\": 1,\"results\": [{}]}"); goAnnotator.setWebPageDownloader(mockDownloader); assertEquals(ExternalServiceStatusType.CHANGED, goAnnotator.getServiceStatus().getStatus()); - } catch (Exception e) { - e.printStackTrace(); - throw e; } finally { goAnnotator.setWebPageDownloader(downloader); } diff --git a/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/HgncAnnotatorTest.java b/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/HgncAnnotatorTest.java index 3d7f21dc102f0be169aea15b5c2a57425980a5a0..a57e8f255c458e284d6dfaeeda5090257a835561 100644 --- a/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/HgncAnnotatorTest.java +++ b/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/HgncAnnotatorTest.java @@ -1,22 +1,15 @@ package lcsb.mapviewer.annotation.services.annotators; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.ArgumentMatchers.nullable; -import static org.mockito.Mockito.when; +import static org.junit.Assert.*; +import static org.mockito.ArgumentMatchers.*; +import static org.mockito.Mockito.*; import java.io.IOException; import java.util.List; -import org.apache.logging.log4j.*; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.junit.*; import org.mockito.Mockito; import org.springframework.beans.factory.annotation.Autowired; @@ -50,441 +43,306 @@ public class HgncAnnotatorTest extends AnnotationTestFunctions { @Test public void testGetAnnotationsForSNCA() throws Exception { - try { - MiriamData snca = new MiriamData(MiriamType.HGNC_SYMBOL, "SNCA"); - GenericProtein proteinAlias = new GenericProtein("id"); - proteinAlias.addMiriamData(snca); - hgncAnnotator.annotateElement(proteinAlias); - assertNotNull(proteinAlias.getSymbol()); - assertTrue(proteinAlias.getFormerSymbols().size() > 0); - assertNotNull(proteinAlias.getFullName()); - assertTrue(proteinAlias.getMiriamData().size() > 1); - assertTrue(proteinAlias.getSynonyms().size() > 0); - - boolean ensemble = false; - boolean hgncId = false; - boolean hgncSymbol = false; - boolean refseq = false; - boolean entrez = false; - boolean uniprot = false; - for (MiriamData md : proteinAlias.getMiriamData()) { - if (MiriamType.ENSEMBL.equals(md.getDataType())) { - ensemble = true; - } else if (MiriamType.HGNC.equals(md.getDataType())) { - assertEquals("Invalid HGNC id", "11138", md.getResource()); - hgncId = true; - } else if (MiriamType.HGNC_SYMBOL.equals(md.getDataType())) { - hgncSymbol = true; - } else if (MiriamType.REFSEQ.equals(md.getDataType())) { - refseq = true; - } else if (MiriamType.ENTREZ.equals(md.getDataType())) { - entrez = true; - } else if (MiriamType.UNIPROT.equals(md.getDataType())) { - uniprot = true; - } + MiriamData snca = new MiriamData(MiriamType.HGNC_SYMBOL, "SNCA"); + GenericProtein proteinAlias = new GenericProtein("id"); + proteinAlias.addMiriamData(snca); + hgncAnnotator.annotateElement(proteinAlias); + assertNotNull(proteinAlias.getSymbol()); + assertTrue(proteinAlias.getFormerSymbols().size() > 0); + assertNotNull(proteinAlias.getFullName()); + assertTrue(proteinAlias.getMiriamData().size() > 1); + assertTrue(proteinAlias.getSynonyms().size() > 0); + + boolean ensemble = false; + boolean hgncId = false; + boolean hgncSymbol = false; + boolean refseq = false; + boolean entrez = false; + boolean uniprot = false; + for (MiriamData md : proteinAlias.getMiriamData()) { + if (MiriamType.ENSEMBL.equals(md.getDataType())) { + ensemble = true; + } else if (MiriamType.HGNC.equals(md.getDataType())) { + assertEquals("Invalid HGNC id", "11138", md.getResource()); + hgncId = true; + } else if (MiriamType.HGNC_SYMBOL.equals(md.getDataType())) { + hgncSymbol = true; + } else if (MiriamType.REFSEQ.equals(md.getDataType())) { + refseq = true; + } else if (MiriamType.ENTREZ.equals(md.getDataType())) { + entrez = true; + } else if (MiriamType.UNIPROT.equals(md.getDataType())) { + uniprot = true; } - logger.debug(proteinAlias.getMiriamData()); - - assertTrue("Ensemble symbol cannot be found", ensemble); - assertTrue("Hgnc id cannot be found", hgncId); - assertTrue("Hgnc symbol cannot be found", hgncSymbol); - assertTrue("RefSeq cannot be found", refseq); - assertTrue("Entrez cannot be found", entrez); - assertTrue("Uniprot cannot be found", uniprot); - - } catch (Exception e) { - e.printStackTrace(); - throw e; } + + assertTrue("Ensemble symbol cannot be found", ensemble); + assertTrue("Hgnc id cannot be found", hgncId); + assertTrue("Hgnc symbol cannot be found", hgncSymbol); + assertTrue("RefSeq cannot be found", refseq); + assertTrue("Entrez cannot be found", entrez); + assertTrue("Uniprot cannot be found", uniprot); } @Test public void testGetAnnotationsForElementWithMultiHGNC() throws Exception { - try { - MiriamData snca = new MiriamData(MiriamType.HGNC_SYMBOL, "SNCA"); - MiriamData park7 = new MiriamData(MiriamType.HGNC_SYMBOL, "PARK7"); - GenericProtein proteinAlias = new GenericProtein("id"); - proteinAlias.setName("SNCA"); - proteinAlias.addMiriamData(snca); - proteinAlias.addMiriamData(park7); - hgncAnnotator.annotateElement(proteinAlias); - - assertEquals(4, getWarnings().size()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + MiriamData snca = new MiriamData(MiriamType.HGNC_SYMBOL, "SNCA"); + MiriamData park7 = new MiriamData(MiriamType.HGNC_SYMBOL, "PARK7"); + GenericProtein proteinAlias = new GenericProtein("id"); + proteinAlias.setName("SNCA"); + proteinAlias.addMiriamData(snca); + proteinAlias.addMiriamData(park7); + hgncAnnotator.annotateElement(proteinAlias); + + assertEquals(4, getWarnings().size()); } @Test public void testGetAnnotationsForHGNC_ID() throws Exception { - try { - MiriamData nsmf = new MiriamData(MiriamType.HGNC, "11138"); - GenericProtein proteinAlias = new GenericProtein("id"); - proteinAlias.addMiriamData(nsmf); - hgncAnnotator.annotateElement(proteinAlias); - assertNotNull(proteinAlias.getSymbol()); - assertTrue(proteinAlias.getFormerSymbols().size() > 0); - assertNotNull(proteinAlias.getFullName()); - assertTrue(proteinAlias.getMiriamData().size() > 1); - assertTrue(proteinAlias.getSynonyms().size() > 0); - - boolean ensemble = false; - boolean hgncId = false; - boolean hgncSymbol = false; - boolean refseq = false; - boolean entrez = false; - for (MiriamData md : proteinAlias.getMiriamData()) { - if (MiriamType.ENSEMBL.equals(md.getDataType())) { - ensemble = true; - } else if (MiriamType.HGNC.equals(md.getDataType())) { - hgncId = true; - } else if (MiriamType.HGNC_SYMBOL.equals(md.getDataType())) { - hgncSymbol = true; - } else if (MiriamType.REFSEQ.equals(md.getDataType())) { - refseq = true; - } else if (MiriamType.ENTREZ.equals(md.getDataType())) { - entrez = true; - } + MiriamData nsmf = new MiriamData(MiriamType.HGNC, "11138"); + GenericProtein proteinAlias = new GenericProtein("id"); + proteinAlias.addMiriamData(nsmf); + hgncAnnotator.annotateElement(proteinAlias); + assertNotNull(proteinAlias.getSymbol()); + assertTrue(proteinAlias.getFormerSymbols().size() > 0); + assertNotNull(proteinAlias.getFullName()); + assertTrue(proteinAlias.getMiriamData().size() > 1); + assertTrue(proteinAlias.getSynonyms().size() > 0); + + boolean ensemble = false; + boolean hgncId = false; + boolean hgncSymbol = false; + boolean refseq = false; + boolean entrez = false; + for (MiriamData md : proteinAlias.getMiriamData()) { + if (MiriamType.ENSEMBL.equals(md.getDataType())) { + ensemble = true; + } else if (MiriamType.HGNC.equals(md.getDataType())) { + hgncId = true; + } else if (MiriamType.HGNC_SYMBOL.equals(md.getDataType())) { + hgncSymbol = true; + } else if (MiriamType.REFSEQ.equals(md.getDataType())) { + refseq = true; + } else if (MiriamType.ENTREZ.equals(md.getDataType())) { + entrez = true; } - - assertTrue("Ensemble symbol cannot be found", ensemble); - assertTrue("Hgnc id cannot be found", hgncId); - assertTrue("Hgnc symbol cannot be found", hgncSymbol); - assertTrue("RefSeq cannot be found", refseq); - assertTrue("Entrez cannot be found", entrez); - - } catch (Exception e) { - e.printStackTrace(); - throw e; } + + assertTrue("Ensemble symbol cannot be found", ensemble); + assertTrue("Hgnc id cannot be found", hgncId); + assertTrue("Hgnc symbol cannot be found", hgncSymbol); + assertTrue("RefSeq cannot be found", refseq); + assertTrue("Entrez cannot be found", entrez); } @Test public void testGetAnnotationsForSNCA2() throws Exception { - try { - GenericProtein proteinAlias = new GenericProtein("id"); - proteinAlias.setName("SNCA"); - hgncAnnotator.annotateElement(proteinAlias); - assertNotNull(proteinAlias.getSymbol()); - assertNotNull(proteinAlias.getName()); - assertTrue(proteinAlias.getFormerSymbols().size() > 0); - assertNotNull(proteinAlias.getFullName()); - assertTrue(proteinAlias.getMiriamData().size() > 1); - assertTrue(proteinAlias.getSynonyms().size() > 0); - - boolean ensemble = false; - boolean hgncId = false; - boolean hgncSymbol = false; - boolean refseq = false; - boolean entrez = false; - for (MiriamData md : proteinAlias.getMiriamData()) { - if (MiriamType.ENSEMBL.equals(md.getDataType())) { - ensemble = true; - } else if (MiriamType.HGNC.equals(md.getDataType())) { - hgncId = true; - } else if (MiriamType.HGNC_SYMBOL.equals(md.getDataType())) { - hgncSymbol = true; - } else if (MiriamType.REFSEQ.equals(md.getDataType())) { - refseq = true; - } else if (MiriamType.ENTREZ.equals(md.getDataType())) { - entrez = true; - } + GenericProtein proteinAlias = new GenericProtein("id"); + proteinAlias.setName("SNCA"); + hgncAnnotator.annotateElement(proteinAlias); + assertNotNull(proteinAlias.getSymbol()); + assertNotNull(proteinAlias.getName()); + assertTrue(proteinAlias.getFormerSymbols().size() > 0); + assertNotNull(proteinAlias.getFullName()); + assertTrue(proteinAlias.getMiriamData().size() > 1); + assertTrue(proteinAlias.getSynonyms().size() > 0); + + boolean ensemble = false; + boolean hgncId = false; + boolean hgncSymbol = false; + boolean refseq = false; + boolean entrez = false; + for (MiriamData md : proteinAlias.getMiriamData()) { + if (MiriamType.ENSEMBL.equals(md.getDataType())) { + ensemble = true; + } else if (MiriamType.HGNC.equals(md.getDataType())) { + hgncId = true; + } else if (MiriamType.HGNC_SYMBOL.equals(md.getDataType())) { + hgncSymbol = true; + } else if (MiriamType.REFSEQ.equals(md.getDataType())) { + refseq = true; + } else if (MiriamType.ENTREZ.equals(md.getDataType())) { + entrez = true; } - - assertTrue("Ensemble symbol cannot be found", ensemble); - assertTrue("Hgnc id cannot be found", hgncId); - assertTrue("Hgnc symbol cannot be found", hgncSymbol); - assertTrue("RefSeq cannot be found", refseq); - assertTrue("Entrez cannot be found", entrez); - - } catch (Exception e) { - e.printStackTrace(); - throw e; } + + assertTrue("Ensemble symbol cannot be found", ensemble); + assertTrue("Hgnc id cannot be found", hgncId); + assertTrue("Hgnc symbol cannot be found", hgncSymbol); + assertTrue("RefSeq cannot be found", refseq); + assertTrue("Entrez cannot be found", entrez); } @Test public void testGetAnnotationsForBID() throws Exception { - try { - GenericProtein bidProtein = new GenericProtein("id"); - bidProtein.setName("BID"); - hgncAnnotator.annotateElement(bidProtein); - - GenericProtein bidMutationProtein = new GenericProtein("id2"); - bidMutationProtein.setName("BID (p15)"); - hgncAnnotator.annotateElement(bidMutationProtein); - - assertEquals(bidProtein.getSymbol(), bidMutationProtein.getSymbol()); - assertEquals(bidProtein.getFormerSymbols(), bidMutationProtein.getFormerSymbols()); - assertEquals(bidProtein.getFullName(), bidMutationProtein.getFullName()); - assertEquals(bidProtein.getMiriamData(), bidMutationProtein.getMiriamData()); - assertEquals(bidProtein.getSynonyms(), bidMutationProtein.getSynonyms()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + GenericProtein bidProtein = new GenericProtein("id"); + bidProtein.setName("BID"); + hgncAnnotator.annotateElement(bidProtein); + + GenericProtein bidMutationProtein = new GenericProtein("id2"); + bidMutationProtein.setName("BID (p15)"); + hgncAnnotator.annotateElement(bidMutationProtein); + + assertEquals(bidProtein.getSymbol(), bidMutationProtein.getSymbol()); + assertEquals(bidProtein.getFormerSymbols(), bidMutationProtein.getFormerSymbols()); + assertEquals(bidProtein.getFullName(), bidMutationProtein.getFullName()); + assertEquals(bidProtein.getMiriamData(), bidMutationProtein.getMiriamData()); + assertEquals(bidProtein.getSynonyms(), bidMutationProtein.getSynonyms()); } @Test public void testGetAnnotationsForInvalid() throws Exception { - try { - Species proteinAlias = new GenericProtein("id"); - proteinAlias.setName("UNKNNOWNASD asd"); - hgncAnnotator.annotateElement(proteinAlias); + Species proteinAlias = new GenericProtein("id"); + proteinAlias.setName("UNKNNOWNASD asd"); + hgncAnnotator.annotateElement(proteinAlias); - assertEquals(1, getWarnings().size()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(1, getWarnings().size()); } @Test public void testGetAnnotationsForInvalid2() throws Exception { - try { - Species proteinAlias = new GenericProtein("id"); - proteinAlias.setName("cAMP/cGMP-dependent protein kinase"); - hgncAnnotator.annotateElement(proteinAlias); - - assertEquals(1, getWarnings().size()); + Species proteinAlias = new GenericProtein("id"); + proteinAlias.setName("cAMP/cGMP-dependent protein kinase"); + hgncAnnotator.annotateElement(proteinAlias); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(1, getWarnings().size()); } @Test(timeout = 15000) public void testCachableInterfaceInvalidate() throws Exception { String query = "http://google.pl/"; - try { - String newRes = "hello"; + String newRes = "hello"; - cache.setCachedQuery(query, hgncAnnotator.getCacheType(), newRes); - String res = cache.getStringByQuery(query, hgncAnnotator.getCacheType()); - assertEquals(newRes, res); - cache.invalidateByQuery(query, hgncAnnotator.getCacheType()); + cache.setCachedQuery(query, hgncAnnotator.getCacheType(), newRes); + String res = cache.getStringByQuery(query, hgncAnnotator.getCacheType()); + assertEquals(newRes, res); + cache.invalidateByQuery(query, hgncAnnotator.getCacheType()); - permanentDatabaseLevelCache.waitToFinishTasks(); + permanentDatabaseLevelCache.waitToFinishTasks(); - res = cache.getStringByQuery(query, hgncAnnotator.getCacheType()); + res = cache.getStringByQuery(query, hgncAnnotator.getCacheType()); - assertNotNull(res); + assertNotNull(res); - assertFalse("Value wasn't refreshed from db", newRes.equals(res)); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertFalse("Value wasn't refreshed from db", newRes.equals(res)); } @Test public void testStatus() throws Exception { - try { - assertEquals(ExternalServiceStatusType.OK, hgncAnnotator.getServiceStatus().getStatus()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(ExternalServiceStatusType.OK, hgncAnnotator.getServiceStatus().getStatus()); } @Test public void testGetAnnotationsForInvalidMiriamSet() throws Exception { - try { - MiriamData md1 = new MiriamData(MiriamType.HGNC, "11138"); - MiriamData md2 = new MiriamData(MiriamType.HGNC, "111382"); - Species proteinAlias = new GenericProtein(""); - proteinAlias.addMiriamData(md1); - proteinAlias.addMiriamData(md2); - hgncAnnotator.annotateElement(proteinAlias); - assertEquals(1, getWarnings().size()); - assertEquals("SNCA", proteinAlias.getName()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + MiriamData md1 = new MiriamData(MiriamType.HGNC, "11138"); + MiriamData md2 = new MiriamData(MiriamType.HGNC, "111382"); + Species proteinAlias = new GenericProtein(""); + proteinAlias.addMiriamData(md1); + proteinAlias.addMiriamData(md2); + hgncAnnotator.annotateElement(proteinAlias); + assertEquals(1, getWarnings().size()); + assertEquals("SNCA", proteinAlias.getName()); } @Test public void testHgncIdToUniprot() throws Exception { - try { - List<MiriamData> result = hgncAnnotator.hgncToUniprot(new MiriamData(MiriamType.HGNC, "11138")); - assertEquals(1, result.size()); - assertEquals(new MiriamData(MiriamType.UNIPROT, "P37840"), result.get(0)); - assertEquals(0, hgncAnnotator.hgncToUniprot(new MiriamData(MiriamType.HGNC, "1")).size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + List<MiriamData> result = hgncAnnotator.hgncToUniprot(new MiriamData(MiriamType.HGNC, "11138")); + assertEquals(1, result.size()); + assertEquals(new MiriamData(MiriamType.UNIPROT, "P37840"), result.get(0)); + assertEquals(0, hgncAnnotator.hgncToUniprot(new MiriamData(MiriamType.HGNC, "1")).size()); } @Test public void testHgncIdToName() throws Exception { - try { - assertEquals(new MiriamData(MiriamType.HGNC_SYMBOL, "FSD2"), - hgncAnnotator.hgncIdToHgncName(new MiriamData(MiriamType.HGNC, "18024"))); - assertEquals(new MiriamData(MiriamType.HGNC_SYMBOL, "LMOD1"), - hgncAnnotator.hgncIdToHgncName(new MiriamData(MiriamType.HGNC, "6647"))); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(new MiriamData(MiriamType.HGNC_SYMBOL, "FSD2"), + hgncAnnotator.hgncIdToHgncName(new MiriamData(MiriamType.HGNC, "18024"))); + assertEquals(new MiriamData(MiriamType.HGNC_SYMBOL, "LMOD1"), + hgncAnnotator.hgncIdToHgncName(new MiriamData(MiriamType.HGNC, "6647"))); } @Test public void testUnknownHgncIdToName() throws Exception { - try { - assertNull(hgncAnnotator.hgncIdToHgncName(new MiriamData(MiriamType.HGNC, "asd"))); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertNull(hgncAnnotator.hgncIdToHgncName(new MiriamData(MiriamType.HGNC, "asd"))); } @Test public void testHgncToUniProt1() throws Exception { - try { - List<MiriamData> list = hgncAnnotator.hgncToUniprot(new MiriamData(MiriamType.HGNC_SYMBOL, "CASP8")); - assertEquals(1, list.size()); - assertEquals("Q14790", list.get(0).getResource()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + List<MiriamData> list = hgncAnnotator.hgncToUniprot(new MiriamData(MiriamType.HGNC_SYMBOL, "CASP8")); + assertEquals(1, list.size()); + assertEquals("Q14790", list.get(0).getResource()); } - @Test + @Test(expected = InvalidArgumentException.class) public void testHgncToUniProtWithInvalidArg() throws Exception { - try { - hgncAnnotator.hgncToUniprot(new MiriamData(MiriamType.CAS, "CASP8")); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + hgncAnnotator.hgncToUniprot(new MiriamData(MiriamType.CAS, "CASP8")); } - @Test + @Test(expected = InvalidArgumentException.class) public void testHgncToEntrezWithInvalidArg() throws Exception { - try { - hgncAnnotator.hgncToEntrez(new MiriamData(MiriamType.CAS, "CASP8")); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + hgncAnnotator.hgncToEntrez(new MiriamData(MiriamType.CAS, "CASP8")); } @Test public void testIsValidHgnc() throws Exception { - try { - assertFalse(hgncAnnotator.isValidHgncMiriam(new MiriamData(MiriamType.CAS, "CASP8"))); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertFalse(hgncAnnotator.isValidHgncMiriam(new MiriamData(MiriamType.CAS, "CASP8"))); } @Test public void testIsValidHgnc2() throws Exception { - try { - assertTrue(hgncAnnotator.isValidHgncMiriam(new MiriamData(MiriamType.HGNC_SYMBOL, "CASP8"))); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertTrue(hgncAnnotator.isValidHgncMiriam(new MiriamData(MiriamType.HGNC_SYMBOL, "CASP8"))); } - @Test + @Test(expected = InvalidArgumentException.class) public void testHgncIdToNameWithInvalidArg() throws Exception { - try { - hgncAnnotator.hgncIdToHgncName(new MiriamData(MiriamType.CAS, "CASP8")); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + hgncAnnotator.hgncIdToHgncName(new MiriamData(MiriamType.CAS, "CASP8")); } @Test public void testHgncToUniProt2() throws Exception { - try { + MiriamData data1 = new MiriamData(MiriamType.HGNC_SYMBOL, "CASP8"); + MiriamData data2 = new MiriamData(MiriamType.HGNC_SYMBOL, "CASP10"); - MiriamData data1 = new MiriamData(MiriamType.HGNC_SYMBOL, "CASP8"); - MiriamData data2 = new MiriamData(MiriamType.HGNC_SYMBOL, "CASP10"); + List<MiriamData> list = hgncAnnotator.hgncToUniprot(data1); + assertEquals(1, list.size()); + assertEquals("Q14790", list.get(0).getResource()); - List<MiriamData> list = hgncAnnotator.hgncToUniprot(data1); - assertEquals(1, list.size()); - assertEquals("Q14790", list.get(0).getResource()); - - list = hgncAnnotator.hgncToUniprot(data2); - assertEquals(1, list.size()); - assertEquals("Q92851", list.get(0).getResource()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + list = hgncAnnotator.hgncToUniprot(data2); + assertEquals(1, list.size()); + assertEquals("Q92851", list.get(0).getResource()); } @Test public void testHgncToUniProt3() throws Exception { - try { - MiriamData data1 = new MiriamData(MiriamType.HGNC_SYMBOL, "blablabla invalid name"); - List<MiriamData> list = hgncAnnotator.hgncToUniprot(data1); - assertNotNull(list); - assertEquals(0, list.size()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + MiriamData data1 = new MiriamData(MiriamType.HGNC_SYMBOL, "blablabla invalid name"); + List<MiriamData> list = hgncAnnotator.hgncToUniprot(data1); + assertNotNull(list); + assertEquals(0, list.size()); } @Test public void testHgncToEntrez() throws Exception { - try { - // check by symbol - MiriamData data1 = new MiriamData(MiriamType.HGNC_SYMBOL, "PTGS1"); - MiriamData entrez = hgncAnnotator.hgncToEntrez(data1); - assertNotNull(entrez); - assertTrue(new MiriamData(MiriamType.ENTREZ, "5742").equals(entrez)); - - // check by id - data1 = new MiriamData(MiriamType.HGNC, "11138"); - entrez = hgncAnnotator.hgncToEntrez(data1); - assertNotNull(entrez); - assertTrue(new MiriamData(MiriamType.ENTREZ, "6622").equals(entrez)); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + // check by symbol + MiriamData data1 = new MiriamData(MiriamType.HGNC_SYMBOL, "PTGS1"); + MiriamData entrez = hgncAnnotator.hgncToEntrez(data1); + assertNotNull(entrez); + assertTrue(new MiriamData(MiriamType.ENTREZ, "5742").equals(entrez)); + + // check by id + data1 = new MiriamData(MiriamType.HGNC, "11138"); + entrez = hgncAnnotator.hgncToEntrez(data1); + assertNotNull(entrez); + assertTrue(new MiriamData(MiriamType.ENTREZ, "6622").equals(entrez)); } @Test public void testInvalidHgncToEntrez() throws Exception { - try { - MiriamData data1 = new MiriamData(MiriamType.HGNC_SYMBOL, "xxxxxsd"); - MiriamData entrez = hgncAnnotator.hgncToEntrez(data1); - assertNull(entrez); - - data1 = new MiriamData(MiriamType.HGNC, "xxxxxsd"); - entrez = hgncAnnotator.hgncToEntrez(data1); - assertNull(entrez); + MiriamData data1 = new MiriamData(MiriamType.HGNC_SYMBOL, "xxxxxsd"); + MiriamData entrez = hgncAnnotator.hgncToEntrez(data1); + assertNull(entrez); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + data1 = new MiriamData(MiriamType.HGNC, "xxxxxsd"); + entrez = hgncAnnotator.hgncToEntrez(data1); + assertNull(entrez); } @Test @@ -496,9 +354,6 @@ public class HgncAnnotatorTest extends AnnotationTestFunctions { .thenThrow(new IOException()); hgncAnnotator.setWebPageDownloader(mockDownloader); assertEquals(ExternalServiceStatusType.DOWN, hgncAnnotator.getServiceStatus().getStatus()); - } catch (Exception e) { - e.printStackTrace(); - throw e; } finally { hgncAnnotator.setWebPageDownloader(downloader); } @@ -513,9 +368,6 @@ public class HgncAnnotatorTest extends AnnotationTestFunctions { .thenReturn("<response><result/></response>"); hgncAnnotator.setWebPageDownloader(mockDownloader); assertEquals(ExternalServiceStatusType.CHANGED, hgncAnnotator.getServiceStatus().getStatus()); - } catch (Exception e) { - e.printStackTrace(); - throw e; } finally { hgncAnnotator.setWebPageDownloader(downloader); } diff --git a/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/KeggAnnotatorTest.java b/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/KeggAnnotatorTest.java index 7db8c0f41618fa6a71d99deabf967b901d8ffc17..6609554d4c94664cd16eeac50076afdf350b0735 100644 --- a/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/KeggAnnotatorTest.java +++ b/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/KeggAnnotatorTest.java @@ -1,22 +1,14 @@ package lcsb.mapviewer.annotation.services.annotators; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.ArgumentMatchers.nullable; -import static org.mockito.Mockito.when; +import static org.junit.Assert.*; +import static org.mockito.ArgumentMatchers.*; +import static org.mockito.Mockito.*; import java.io.IOException; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashSet; -import java.util.Set; +import java.util.*; import org.apache.http.HttpStatus; -import org.junit.After; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; +import org.junit.*; import org.mockito.Mockito; import org.springframework.beans.factory.annotation.Autowired; @@ -75,195 +67,137 @@ public class KeggAnnotatorTest extends AnnotationTestFunctions { @Test public void testAnnotateFromUniprotWithoutParams() throws Exception { - try { - - Species protein = new GenericProtein("id"); - protein.setName("bla"); - protein.addMiriamData(new MiriamData(MiriamType.UNIPROT, "Q42561")); - - keggAnnotator.annotateElement(protein); + Species protein = new GenericProtein("id"); + protein.setName("bla"); + protein.addMiriamData(new MiriamData(MiriamType.UNIPROT, "Q42561")); - Evaluate_3_1_2_14(protein); + keggAnnotator.annotateElement(protein); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Evaluate_3_1_2_14(protein); } @Test public void testAnnotateFromUniprotWithParams() throws Exception { - try { - - Species protein = new GenericProtein("id"); - protein.setName("bla"); - protein.addMiriamData(new MiriamData(MiriamType.UNIPROT, "Q42561")); - - AnnotatorData parameters = keggAnnotator.createAnnotatorData() - .addAnnotatorParameter(AnnotatorParamDefinition.KEGG_ORGANISM_IDENTIFIER, "ATH"); - keggAnnotator.annotateElement(protein, parameters); - - int cntTairs = 0; - for (MiriamData md : protein.getMiriamData()) { - if (md.getDataType().equals(MiriamType.TAIR_LOCUS)) { - cntTairs++; - } - } + Species protein = new GenericProtein("id"); + protein.setName("bla"); + protein.addMiriamData(new MiriamData(MiriamType.UNIPROT, "Q42561")); - assertTrue("Invalid number of TAIR annotators from KEGG", cntTairs == 3); + AnnotatorData parameters = keggAnnotator.createAnnotatorData() + .addAnnotatorParameter(AnnotatorParamDefinition.KEGG_ORGANISM_IDENTIFIER, "ATH"); + keggAnnotator.annotateElement(protein, parameters); - } catch (Exception e) { - e.printStackTrace(); - throw e; + int cntTairs = 0; + for (MiriamData md : protein.getMiriamData()) { + if (md.getDataType().equals(MiriamType.TAIR_LOCUS)) { + cntTairs++; + } } + + assertTrue("Invalid number of TAIR annotators from KEGG", cntTairs == 3); } @Test public void testAnnotateFromUniprotWithWrongParams1() throws Exception { - try { + Species protein = new GenericProtein("id"); + protein.setName("bla"); + protein.addMiriamData(new MiriamData(MiriamType.UNIPROT, "Q42561")); - Species protein = new GenericProtein("id"); - protein.setName("bla"); - protein.addMiriamData(new MiriamData(MiriamType.UNIPROT, "Q42561")); - - AnnotatorData parameters = keggAnnotator.createAnnotatorData() - .addAnnotatorParameter(AnnotatorParamDefinition.KEGG_ORGANISM_IDENTIFIER, "XXX"); - keggAnnotator.annotateElement(protein, parameters); + AnnotatorData parameters = keggAnnotator.createAnnotatorData() + .addAnnotatorParameter(AnnotatorParamDefinition.KEGG_ORGANISM_IDENTIFIER, "XXX"); + keggAnnotator.annotateElement(protein, parameters); - assertEquals("There should be warning about unsupported parameter", 1, getWarnings().size()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals("There should be warning about unsupported parameter", 1, getWarnings().size()); } @Test public void testAnnotateFromUniprotWithWrongParams2() throws Exception { - try { - - Species protein = new GenericProtein("id"); - protein.setName("bla"); - protein.addMiriamData(new MiriamData(MiriamType.UNIPROT, "Q42561")); - AnnotatorData parameters = keggAnnotator.createAnnotatorData() - .addAnnotatorParameter(AnnotatorParamDefinition.KEGG_ORGANISM_IDENTIFIER, "ATH AAA"); - keggAnnotator.annotateElement(protein, parameters); - - int cntTairs = 0; - for (MiriamData md : protein.getMiriamData()) { - if (md.getDataType().equals(MiriamType.TAIR_LOCUS)) { - cntTairs++; - } + Species protein = new GenericProtein("id"); + protein.setName("bla"); + protein.addMiriamData(new MiriamData(MiriamType.UNIPROT, "Q42561")); + AnnotatorData parameters = keggAnnotator.createAnnotatorData() + .addAnnotatorParameter(AnnotatorParamDefinition.KEGG_ORGANISM_IDENTIFIER, "ATH AAA"); + keggAnnotator.annotateElement(protein, parameters); + + int cntTairs = 0; + for (MiriamData md : protein.getMiriamData()) { + if (md.getDataType().equals(MiriamType.TAIR_LOCUS)) { + cntTairs++; } - - assertTrue("Invalid number of TAIR annotators from KEGG", cntTairs == 3); - assertEquals("There should be warning about unsupported parameter", 1, getWarnings().size()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; } + + assertTrue("Invalid number of TAIR annotators from KEGG", cntTairs == 3); + assertEquals("There should be warning about unsupported parameter", 1, getWarnings().size()); } @Test public void testAnnotateFromEc() throws Exception { - try { + Species protein = new GenericProtein("id"); + protein.setName("bla"); + protein.addMiriamData(new MiriamData(MiriamType.EC, "3.1.2.14")); - Species protein = new GenericProtein("id"); - protein.setName("bla"); - protein.addMiriamData(new MiriamData(MiriamType.EC, "3.1.2.14")); + keggAnnotator.annotateElement(protein); - keggAnnotator.annotateElement(protein); - - Evaluate_3_1_2_14(protein); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Evaluate_3_1_2_14(protein); } @Test @Ignore("TAIR DB restricts queries by IP") public void testAnnotateFromTair() throws Exception { - try { - Species protein = new GenericProtein("id"); - protein.setName("bla"); - protein.addMiriamData(new MiriamData(MiriamType.TAIR_LOCUS, "2090285")); //TAIR locus AT3G25110 - - keggAnnotator.annotateElement(protein); + Species protein = new GenericProtein("id"); + protein.setName("bla"); + protein.addMiriamData(new MiriamData(MiriamType.TAIR_LOCUS, "2090285")); // TAIR locus AT3G25110 - Evaluate_3_1_2_14(protein); + keggAnnotator.annotateElement(protein); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Evaluate_3_1_2_14(protein); } @Test public void testAnnotateFromUniprotWithMultipleECs() throws Exception { - try { - Species protein = new GenericProtein("id"); - protein.setName("bla"); - protein.addMiriamData(new MiriamData(MiriamType.UNIPROT, "P12345")); + Species protein = new GenericProtein("id"); + protein.setName("bla"); + protein.addMiriamData(new MiriamData(MiriamType.UNIPROT, "P12345")); - keggAnnotator.annotateElement(protein); + keggAnnotator.annotateElement(protein); - Collection<MiriamData> mdPubmed = new ArrayList<>(); + Collection<MiriamData> mdPubmed = new ArrayList<>(); - for (MiriamData md : protein.getMiriamData()) { - if (md.getDataType().equals(MiriamType.PUBMED)) { - mdPubmed.add(md); - } + for (MiriamData md : protein.getMiriamData()) { + if (md.getDataType().equals(MiriamType.PUBMED)) { + mdPubmed.add(md); } - - assertEquals("Wrong number of publications extracted from KEGG annotator", 9, mdPubmed.size()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; } + + assertEquals("Wrong number of publications extracted from KEGG annotator", 9, mdPubmed.size()); } @Test public void testAnnotateFromUniprotWithMultipleECsAndEC() throws Exception { - try { - Species protein = new GenericProtein("id"); - protein.setName("bla"); - protein.addMiriamData(new MiriamData(MiriamType.UNIPROT, "P12345")); - protein.addMiriamData(new MiriamData(MiriamType.EC, "3.1.2.14")); + Species protein = new GenericProtein("id"); + protein.setName("bla"); + protein.addMiriamData(new MiriamData(MiriamType.UNIPROT, "P12345")); + protein.addMiriamData(new MiriamData(MiriamType.EC, "3.1.2.14")); - keggAnnotator.annotateElement(protein); + keggAnnotator.annotateElement(protein); - Collection<MiriamData> mdPubmed = new ArrayList<>(); + Collection<MiriamData> mdPubmed = new ArrayList<>(); - for (MiriamData md : protein.getMiriamData()) { - if (md.getDataType().equals(MiriamType.PUBMED)) { - mdPubmed.add(md); - } + for (MiriamData md : protein.getMiriamData()) { + if (md.getDataType().equals(MiriamType.PUBMED)) { + mdPubmed.add(md); } - - assertTrue("Wrong number of publications extracted from KEGG annotator", mdPubmed.size() >= 9); - - } catch (Exception e) { - e.printStackTrace(); - throw e; } + + assertTrue("Wrong number of publications extracted from KEGG annotator", mdPubmed.size() >= 9); } @Test public void testAnnotateInvalidEmpty() throws Exception { - try { - Species protein = new GenericProtein("id"); - protein.setName("bla"); - keggAnnotator.annotateElement(protein); + Species protein = new GenericProtein("id"); + protein.setName("bla"); + keggAnnotator.annotateElement(protein); - assertEquals(0, protein.getMiriamData().size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, protein.getMiriamData().size()); } @Test @@ -282,10 +216,6 @@ public class KeggAnnotatorTest extends AnnotationTestFunctions { assertEquals(1, protein.getMiriamData().size()); assertTrue(getWarnings().size() > 0); - - } catch (Exception e) { - e.printStackTrace(); - throw e; } finally { uniprotAnnotator.setWebPageDownloader(downloader); } @@ -293,29 +223,18 @@ public class KeggAnnotatorTest extends AnnotationTestFunctions { @Test public void testAnnotateInvalidTair() throws Exception { - try { - Species protein = new GenericProtein("id"); - protein.addMiriamData(new MiriamData(MiriamType.TAIR_LOCUS, "bla")); - keggAnnotator.annotateElement(protein); - - assertEquals(1, protein.getMiriamData().size()); + Species protein = new GenericProtein("id"); + protein.addMiriamData(new MiriamData(MiriamType.TAIR_LOCUS, "bla")); + keggAnnotator.annotateElement(protein); - assertTrue(getWarnings().size() > 0); + assertEquals(1, protein.getMiriamData().size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertTrue(getWarnings().size() > 0); } @Test public void testStatus() throws Exception { - try { - assertEquals(ExternalServiceStatusType.OK, keggAnnotator.getServiceStatus().getStatus()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(ExternalServiceStatusType.OK, keggAnnotator.getServiceStatus().getStatus()); } @Test @@ -327,9 +246,6 @@ public class KeggAnnotatorTest extends AnnotationTestFunctions { .thenThrow(new IOException()); keggAnnotator.setWebPageDownloader(mockDownloader); assertEquals(ExternalServiceStatusType.DOWN, keggAnnotator.getServiceStatus().getStatus()); - } catch (Exception e) { - e.printStackTrace(); - throw e; } finally { keggAnnotator.setWebPageDownloader(downloader); } @@ -344,9 +260,6 @@ public class KeggAnnotatorTest extends AnnotationTestFunctions { .thenReturn("GN Name=ACSS2; Synonyms=ACAS2;"); keggAnnotator.setWebPageDownloader(mockDownloader); assertEquals(ExternalServiceStatusType.CHANGED, keggAnnotator.getServiceStatus().getStatus()); - } catch (Exception e) { - e.printStackTrace(); - throw e; } finally { keggAnnotator.setWebPageDownloader(downloader); } diff --git a/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/MultipleAnnotatorsTest.java b/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/MultipleAnnotatorsTest.java index 56fbb37765ae5c052c3cf1c6903a1eabf6c3bb3e..e2b2294988be4c7189e80518911dc67fe0196fa8 100644 --- a/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/MultipleAnnotatorsTest.java +++ b/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/MultipleAnnotatorsTest.java @@ -1,10 +1,8 @@ package lcsb.mapviewer.annotation.services.annotators; -import static org.junit.Assert.assertEquals; +import static org.junit.Assert.*; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.springframework.beans.factory.annotation.Autowired; import lcsb.mapviewer.annotation.AnnotationTestFunctions; @@ -34,30 +32,23 @@ public class MultipleAnnotatorsTest extends AnnotationTestFunctions { @Test public void testAnnotateUniprotByUniprotAndKegg() throws Exception { - try { - - Species protein = new GenericProtein("id"); - protein.setName("bla"); - protein.addMiriamData(new MiriamData(MiriamType.UNIPROT, "P12345")); - - keggAnnotator.annotateElement(protein); - uniprotAnnotator.annotateElement(protein); - hgncAnnotator.annotateElement(protein); - // biocompendiumAnnotator.annotateElement(protein); - - int cntNoAnnotator = 0; - for (MiriamData md : protein.getMiriamData()) { - if (md.getAnnotator() == null) { - cntNoAnnotator++; - } + Species protein = new GenericProtein("id"); + protein.setName("bla"); + protein.addMiriamData(new MiriamData(MiriamType.UNIPROT, "P12345")); + + keggAnnotator.annotateElement(protein); + uniprotAnnotator.annotateElement(protein); + hgncAnnotator.annotateElement(protein); + // biocompendiumAnnotator.annotateElement(protein); + + int cntNoAnnotator = 0; + for (MiriamData md : protein.getMiriamData()) { + if (md.getAnnotator() == null) { + cntNoAnnotator++; } - - assertEquals("Wrong number of annotated elements with no information about annotator", 1, cntNoAnnotator); - - } catch (Exception e) { - e.printStackTrace(); - throw e; } + + assertEquals("Wrong number of annotated elements with no information about annotator", 1, cntNoAnnotator); } } diff --git a/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/PdbAnnotatorTest.java b/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/PdbAnnotatorTest.java index 2eac724fa920edee5164cc112ee98bd0a0e85b59..b73292ab9fb9457da909807ea5ec4d76049acb3f 100644 --- a/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/PdbAnnotatorTest.java +++ b/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/PdbAnnotatorTest.java @@ -1,18 +1,12 @@ package lcsb.mapviewer.annotation.services.annotators; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.ArgumentMatchers.nullable; -import static org.mockito.Mockito.when; +import static org.junit.Assert.*; +import static org.mockito.ArgumentMatchers.*; +import static org.mockito.Mockito.*; import java.util.Set; -import org.junit.After; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; +import org.junit.*; import org.mockito.Mockito; import org.springframework.beans.factory.annotation.Autowired; @@ -44,147 +38,118 @@ public class PdbAnnotatorTest extends AnnotationTestFunctions { @Test public void testAnnotate1() throws Exception { - try { - String uniprotId = "P29373"; - Species protein = new GenericProtein("id"); - protein.setName(uniprotId); - /* - * One needs to have the UniProt ID first. This tests simulates situation when - * the Uniprot annotator is called first. - */ - uniprotAnnotator.annotateElement(protein); - int cntAnnotations1 = protein.getMiriamData().size(); - pdbAnnotator.annotateElement(protein); - int cntAnnotations2 = protein.getMiriamData().size(); - - assertTrue(cntAnnotations2 > cntAnnotations1); - - boolean pdb = false; - - for (MiriamData md : protein.getMiriamData()) { - if (md.getDataType().equals(MiriamType.PDB)) { - pdb = true; - break; - } + String uniprotId = "P29373"; + Species protein = new GenericProtein("id"); + protein.setName(uniprotId); + /* + * One needs to have the UniProt ID first. This tests simulates situation when + * the Uniprot annotator is called first. + */ + uniprotAnnotator.annotateElement(protein); + int cntAnnotations1 = protein.getMiriamData().size(); + pdbAnnotator.annotateElement(protein); + int cntAnnotations2 = protein.getMiriamData().size(); + + assertTrue(cntAnnotations2 > cntAnnotations1); + + boolean pdb = false; + + for (MiriamData md : protein.getMiriamData()) { + if (md.getDataType().equals(MiriamType.PDB)) { + pdb = true; + break; } - assertTrue("No PDB annotation extracted from pdb annotator", pdb); - - Set<UniprotRecord> urs = protein.getUniprots(); - // Test whether there is a uniprot record - assertTrue(urs.size() > 0); - UniprotRecord ur = null; - for (UniprotRecord ur1 : urs) { - if (ur1.getUniprotId() == uniprotId) { - ur = ur1; - } + } + assertTrue("No PDB annotation extracted from pdb annotator", pdb); + + Set<UniprotRecord> urs = protein.getUniprots(); + // Test whether there is a uniprot record + assertTrue(urs.size() > 0); + UniprotRecord ur = null; + for (UniprotRecord ur1 : urs) { + if (ur1.getUniprotId() == uniprotId) { + ur = ur1; } - // Test whether there is a uniprot record with the uniprot ID which was stored - assertNotNull(ur); - // Test whether structures are there - Set<Structure> ss = ur.getStructures(); - assertNotNull(ss); - assertTrue(ss.size() > 0); - // Test whether uniprot is accessible from structure - assertTrue(ss.iterator().next().getUniprot() == ur); - } catch (Exception e) { - e.printStackTrace(); - throw e; } + // Test whether there is a uniprot record with the uniprot ID which was stored + assertNotNull(ur); + // Test whether structures are there + Set<Structure> ss = ur.getStructures(); + assertNotNull(ss); + assertTrue(ss.size() > 0); + // Test whether uniprot is accessible from structure + assertTrue(ss.iterator().next().getUniprot() == ur); } @Test @Ignore public void testAnnotate2() throws Exception { - try { - Species protein = new GenericProtein("id"); - protein.setName("P29373"); - /* - * One needs to have the UniProt ID first, and Uniprot lookup through HGNC is - * included in PDB annotator. This tests simulates situation when the PDB - * annotator is called first. - */ - pdbAnnotator.annotateElement(protein); - int cntAnnotations = protein.getMiriamData().size(); - - assertTrue(cntAnnotations > 0); - - boolean pdb = false; - - for (MiriamData md : protein.getMiriamData()) { - if (md.getDataType().equals(MiriamType.PDB)) { - pdb = true; - break; - } + Species protein = new GenericProtein("id"); + protein.setName("P29373"); + /* + * One needs to have the UniProt ID first, and Uniprot lookup through HGNC is + * included in PDB annotator. This tests simulates situation when the PDB + * annotator is called first. + */ + pdbAnnotator.annotateElement(protein); + int cntAnnotations = protein.getMiriamData().size(); + + assertTrue(cntAnnotations > 0); + + boolean pdb = false; + + for (MiriamData md : protein.getMiriamData()) { + if (md.getDataType().equals(MiriamType.PDB)) { + pdb = true; + break; } - assertTrue("No PDB annotation extracted from pdb annotator", pdb); - - } catch (Exception e) { - e.printStackTrace(); - throw e; } + assertTrue("No PDB annotation extracted from pdb annotator", pdb); } @Test @Ignore public void testAnnotateNotUniprotAnnodated() throws Exception { - try { - Species protein = new GenericProtein("id"); - protein.setName("P29373"); - pdbAnnotator.annotateElement(protein); + Species protein = new GenericProtein("id"); + protein.setName("P29373"); + pdbAnnotator.annotateElement(protein); - assertTrue("UniProt annotation in PDB annotator failed", protein.getMiriamData().size() > 0); + assertTrue("UniProt annotation in PDB annotator failed", protein.getMiriamData().size() > 0); - boolean pdb = false; + boolean pdb = false; - for (MiriamData md : protein.getMiriamData()) { - if (md.getDataType().equals(MiriamType.PDB)) { - pdb = true; - break; - } + for (MiriamData md : protein.getMiriamData()) { + if (md.getDataType().equals(MiriamType.PDB)) { + pdb = true; + break; } - assertTrue("No PDB annotation extracted from PDB annotator", pdb); - - } catch (Exception e) { - e.printStackTrace(); - throw e; } + assertTrue("No PDB annotation extracted from PDB annotator", pdb); } @Test public void testAnnotateInvalidUniprot() throws Exception { - try { - Species protein = new GenericProtein("id"); - protein.setName("bla"); - pdbAnnotator.annotateElement(protein); + Species protein = new GenericProtein("id"); + protein.setName("bla"); + pdbAnnotator.annotateElement(protein); - assertEquals(0, protein.getMiriamData().size()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, protein.getMiriamData().size()); } @Test public void testAnnotateValidUniprotNonexistingPdb() throws Exception { - try { - Species protein = new GenericProtein("id"); - protein.setName("Q88VP8"); - pdbAnnotator.annotateElement(protein); - - boolean pdb = false; - for (MiriamData md : protein.getMiriamData()) { - if (md.getDataType().equals(MiriamType.PDB)) { - pdb = true; - break; - } + Species protein = new GenericProtein("id"); + protein.setName("Q88VP8"); + pdbAnnotator.annotateElement(protein); + + boolean pdb = false; + for (MiriamData md : protein.getMiriamData()) { + if (md.getDataType().equals(MiriamType.PDB)) { + pdb = true; + break; } - assertTrue("PDB mapping found for structure for which no should be available", !pdb); - - } catch (Exception e) { - e.printStackTrace(); - throw e; } + assertTrue("PDB mapping found for structure for which no should be available", !pdb); } @Test @@ -195,9 +160,6 @@ public class PdbAnnotatorTest extends AnnotationTestFunctions { when(mockDownloader.getFromNetwork(anyString(), anyString(), anyString())).thenReturn(""); pdbAnnotator.setWebPageDownloader(mockDownloader); assertEquals(ExternalServiceStatusType.DOWN, pdbAnnotator.getServiceStatus().getStatus()); - } catch (Exception e) { - e.printStackTrace(); - throw e; } finally { pdbAnnotator.setWebPageDownloader(downloader); } @@ -212,9 +174,6 @@ public class PdbAnnotatorTest extends AnnotationTestFunctions { .thenReturn("{\"P29373\": [{\"xxx\": 140}]}"); pdbAnnotator.setWebPageDownloader(mockDownloader); assertEquals(ExternalServiceStatusType.CHANGED, pdbAnnotator.getServiceStatus().getStatus()); - } catch (Exception e) { - e.printStackTrace(); - throw e; } finally { pdbAnnotator.setWebPageDownloader(downloader); } @@ -237,9 +196,6 @@ public class PdbAnnotatorTest extends AnnotationTestFunctions { pdbAnnotator.annotateElement(protein); int cntAnnotations2 = protein.getMiriamData().size(); assertTrue(cntAnnotations1 == cntAnnotations2); - } catch (Exception e) { - e.printStackTrace(); - throw e; } finally { pdbAnnotator.setWebPageDownloader(downloader); } diff --git a/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/ReconAnnotatorTest.java b/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/ReconAnnotatorTest.java index a6a57dc8b9f65cd166803d3cbad2b6a8a490c88a..475f7d55ad29a2be3484862f78b3008ed266d3f8 100644 --- a/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/ReconAnnotatorTest.java +++ b/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/ReconAnnotatorTest.java @@ -1,20 +1,14 @@ package lcsb.mapviewer.annotation.services.annotators; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.ArgumentMatchers.nullable; -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.when; +import static org.junit.Assert.*; +import static org.mockito.ArgumentMatchers.*; +import static org.mockito.Mockito.*; import java.io.IOException; -import org.apache.logging.log4j.*; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.junit.*; import org.mockito.Mockito; import org.springframework.beans.factory.annotation.Autowired; @@ -24,9 +18,7 @@ import lcsb.mapviewer.annotation.cache.WebPageDownloader; import lcsb.mapviewer.annotation.services.ExternalServiceStatusType; import lcsb.mapviewer.model.map.BioEntity; import lcsb.mapviewer.model.map.reaction.Reaction; -import lcsb.mapviewer.model.map.species.Ion; -import lcsb.mapviewer.model.map.species.SimpleMolecule; -import lcsb.mapviewer.model.map.species.Species; +import lcsb.mapviewer.model.map.species.*; public class ReconAnnotatorTest extends AnnotationTestFunctions { Logger logger = LogManager.getLogger(ReconAnnotatorTest.class); @@ -43,29 +35,19 @@ public class ReconAnnotatorTest extends AnnotationTestFunctions { @Test public void testAnnotateReaction() throws Exception { - try { - Reaction reaction = new Reaction(); - reaction.setAbbreviation("P5CRm"); - reconAnnotator.annotateElement(reaction); - assertTrue("No new annotations from recon db imported", reaction.getMiriamData().size() > 0); - assertEquals(0, getWarnings().size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Reaction reaction = new Reaction(); + reaction.setAbbreviation("P5CRm"); + reconAnnotator.annotateElement(reaction); + assertTrue("No new annotations from recon db imported", reaction.getMiriamData().size() > 0); + assertEquals(0, getWarnings().size()); } @Test public void testAnnotating_O16G2e_Reaction() throws Exception { - try { - Reaction reaction = new Reaction(); - reaction.setName("O16G2e"); - reconAnnotator.annotateElement(reaction); - assertEquals(0, getWarnings().size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Reaction reaction = new Reaction(); + reaction.setName("O16G2e"); + reconAnnotator.annotateElement(reaction); + assertEquals(0, getWarnings().size()); } @Test @@ -86,9 +68,6 @@ public class ReconAnnotatorTest extends AnnotationTestFunctions { reconAnnotator.annotateElement(ion); assertEquals(1, getWarnings().size()); assertTrue(getWarnings().get(0).getMessage().getFormattedMessage().contains("No recon annotations")); - } catch (Exception e) { - e.printStackTrace(); - throw e; } finally { reconAnnotator.setWebPageDownloader(downloader); reconAnnotator.setCache(originalCache); @@ -114,9 +93,6 @@ public class ReconAnnotatorTest extends AnnotationTestFunctions { reconAnnotator.annotateElement(ion); assertEquals(2, getWarnings().size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; } finally { reconAnnotator.setWebPageDownloader(downloader); reconAnnotator.setCache(originalCache); @@ -142,9 +118,6 @@ public class ReconAnnotatorTest extends AnnotationTestFunctions { reconAnnotator.annotateElement(reaction); assertEquals(2, getWarnings().size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; } finally { reconAnnotator.setWebPageDownloader(downloader); reconAnnotator.setCache(originalCache); @@ -153,99 +126,64 @@ public class ReconAnnotatorTest extends AnnotationTestFunctions { @Test public void testAnnotateUnknownElement() throws Exception { - try { - BioEntity obj = Mockito.mock(BioEntity.class); - when(obj.getName()).thenReturn("O16G2e"); - - ReconAnnotator tweakedReconAnnotator = Mockito.spy(reconAnnotator); - doReturn(true).when(tweakedReconAnnotator).isAnnotatable(any(BioEntity.class)); - - tweakedReconAnnotator.annotateElement(obj); - assertTrue(getWarnings().size() > 0); - assertTrue(getWarnings().get(0).getMessage().getFormattedMessage().contains("Unknown class type")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + BioEntity obj = Mockito.mock(BioEntity.class); + when(obj.getName()).thenReturn("O16G2e"); + + ReconAnnotator tweakedReconAnnotator = Mockito.spy(reconAnnotator); + doReturn(true).when(tweakedReconAnnotator).isAnnotatable(any(BioEntity.class)); + + tweakedReconAnnotator.annotateElement(obj); + assertTrue(getWarnings().size() > 0); + assertTrue(getWarnings().get(0).getMessage().getFormattedMessage().contains("Unknown class type")); } @Test public void testAnnotatingWithParentehesis() throws Exception { - try { - Reaction reaction = new Reaction(); - reaction.setName("gm2_hs[g]"); - reconAnnotator.annotateElement(reaction); - assertEquals(0, getWarnings().size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Reaction reaction = new Reaction(); + reaction.setName("gm2_hs[g]"); + reconAnnotator.annotateElement(reaction); + assertEquals(0, getWarnings().size()); } @Test public void testAnnotatingForOxygen() throws Exception { - try { - SimpleMolecule molecule = new SimpleMolecule("id"); - molecule.setName("o2"); - reconAnnotator.annotateElement(molecule); - assertTrue(molecule.getMiriamData().size() > 0); - assertEquals(0, getWarnings().size()); - assertEquals("O2", molecule.getFormula()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + SimpleMolecule molecule = new SimpleMolecule("id"); + molecule.setName("o2"); + reconAnnotator.annotateElement(molecule); + assertTrue(molecule.getMiriamData().size() > 0); + assertEquals(0, getWarnings().size()); + assertEquals("O2", molecule.getFormula()); } @Test public void testAnnotatingWithWhitespace() throws Exception { - try { - Reaction reaction = new Reaction(); - reaction.setName("NDPK4m "); - reconAnnotator.annotateElement(reaction); - assertEquals(0, getWarnings().size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Reaction reaction = new Reaction(); + reaction.setName("NDPK4m "); + reconAnnotator.annotateElement(reaction); + assertEquals(0, getWarnings().size()); } @Test public void testAnnotateElement() throws Exception { - try { - SimpleMolecule smallMolecule = new SimpleMolecule("id"); - smallMolecule.setAbbreviation("h2o"); - reconAnnotator.annotateElement(smallMolecule); - assertTrue("No new annotations from recon db imported", smallMolecule.getMiriamData().size() > 0); - assertEquals(0, getWarnings().size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + SimpleMolecule smallMolecule = new SimpleMolecule("id"); + smallMolecule.setAbbreviation("h2o"); + reconAnnotator.annotateElement(smallMolecule); + assertTrue("No new annotations from recon db imported", smallMolecule.getMiriamData().size() > 0); + assertEquals(0, getWarnings().size()); } @Test public void testAnnotateElement2() throws Exception { - try { - Species smallMolecule = new SimpleMolecule("id"); - smallMolecule.setAbbreviation("P5CRm"); - reconAnnotator.annotateElement(smallMolecule); - assertEquals(0, smallMolecule.getMiriamData().size()); - assertFalse(getWarnings().size() == 0); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Species smallMolecule = new SimpleMolecule("id"); + smallMolecule.setAbbreviation("P5CRm"); + reconAnnotator.annotateElement(smallMolecule); + assertEquals(0, smallMolecule.getMiriamData().size()); + assertFalse(getWarnings().size() == 0); } @Test public void testStatus() throws Exception { - try { - assertEquals(ExternalServiceStatusType.OK, reconAnnotator.getServiceStatus().getStatus()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(ExternalServiceStatusType.OK, reconAnnotator.getServiceStatus().getStatus()); } @Test @@ -257,9 +195,6 @@ public class ReconAnnotatorTest extends AnnotationTestFunctions { .thenThrow(new IOException()); reconAnnotator.setWebPageDownloader(mockDownloader); assertEquals(ExternalServiceStatusType.DOWN, reconAnnotator.getServiceStatus().getStatus()); - } catch (Exception e) { - e.printStackTrace(); - throw e; } finally { reconAnnotator.setWebPageDownloader(downloader); } @@ -274,9 +209,6 @@ public class ReconAnnotatorTest extends AnnotationTestFunctions { .thenReturn("{\"results\":[{}]}"); reconAnnotator.setWebPageDownloader(mockDownloader); assertEquals(ExternalServiceStatusType.CHANGED, reconAnnotator.getServiceStatus().getStatus()); - } catch (Exception e) { - e.printStackTrace(); - throw e; } finally { reconAnnotator.setWebPageDownloader(downloader); } @@ -291,9 +223,6 @@ public class ReconAnnotatorTest extends AnnotationTestFunctions { .thenReturn("{\"results\":[{\"keggId\":\"C00001\",\"xxx\":\"yyy\"}]}"); reconAnnotator.setWebPageDownloader(mockDownloader); assertEquals(ExternalServiceStatusType.CHANGED, reconAnnotator.getServiceStatus().getStatus()); - } catch (Exception e) { - e.printStackTrace(); - throw e; } finally { reconAnnotator.setWebPageDownloader(downloader); } diff --git a/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/StitchAnnotatorTest.java b/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/StitchAnnotatorTest.java index eceab162f8fe8547547c2099fd669489ee85a476..0ad50e1a8e013189a0949eb6018a8c8118875058 100644 --- a/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/StitchAnnotatorTest.java +++ b/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/StitchAnnotatorTest.java @@ -1,11 +1,8 @@ package lcsb.mapviewer.annotation.services.annotators; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.Assert.*; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.springframework.beans.factory.annotation.Autowired; import lcsb.mapviewer.annotation.AnnotationTestFunctions; @@ -29,71 +26,39 @@ public class StitchAnnotatorTest extends AnnotationTestFunctions { @Test public void testAnnotate() throws Exception { - try { + Species bioEntity = new SimpleMolecule("id"); + bioEntity.addMiriamData(new MiriamData(MiriamType.CHEBI, "CHEBI:35697")); - Species bioEntity = new SimpleMolecule("id"); - bioEntity.addMiriamData(new MiriamData(MiriamType.CHEBI, "CHEBI:35697")); + testedAnnotator.annotateElement(bioEntity); - testedAnnotator.annotateElement(bioEntity); + MiriamData mdStitch = null; - MiriamData mdStitch = null; - - for (MiriamData md : bioEntity.getMiriamData()) { - if (md.getDataType().equals(MiriamType.STITCH)) { - mdStitch = md; // there should be only one EC number for that TAIR<->UNIPROT record - } + for (MiriamData md : bioEntity.getMiriamData()) { + if (md.getDataType().equals(MiriamType.STITCH)) { + mdStitch = md; // there should be only one EC number for that TAIR<->UNIPROT record } - - assertTrue("No STITCH annotation extracted from STITCH annotator", mdStitch != null); - assertTrue("Wrong number of annotations extract from STITCH annotator", bioEntity.getMiriamData().size() == 2); - assertTrue("Invalid STITCH annotation extracted from STITCH annotator based on CHEBI ID", - mdStitch.getResource().equalsIgnoreCase("WBYWAXJHAXSJNI")); - - } catch (Exception e) { - e.printStackTrace(); - throw e; } - } - @Test - public void testExtractInchiMainLayer() throws Exception { - try { - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertTrue("No STITCH annotation extracted from STITCH annotator", mdStitch != null); + assertTrue("Wrong number of annotations extract from STITCH annotator", bioEntity.getMiriamData().size() == 2); + assertTrue("Invalid STITCH annotation extracted from STITCH annotator based on CHEBI ID", + mdStitch.getResource().equalsIgnoreCase("WBYWAXJHAXSJNI")); } @Test public void testAnnotateInvalidEmpty() throws Exception { - try { - Species bioEntity = new SimpleMolecule("id"); - testedAnnotator.annotateElement(bioEntity); - - assertEquals(0, bioEntity.getMiriamData().size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Species bioEntity = new SimpleMolecule("id"); + testedAnnotator.annotateElement(bioEntity); + + assertEquals(0, bioEntity.getMiriamData().size()); } @Test public void testAnnotateInvalidChebi() throws Exception { - try { - Species bioEntity = new SimpleMolecule("id"); - bioEntity.addMiriamData(new MiriamData(MiriamType.CHEBI, "bla")); - testedAnnotator.annotateElement(bioEntity); - - assertEquals(1, bioEntity.getMiriamData().size()); + Species bioEntity = new SimpleMolecule("id"); + bioEntity.addMiriamData(new MiriamData(MiriamType.CHEBI, "bla")); + testedAnnotator.annotateElement(bioEntity); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(1, bioEntity.getMiriamData().size()); } - - // All the service status tests are not necessary, since STTICH annotator - // internally calls ChEBI annotator which has it own set of tests - } diff --git a/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/StringAnnotatorTest.java b/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/StringAnnotatorTest.java index 97d154bc6ff4ae1b7eeacbce08dcd9ff9be9ac8d..e39e0d2732a5980e1e25b6a6b02b142baefc46bd 100644 --- a/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/StringAnnotatorTest.java +++ b/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/StringAnnotatorTest.java @@ -1,11 +1,8 @@ package lcsb.mapviewer.annotation.services.annotators; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.Assert.*; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.springframework.beans.factory.annotation.Autowired; import lcsb.mapviewer.annotation.AnnotationTestFunctions; @@ -29,104 +26,68 @@ public class StringAnnotatorTest extends AnnotationTestFunctions { @Test public void testAnnotateUniprot() throws Exception { - try { - - Species bioEntity = new GenericProtein("id"); - bioEntity.addMiriamData(new MiriamData(MiriamType.UNIPROT, "P53350")); + Species bioEntity = new GenericProtein("id"); + bioEntity.addMiriamData(new MiriamData(MiriamType.UNIPROT, "P53350")); - testedAnnotator.annotateElement(bioEntity); + testedAnnotator.annotateElement(bioEntity); - MiriamData mdString = null; + MiriamData mdString = null; - for (MiriamData md : bioEntity.getMiriamData()) { - if (md.getDataType().equals(MiriamType.STRING)) { - mdString = md; // there should be only one EC number for that TAIR<->UNIPROT record - } + for (MiriamData md : bioEntity.getMiriamData()) { + if (md.getDataType().equals(MiriamType.STRING)) { + mdString = md; // there should be only one EC number for that TAIR<->UNIPROT record } - - assertTrue("No STRING annotation extracted from STRING annotator", mdString != null); - assertTrue("Wrong number of annotations extract from STRING annotator", bioEntity.getMiriamData().size() == 2); - assertTrue("Invalid STRING annotation extracted from STRING annotator based on the UniProt annotation", - mdString.getResource().equalsIgnoreCase("P53350")); - - } catch (Exception e) { - e.printStackTrace(); - throw e; } + + assertTrue("No STRING annotation extracted from STRING annotator", mdString != null); + assertTrue("Wrong number of annotations extract from STRING annotator", bioEntity.getMiriamData().size() == 2); + assertTrue("Invalid STRING annotation extracted from STRING annotator based on the UniProt annotation", + mdString.getResource().equalsIgnoreCase("P53350")); } @Test -// @Ignore("TAIR DB restricts queries by IP") public void testAnnotateTair() throws Exception { - try { - - Species bioEntity = new GenericProtein("id"); - bioEntity.addMiriamData(new MiriamData(MiriamType.TAIR_LOCUS, "2200950")); + Species bioEntity = new GenericProtein("id"); + bioEntity.addMiriamData(new MiriamData(MiriamType.TAIR_LOCUS, "2200950")); - testedAnnotator.annotateElement(bioEntity); + testedAnnotator.annotateElement(bioEntity); - MiriamData mdString = null; + MiriamData mdString = null; - for (MiriamData md : bioEntity.getMiriamData()) { - if (md.getDataType().equals(MiriamType.STRING)) { - mdString = md; - } + for (MiriamData md : bioEntity.getMiriamData()) { + if (md.getDataType().equals(MiriamType.STRING)) { + mdString = md; } - - assertTrue("No STRING annotation extracted from STRING annotator", mdString != null); - assertTrue("Wrong number of annotations extract from STRING annotator", bioEntity.getMiriamData().size() == 2); - - } catch (Exception e) { - e.printStackTrace(); - throw e; } + + assertTrue("No STRING annotation extracted from STRING annotator", mdString != null); + assertTrue("Wrong number of annotations extract from STRING annotator", bioEntity.getMiriamData().size() == 2); } - - @Test -//@Ignore("TAIR DB restricts queries by IP") -public void testAnnotateTairOnlyFromHumanAnnotator() throws Exception { - try { + @Test + public void testAnnotateTairOnlyFromHumanAnnotator() throws Exception { Species bioEntity = new GenericProtein("id"); bioEntity.addMiriamData(new MiriamData(MiriamType.TAIR_LOCUS, "2200950", KeggAnnotator.class)); testedAnnotator.annotateElement(bioEntity); assertTrue(bioEntity.getMiriamData().size() == 1); - } catch (Exception e) { - e.printStackTrace(); - throw e; } -} @Test public void testAnnotateInvalidEmpty() throws Exception { - try { - Species bioEntity = new GenericProtein("id"); - testedAnnotator.annotateElement(bioEntity); - - assertEquals(0, bioEntity.getMiriamData().size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Species bioEntity = new GenericProtein("id"); + testedAnnotator.annotateElement(bioEntity); + + assertEquals(0, bioEntity.getMiriamData().size()); } @Test public void testAnnotateInvalidTair() throws Exception { - try { - Species bioEntity = new GenericProtein("id"); - bioEntity.addMiriamData(new MiriamData(MiriamType.TAIR_LOCUS, "bla")); - testedAnnotator.annotateElement(bioEntity); - - assertEquals(1, bioEntity.getMiriamData().size()); + Species bioEntity = new GenericProtein("id"); + bioEntity.addMiriamData(new MiriamData(MiriamType.TAIR_LOCUS, "bla")); + testedAnnotator.annotateElement(bioEntity); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(1, bioEntity.getMiriamData().size()); } - - // All the service status tests are not necessary, since STRING annotator - // internally calls TAIR annotator which has it own set of tests } diff --git a/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/TairAnnotatorTest.java b/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/TairAnnotatorTest.java index 2b7c4215ad9286ec6120347cf821bad978baaf25..d2d97a110356697900bf4644006b17eaeb8b645f 100644 --- a/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/TairAnnotatorTest.java +++ b/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/TairAnnotatorTest.java @@ -1,18 +1,12 @@ package lcsb.mapviewer.annotation.services.annotators; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.ArgumentMatchers.nullable; -import static org.mockito.Mockito.when; +import static org.junit.Assert.*; +import static org.mockito.ArgumentMatchers.*; +import static org.mockito.Mockito.*; import java.io.IOException; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.mockito.Mockito; import org.springframework.beans.factory.annotation.Autowired; @@ -39,156 +33,98 @@ public class TairAnnotatorTest extends AnnotationTestFunctions { } @Test - // @Ignore("TAIR DB restricts queries by IP") public void testAnnotate1() throws Exception { - try { - - Species protein = new GenericProtein("id"); - protein.setName("bla"); - protein.addMiriamData(new MiriamData(MiriamType.TAIR_LOCUS, "2200950")); //AT1G01030 + Species protein = new GenericProtein("id"); + protein.setName("bla"); + protein.addMiriamData(new MiriamData(MiriamType.TAIR_LOCUS, "2200950")); // AT1G01030 - tairAnnotator.annotateElement(protein); + tairAnnotator.annotateElement(protein); - MiriamData mdUniprot = null; + MiriamData mdUniprot = null; - for (MiriamData md : protein.getMiriamData()) { - if (md.getDataType().equals(MiriamType.UNIPROT)) { - mdUniprot = md; - } + for (MiriamData md : protein.getMiriamData()) { + if (md.getDataType().equals(MiriamType.UNIPROT)) { + mdUniprot = md; } - - assertTrue("No UNIPROT annotation extracted from TAIR annotator", mdUniprot != null); - assertTrue("Invalid UNIPROT annotation extracted from TAIR annotator", - mdUniprot.getResource().equalsIgnoreCase("Q9MAN1")); - - } catch (Exception e) { - e.printStackTrace(); - throw e; } + + assertTrue("No UNIPROT annotation extracted from TAIR annotator", mdUniprot != null); + assertTrue("Invalid UNIPROT annotation extracted from TAIR annotator", + mdUniprot.getResource().equalsIgnoreCase("Q9MAN1")); } @Test // @Ignore("TAIR DB restricts queries by IP") public void testAnnotateExistingUniprot() throws Exception { - try { + Species protein = new GenericProtein("id"); + protein.setName("bla"); + protein.addMiriamData(new MiriamData(MiriamType.TAIR_LOCUS, "2200427")); + protein.addMiriamData(new MiriamData(MiriamType.UNIPROT, "P32246")); // Human version of the protein - Species protein = new GenericProtein("id"); - protein.setName("bla"); - protein.addMiriamData(new MiriamData(MiriamType.TAIR_LOCUS, "2200427")); - protein.addMiriamData(new MiriamData(MiriamType.UNIPROT, "P32246")); // Human version of the protein + tairAnnotator.annotateElement(protein); - tairAnnotator.annotateElement(protein); + int cntUniProts = 0; - int cntUniProts = 0; - - for (MiriamData md : protein.getMiriamData()) { - if (md.getDataType().equals(MiriamType.UNIPROT)) { - cntUniProts++; - } + for (MiriamData md : protein.getMiriamData()) { + if (md.getDataType().equals(MiriamType.UNIPROT)) { + cntUniProts++; } - - assertTrue("No UNIPROT annotation extracted from TAIR annotator", cntUniProts > 1); - - } catch (Exception e) { - e.printStackTrace(); - throw e; } + + assertTrue("No UNIPROT annotation extracted from TAIR annotator", cntUniProts > 1); } @Test public void testAnnotateInvalidTair() throws Exception { - try { - Species protein = new GenericProtein("id"); - protein.setName("bla"); - protein.addMiriamData(new MiriamData(MiriamType.TAIR_LOCUS, "bla")); - tairAnnotator.annotateElement(protein); - - assertEquals(1, protein.getMiriamData().size()); + Species protein = new GenericProtein("id"); + protein.setName("bla"); + protein.addMiriamData(new MiriamData(MiriamType.TAIR_LOCUS, "bla")); + tairAnnotator.annotateElement(protein); - assertEquals(1, getWarnings().size()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(1, protein.getMiriamData().size()); + assertEquals(1, getWarnings().size()); } @Test public void testInvalidTairToUniprot() throws Exception { - try { - assertNull(tairAnnotator.tairToUniprot(null)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertNull(tairAnnotator.tairToUniprot(null)); } - @Test + @Test(expected = InvalidArgumentException.class) public void testInvalidTairToUniprot2() throws Exception { - try { - tairAnnotator.tairToUniprot(new MiriamData(MiriamType.WIKIPEDIA, "bla")); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + tairAnnotator.tairToUniprot(new MiriamData(MiriamType.WIKIPEDIA, "bla")); } @Test public void testAnnotateInvalid() throws Exception { - try { - Species protein = new GenericProtein("id"); - protein.setName("bla"); - tairAnnotator.annotateElement(protein); - - assertEquals(0, protein.getMiriamData().size()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Species protein = new GenericProtein("id"); + protein.setName("bla"); + tairAnnotator.annotateElement(protein); + assertEquals(0, protein.getMiriamData().size()); } @Test - // @Ignore("TAIR DB restricts queries by IP") public void testTairToUniprot() throws Exception { - try { - assertTrue(tairAnnotator.tairToUniprot(new MiriamData(MiriamType.TAIR_LOCUS, "2200950")) // TAIR locus AT1G01030 - .contains(new MiriamData(MiriamType.UNIPROT, "Q9MAN1"))); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertTrue(tairAnnotator.tairToUniprot(new MiriamData(MiriamType.TAIR_LOCUS, "2200950")) // TAIR locus AT1G01030 + .contains(new MiriamData(MiriamType.UNIPROT, "Q9MAN1"))); } - + @Test public void testTairToUniprotFromKEGG() throws Exception { - //TAIR Loci comming from annotators should be ignored by TAIR (only TAIR LOCI provided by the human annotator should be considered) - try { - Species protein = new GenericProtein("id"); - protein.setName("bla"); - protein.addMiriamData(new MiriamData(MiriamType.TAIR_LOCUS, "2200427", KeggAnnotator.class)); - tairAnnotator.annotateElement(protein); - assertTrue( protein.getMiriamData().size() == 1); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + // TAIR Loci comming from annotators should be ignored by TAIR (only TAIR LOCI + // provided by the human annotator should be considered) + Species protein = new GenericProtein("id"); + protein.setName("bla"); + protein.addMiriamData(new MiriamData(MiriamType.TAIR_LOCUS, "2200427", KeggAnnotator.class)); + tairAnnotator.annotateElement(protein); + assertTrue(protein.getMiriamData().size() == 1); } - @Test - // @Ignore("TAIR DB restricts queries by IP") public void testStatus() throws Exception { - try { - assertEquals(ExternalServiceStatusType.OK, tairAnnotator.getServiceStatus().getStatus()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(ExternalServiceStatusType.OK, tairAnnotator.getServiceStatus().getStatus()); } @Test @@ -200,38 +136,11 @@ public class TairAnnotatorTest extends AnnotationTestFunctions { .thenThrow(new IOException()); tairAnnotator.setWebPageDownloader(mockDownloader); assertEquals(ExternalServiceStatusType.DOWN, tairAnnotator.getServiceStatus().getStatus()); - } catch (Exception e) { - e.printStackTrace(); - throw e; } finally { tairAnnotator.setWebPageDownloader(downloader); } } - // @Test - // public void testAnnotateWithUniprotServerError() throws Exception { - // WebPageDownloader downloader = uniprotAnnotator.getWebPageDownloader(); - // GeneralCacheInterface cache = uniprotAnnotator.getCache(); - // uniprotAnnotator.setCache(new GeneralCacheWithExclusion(cache, 1)); - // try { - // WebPageDownloader mockDownloader = Mockito.mock(WebPageDownloader.class); - // when(mockDownloader.getFromNetwork(anyString(), anyString(), - // anyString())).thenThrow(new IOException()); - // uniprotAnnotator.setWebPageDownloader(mockDownloader); - // Species protein = new GenericProtein("id"); - // protein.addMiriamData(new MiriamData(MiriamType.UNIPROT, "P01308")); - // uniprotAnnotator.annotateElement(protein); - // fail("Exception expected"); - // } catch (AnnotatorException e) { - // } catch (Exception e) { - // e.printStackTrace(); - // throw e; - // } finally { - // uniprotAnnotator.setCache(cache); - // uniprotAnnotator.setWebPageDownloader(downloader); - // } - // } - @Test public void testSimulateChangedStatus() throws Exception { WebPageDownloader downloader = tairAnnotator.getWebPageDownloader(); @@ -241,9 +150,6 @@ public class TairAnnotatorTest extends AnnotationTestFunctions { .thenReturn("GN Name=ACSS2; Synonyms=ACAS2;"); tairAnnotator.setWebPageDownloader(mockDownloader); assertEquals(ExternalServiceStatusType.CHANGED, tairAnnotator.getServiceStatus().getStatus()); - } catch (Exception e) { - e.printStackTrace(); - throw e; } finally { tairAnnotator.setWebPageDownloader(downloader); } diff --git a/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/UniprotAnnotatorTest.java b/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/UniprotAnnotatorTest.java index aaa118d44c5e90d99be8d5e35b6290c479c14f2a..a85c04ecebbf603b6d5e36c6e3340b3b7973ee8b 100644 --- a/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/UniprotAnnotatorTest.java +++ b/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/UniprotAnnotatorTest.java @@ -1,21 +1,14 @@ package lcsb.mapviewer.annotation.services.annotators; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.ArgumentMatchers.nullable; -import static org.mockito.Mockito.when; +import static org.junit.Assert.*; +import static org.mockito.ArgumentMatchers.*; +import static org.mockito.Mockito.*; import java.io.IOException; import java.util.Collection; import org.apache.http.HttpStatus; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.mockito.Mockito; import org.springframework.beans.factory.annotation.Autowired; @@ -45,98 +38,62 @@ public class UniprotAnnotatorTest extends AnnotationTestFunctions { @Test public void testAnnotate1() throws Exception { - try { - - Species protein = new GenericProtein("id"); - protein.setName("P12345"); - uniprotAnnotator.annotateElement(protein); - - assertTrue(protein.getMiriamData().size() > 0); - - boolean entrez = false; - boolean hgnc = false; - boolean uniprot = false; - boolean ec = false; - - for (MiriamData md : protein.getMiriamData()) { - if (md.getDataType().equals(MiriamType.UNIPROT)) { - uniprot = true; - } else if (md.getDataType().equals(MiriamType.HGNC_SYMBOL)) { - hgnc = true; - } else if (md.getDataType().equals(MiriamType.ENTREZ)) { - entrez = true; - } else if (md.getDataType().equals(MiriamType.EC)) { - ec = true; - } + Species protein = new GenericProtein("id"); + protein.setName("P12345"); + uniprotAnnotator.annotateElement(protein); + + assertTrue(protein.getMiriamData().size() > 0); + + boolean entrez = false; + boolean hgnc = false; + boolean uniprot = false; + boolean ec = false; + + for (MiriamData md : protein.getMiriamData()) { + if (md.getDataType().equals(MiriamType.UNIPROT)) { + uniprot = true; + } else if (md.getDataType().equals(MiriamType.HGNC_SYMBOL)) { + hgnc = true; + } else if (md.getDataType().equals(MiriamType.ENTREZ)) { + entrez = true; + } else if (md.getDataType().equals(MiriamType.EC)) { + ec = true; } - assertTrue("No HGNC annotation extracted from uniprot annotator", hgnc); - assertTrue("No ENTREZ annotation extracted from uniprot annotator", entrez); - assertTrue("No UNIPROT annotation extracted from uniprot annotator", uniprot); - assertTrue("No UNIPROT annotation extracted from uniprot annotator", ec); - - } catch (Exception e) { - e.printStackTrace(); - throw e; } - + assertTrue("No HGNC annotation extracted from uniprot annotator", hgnc); + assertTrue("No ENTREZ annotation extracted from uniprot annotator", entrez); + assertTrue("No UNIPROT annotation extracted from uniprot annotator", uniprot); + assertTrue("No UNIPROT annotation extracted from uniprot annotator", ec); } @Test public void testEC1() throws Exception { - try { + Collection<MiriamData> mds = uniprotAnnotator.uniProtToEC(new MiriamData(MiriamType.UNIPROT, "P12345")); - Collection<MiriamData> mds = uniprotAnnotator.uniProtToEC(new MiriamData(MiriamType.UNIPROT, "P12345")); - - assertEquals(mds.size(), 2); - MiriamData md1 = new MiriamData(MiriamType.EC, "2.6.1.1"); - MiriamData md2 = new MiriamData(MiriamType.EC, "2.6.1.7"); - for (MiriamData md : mds) { - assertTrue(md.compareTo(md1) == 0 || md.compareTo(md2) == 0); - } - - } catch (Exception e) { - e.printStackTrace(); - throw e; + assertEquals(mds.size(), 2); + MiriamData md1 = new MiriamData(MiriamType.EC, "2.6.1.1"); + MiriamData md2 = new MiriamData(MiriamType.EC, "2.6.1.7"); + for (MiriamData md : mds) { + assertTrue(md.compareTo(md1) == 0 || md.compareTo(md2) == 0); } - } @Test public void testEC2() throws Exception { - try { - - Collection<MiriamData> mds = uniprotAnnotator.uniProtToEC(new MiriamData(MiriamType.UNIPROT, "P25405")); - - assertTrue("No EC miriam data extracted from uniprot annotator", mds.size() > 0); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Collection<MiriamData> mds = uniprotAnnotator.uniProtToEC(new MiriamData(MiriamType.UNIPROT, "P25405")); + assertTrue("No EC miriam data extracted from uniprot annotator", mds.size() > 0); } @Test public void testInvalidUniprotToECNull() throws Exception { - try { - assertNotNull(uniprotAnnotator.uniProtToEC(null)); - assertEquals(0,uniprotAnnotator.uniProtToEC(null).size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertNotNull(uniprotAnnotator.uniProtToEC(null)); + assertEquals(0, uniprotAnnotator.uniProtToEC(null).size()); } - @Test + @Test(expected = InvalidArgumentException.class) public void testInvalidUniprotToECWrongMd() throws Exception { - try { - uniprotAnnotator.uniProtToEC(new MiriamData(MiriamType.WIKIPEDIA, "bla")); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + uniprotAnnotator.uniProtToEC(new MiriamData(MiriamType.WIKIPEDIA, "bla")); } @Test @@ -152,70 +109,46 @@ public class UniprotAnnotatorTest extends AnnotationTestFunctions { uniprotAnnotator.annotateElement(protein); assertEquals(1, getWarnings().size()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; } finally { uniprotAnnotator.setWebPageDownloader(downloader); } - } @Test public void testInvalidUniprotToHgnc() throws Exception { - try { - assertNull(uniprotAnnotator.uniProtToHgnc(null)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertNull(uniprotAnnotator.uniProtToHgnc(null)); } - @Test + @Test(expected = InvalidArgumentException.class) public void testInvalidUniprotToHgnc2() throws Exception { - try { - uniprotAnnotator.uniProtToHgnc(new MiriamData(MiriamType.WIKIPEDIA, "bla")); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + uniprotAnnotator.uniProtToHgnc(new MiriamData(MiriamType.WIKIPEDIA, "bla")); } @Test public void testAnnotate2() throws Exception { - try { - Species protein = new GenericProtein("id"); - protein.setName("bla"); - protein.addMiriamData(new MiriamData(MiriamType.UNIPROT, "P01308")); - uniprotAnnotator.annotateElement(protein); - - assertTrue(protein.getMiriamData().size() > 1); - - boolean entrez = false; - boolean hgnc = false; - boolean uniprot = false; - - for (MiriamData md : protein.getMiriamData()) { - if (md.getDataType().equals(MiriamType.UNIPROT)) { - uniprot = true; - } else if (md.getDataType().equals(MiriamType.HGNC_SYMBOL)) { - hgnc = true; - } else if (md.getDataType().equals(MiriamType.ENTREZ)) { - entrez = true; - } + Species protein = new GenericProtein("id"); + protein.setName("bla"); + protein.addMiriamData(new MiriamData(MiriamType.UNIPROT, "P01308")); + uniprotAnnotator.annotateElement(protein); + + assertTrue(protein.getMiriamData().size() > 1); + + boolean entrez = false; + boolean hgnc = false; + boolean uniprot = false; + + for (MiriamData md : protein.getMiriamData()) { + if (md.getDataType().equals(MiriamType.UNIPROT)) { + uniprot = true; + } else if (md.getDataType().equals(MiriamType.HGNC_SYMBOL)) { + hgnc = true; + } else if (md.getDataType().equals(MiriamType.ENTREZ)) { + entrez = true; } - assertTrue("No HGNC annotation extracted from uniprot annotator", hgnc); - assertTrue("No ENTREZ annotation extracted from uniprot annotator", entrez); - assertTrue("No UNIPROT annotation extracted from uniprot annotator", uniprot); - - } catch (Exception e) { - e.printStackTrace(); - throw e; } - + assertTrue("No HGNC annotation extracted from uniprot annotator", hgnc); + assertTrue("No ENTREZ annotation extracted from uniprot annotator", entrez); + assertTrue("No UNIPROT annotation extracted from uniprot annotator", uniprot); } @Test @@ -235,10 +168,6 @@ public class UniprotAnnotatorTest extends AnnotationTestFunctions { assertEquals(1, protein.getMiriamData().size()); assertEquals(2, getWarnings().size()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; } finally { uniprotAnnotator.setWebPageDownloader(downloader); } @@ -258,10 +187,6 @@ public class UniprotAnnotatorTest extends AnnotationTestFunctions { uniprotAnnotator.annotateElement(protein); assertEquals(0, protein.getMiriamData().size()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; } finally { uniprotAnnotator.setWebPageDownloader(downloader); } @@ -270,47 +195,25 @@ public class UniprotAnnotatorTest extends AnnotationTestFunctions { @Test public void testUniprotToHgnc() throws Exception { - try { - assertEquals(new MiriamData(MiriamType.HGNC_SYMBOL, "KDR"), - uniprotAnnotator.uniProtToHgnc(new MiriamData(MiriamType.UNIPROT, "P35968"))); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(new MiriamData(MiriamType.HGNC_SYMBOL, "KDR"), + uniprotAnnotator.uniProtToHgnc(new MiriamData(MiriamType.UNIPROT, "P35968"))); } - + @Test public void testUniprotTairLocusToId() throws Exception { - try { - assertEquals(new MiriamData(MiriamType.TAIR_LOCUS, "2201786"), - uniprotAnnotator.uniprotTairLocusNameToId("AT1G08510") ); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(new MiriamData(MiriamType.TAIR_LOCUS, "2201786"), + uniprotAnnotator.uniprotTairLocusNameToId("AT1G08510")); } - + @Test public void testUniprotWrongTairLocusToId() throws Exception { - try { - assertEquals(new MiriamData(), - uniprotAnnotator.uniprotTairLocusNameToId("bla")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(new MiriamData(), + uniprotAnnotator.uniprotTairLocusNameToId("bla")); } - - @Test public void testStatus() throws Exception { - try { - assertEquals(ExternalServiceStatusType.OK, uniprotAnnotator.getServiceStatus().getStatus()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(ExternalServiceStatusType.OK, uniprotAnnotator.getServiceStatus().getStatus()); } @Test @@ -322,15 +225,12 @@ public class UniprotAnnotatorTest extends AnnotationTestFunctions { .thenThrow(new IOException()); uniprotAnnotator.setWebPageDownloader(mockDownloader); assertEquals(ExternalServiceStatusType.DOWN, uniprotAnnotator.getServiceStatus().getStatus()); - } catch (Exception e) { - e.printStackTrace(); - throw e; } finally { uniprotAnnotator.setWebPageDownloader(downloader); } } - @Test + @Test(expected = AnnotatorException.class) public void testAnnotateWithUniprotServerError() throws Exception { WebPageDownloader downloader = uniprotAnnotator.getWebPageDownloader(); GeneralCacheInterface cache = uniprotAnnotator.getCache(); @@ -343,11 +243,6 @@ public class UniprotAnnotatorTest extends AnnotationTestFunctions { Species protein = new GenericProtein("id"); protein.addMiriamData(new MiriamData(MiriamType.UNIPROT, "P01308")); uniprotAnnotator.annotateElement(protein); - fail("Exception expected"); - } catch (AnnotatorException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; } finally { uniprotAnnotator.setCache(cache); uniprotAnnotator.setWebPageDownloader(downloader); @@ -362,9 +257,6 @@ public class UniprotAnnotatorTest extends AnnotationTestFunctions { when(mockDownloader.getFromNetwork(anyString(), anyString(), nullable(String.class))).thenReturn(""); uniprotAnnotator.setWebPageDownloader(mockDownloader); assertEquals(ExternalServiceStatusType.DOWN, uniprotAnnotator.getServiceStatus().getStatus()); - } catch (Exception e) { - e.printStackTrace(); - throw e; } finally { uniprotAnnotator.setWebPageDownloader(downloader); } @@ -379,9 +271,6 @@ public class UniprotAnnotatorTest extends AnnotationTestFunctions { .thenReturn("GN Name=ACSS2; Synonyms=ACAS2;"); uniprotAnnotator.setWebPageDownloader(mockDownloader); assertEquals(ExternalServiceStatusType.CHANGED, uniprotAnnotator.getServiceStatus().getStatus()); - } catch (Exception e) { - e.printStackTrace(); - throw e; } finally { uniprotAnnotator.setWebPageDownloader(downloader); } diff --git a/annotation/src/test/java/lcsb/mapviewer/annotation/services/genome/UcscReferenceGenomeConnectorTest.java b/annotation/src/test/java/lcsb/mapviewer/annotation/services/genome/UcscReferenceGenomeConnectorTest.java index 9fa49bc988559752828a7d38351704ac5abf1835..6d5a6e730b0cddd6c1404c7b32aa7cd421a9674a 100644 --- a/annotation/src/test/java/lcsb/mapviewer/annotation/services/genome/UcscReferenceGenomeConnectorTest.java +++ b/annotation/src/test/java/lcsb/mapviewer/annotation/services/genome/UcscReferenceGenomeConnectorTest.java @@ -1,41 +1,25 @@ package lcsb.mapviewer.annotation.services.genome; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyBoolean; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.ArgumentMatchers.nullable; -import static org.mockito.Mockito.when; +import static org.junit.Assert.*; +import static org.mockito.ArgumentMatchers.*; +import static org.mockito.Mockito.*; import java.io.IOException; import java.net.URISyntaxException; import java.util.List; -import java.util.concurrent.Callable; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Future; - -import org.apache.commons.net.ftp.FTPClient; -import org.apache.commons.net.ftp.FTPFile; -import org.apache.commons.net.ftp.FTPReply; -import org.apache.logging.log4j.*; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import java.util.concurrent.*; + +import org.apache.commons.net.ftp.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.junit.*; import org.mockito.Mockito; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import org.springframework.beans.factory.annotation.Autowired; import lcsb.mapviewer.annotation.AnnotationTestFunctions; -import lcsb.mapviewer.annotation.cache.BigFileCache; -import lcsb.mapviewer.annotation.cache.GeneralCacheInterface; -import lcsb.mapviewer.annotation.cache.SourceNotAvailable; -import lcsb.mapviewer.annotation.cache.WebPageDownloader; +import lcsb.mapviewer.annotation.cache.*; import lcsb.mapviewer.annotation.services.TaxonomyBackend; import lcsb.mapviewer.annotation.services.TaxonomySearchException; import lcsb.mapviewer.common.IProgressUpdater; @@ -43,9 +27,7 @@ import lcsb.mapviewer.common.exception.InvalidArgumentException; import lcsb.mapviewer.common.exception.InvalidStateException; import lcsb.mapviewer.model.map.MiriamData; import lcsb.mapviewer.model.map.MiriamType; -import lcsb.mapviewer.model.map.layout.ReferenceGenome; -import lcsb.mapviewer.model.map.layout.ReferenceGenomeGeneMapping; -import lcsb.mapviewer.model.map.layout.ReferenceGenomeType; +import lcsb.mapviewer.model.map.layout.*; import lcsb.mapviewer.persist.dao.map.layout.ReferenceGenomeDao; public class UcscReferenceGenomeConnectorTest extends AnnotationTestFunctions { @@ -68,27 +50,17 @@ public class UcscReferenceGenomeConnectorTest extends AnnotationTestFunctions { @Test public void testRefreshCacheQuery() throws Exception { - try { - assertNotNull(connector.refreshCacheQuery("http://google.pl/")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertNotNull(connector.refreshCacheQuery("http://google.pl/")); } @Test public void testGetAvailableGenomeVersion() throws Exception { MiriamData human = new MiriamData(MiriamType.TAXONOMY, "9606"); - try { - List<String> list = connector.getAvailableGenomeVersion(human); - assertTrue(list.size() >= 17); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + List<String> list = connector.getAvailableGenomeVersion(human); + assertTrue(list.size() >= 17); } - @Test + @Test(expected = ReferenceGenomeConnectorException.class) public void testGetAvailableGenomeVersionWhenProblemWithTaxonomyServer() throws Exception { MiriamData human = new MiriamData(MiriamType.TAXONOMY, "9606"); TaxonomyBackend taxonomyBackend = connector.getTaxonomyBackend(); @@ -99,11 +71,6 @@ public class UcscReferenceGenomeConnectorTest extends AnnotationTestFunctions { connector.setTaxonomyBackend(taxonomyMock); connector.getAvailableGenomeVersion(human); - fail("Exception expected"); - } catch (ReferenceGenomeConnectorException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; } finally { connector.setTaxonomyBackend(taxonomyBackend); } @@ -112,33 +79,22 @@ public class UcscReferenceGenomeConnectorTest extends AnnotationTestFunctions { @Test public void testGetAvailableGenomeVersionForInvalidTaxonomy() throws Exception { MiriamData unknown = new MiriamData(MiriamType.TAXONOMY, "10101010101"); - try { - List<String> list = connector.getAvailableGenomeVersion(unknown); - assertEquals(0, list.size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + List<String> list = connector.getAvailableGenomeVersion(unknown); + assertEquals(0, list.size()); } @Test public void testGetAvailableOrganisms() throws Exception { - try { - MiriamData human = new MiriamData(MiriamType.TAXONOMY, "9606"); - MiriamData chicken = new MiriamData(MiriamType.TAXONOMY, "9031"); - List<MiriamData> list = connector.getAvailableOrganisms(); - assertTrue("At least 40 different organism were expected but found: " + list.size(), list.size() > 40); - - assertTrue(list.contains(human)); - assertTrue(list.contains(chicken)); + MiriamData human = new MiriamData(MiriamType.TAXONOMY, "9606"); + MiriamData chicken = new MiriamData(MiriamType.TAXONOMY, "9031"); + List<MiriamData> list = connector.getAvailableOrganisms(); + assertTrue("At least 40 different organism were expected but found: " + list.size(), list.size() > 40); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertTrue(list.contains(human)); + assertTrue(list.contains(chicken)); } - @Test + @Test(expected = ReferenceGenomeConnectorException.class) public void testGetAvailableOrganismsWhenUcscWebpageDown() throws Exception { WebPageDownloader downloader = connector.getWebPageDownloader(); GeneralCacheInterface originalCache = connector.getCache(); @@ -151,12 +107,6 @@ public class UcscReferenceGenomeConnectorTest extends AnnotationTestFunctions { .thenThrow(new IOException()); connector.setWebPageDownloader(mockDownloader); connector.getAvailableOrganisms(); - fail("Exception expected"); - } catch (ReferenceGenomeConnectorException e) { - assertTrue(e.getMessage().contains("Problem with accessing UCSC database")); - } catch (Exception e) { - e.printStackTrace(); - throw e; } finally { connector.setWebPageDownloader(downloader); connector.setCache(originalCache); @@ -167,95 +117,88 @@ public class UcscReferenceGenomeConnectorTest extends AnnotationTestFunctions { public void testDownloadGenomeVersion() throws Exception { MiriamData yeast = new MiriamData(MiriamType.TAXONOMY, "1570291"); String version = "eboVir3"; + dbUtils.createSessionForCurrentThread(); + List<String> list = connector.getDownloadedGenomeVersions(yeast); + if (list.contains(version)) { + connector.removeGenomeVersion(yeast, version); + } + dbUtils.closeSessionForCurrentThread(); + list = connector.getDownloadedGenomeVersions(yeast); - try { - dbUtils.createSessionForCurrentThread(); - List<String> list = connector.getDownloadedGenomeVersions(yeast); - if (list.contains(version)) { - connector.removeGenomeVersion(yeast, version); + assertFalse(list.contains(version)); + + connector.downloadGenomeVersion(yeast, version, new IProgressUpdater() { + @Override + public void setProgress(double progress) { } - dbUtils.closeSessionForCurrentThread(); - list = connector.getDownloadedGenomeVersions(yeast); + }, false); - assertFalse(list.contains(version)); + list = connector.getDownloadedGenomeVersions(yeast); + assertTrue(list.contains(version)); - connector.downloadGenomeVersion(yeast, version, new IProgressUpdater() { + List<ReferenceGenome> genomes = referenceGenomeDao.getByType(ReferenceGenomeType.UCSC); + ReferenceGenome genome = null; + for (ReferenceGenome referenceGenome : genomes) { + if (referenceGenome.getVersion().equals(version)) { + genome = referenceGenome; + } + } + assertNotNull(genome); + connector.downloadGeneMappingGenomeVersion(genome, "test", null, false, + "http://www.biodalliance.org/datasets/flyThickets.bb"); + + dbUtils.createSessionForCurrentThread(); + genomes = referenceGenomeDao.getByType(ReferenceGenomeType.UCSC); + genome = null; + for (ReferenceGenome referenceGenome : genomes) { + if (referenceGenome.getVersion().equals(version)) { + genome = referenceGenome; + } + } + assertNotNull(genome); + assertEquals(1, genome.getGeneMapping().size()); + dbUtils.closeSessionForCurrentThread(); + + try { + // try to download the same thing for the second time + connector.downloadGeneMappingGenomeVersion(genome, "test", new IProgressUpdater() { @Override public void setProgress(double progress) { } - }, false); - - list = connector.getDownloadedGenomeVersions(yeast); - assertTrue(list.contains(version)); - - List<ReferenceGenome> genomes = referenceGenomeDao.getByType(ReferenceGenomeType.UCSC); - ReferenceGenome genome = null; - for (ReferenceGenome referenceGenome : genomes) { - if (referenceGenome.getVersion().equals(version)) { - genome = referenceGenome; - } - } - assertNotNull(genome); - connector.downloadGeneMappingGenomeVersion(genome, "test", null, false, - "http://www.biodalliance.org/datasets/flyThickets.bb"); + }, false, "http://www.biodalliance.org/datasets/flyThickets.bb"); + fail("Exception expected"); + } catch (ReferenceGenomeConnectorException e) { + assertTrue(e.getMessage().contains("already exists")); + } - dbUtils.createSessionForCurrentThread(); - genomes = referenceGenomeDao.getByType(ReferenceGenomeType.UCSC); - genome = null; - for (ReferenceGenome referenceGenome : genomes) { - if (referenceGenome.getVersion().equals(version)) { - genome = referenceGenome; + try { + // try to download something that is not big bed + connector.downloadGeneMappingGenomeVersion(genome, "test2", new IProgressUpdater() { + @Override + public void setProgress(double progress) { } - } - assertNotNull(genome); - assertEquals(1, genome.getGeneMapping().size()); - dbUtils.closeSessionForCurrentThread(); - - try { - // try to download the same thing for the second time - connector.downloadGeneMappingGenomeVersion(genome, "test", new IProgressUpdater() { - @Override - public void setProgress(double progress) { - } - }, false, "http://www.biodalliance.org/datasets/flyThickets.bb"); - fail("Exception expected"); - } catch (ReferenceGenomeConnectorException e) { - assertTrue(e.getMessage().contains("already exists")); - } - - try { - // try to download something that is not big bed - connector.downloadGeneMappingGenomeVersion(genome, "test2", new IProgressUpdater() { - @Override - public void setProgress(double progress) { - } - }, false, "http://www.biodalliance.org/datasets/flyThickets.txt"); - fail("Exception expected"); - } catch (ReferenceGenomeConnectorException e) { - assertTrue(e.getMessage().contains("Only big bed format files are supported")); - } - - // connector.removeGeneMapping(genome.getGeneMapping().get(0)); + }, false, "http://www.biodalliance.org/datasets/flyThickets.txt"); + fail("Exception expected"); + } catch (ReferenceGenomeConnectorException e) { + assertTrue(e.getMessage().contains("Only big bed format files are supported")); + } - int warningCount = getWarnings().size(); + // connector.removeGeneMapping(genome.getGeneMapping().get(0)); - // try to remove invalid mapping - connector.removeGeneMapping(new ReferenceGenomeGeneMapping()); + int warningCount = getWarnings().size(); - assertEquals(warningCount + 1, getWarnings().size()); + // try to remove invalid mapping + connector.removeGeneMapping(new ReferenceGenomeGeneMapping()); - dbUtils.createSessionForCurrentThread(); - connector.removeGenomeVersion(yeast, version); - dbUtils.closeSessionForCurrentThread(); + assertEquals(warningCount + 1, getWarnings().size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + dbUtils.createSessionForCurrentThread(); + connector.removeGenomeVersion(yeast, version); + dbUtils.closeSessionForCurrentThread(); } @SuppressWarnings("unchecked") - @Test + @Test(expected = InvalidStateException.class) public void testDownloadGenomeVersionWhenInternalUrlIsInvalid() throws Exception { MiriamData yeast = new MiriamData(MiriamType.TAXONOMY, "1570291"); String version = "eboVir3"; @@ -273,12 +216,6 @@ public class UcscReferenceGenomeConnectorTest extends AnnotationTestFunctions { public void setProgress(double progress) { } }, false); - fail("Exception expected"); - - } catch (InvalidStateException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; } finally { connector.setSyncExecutorService(originalExecutorService); } @@ -387,10 +324,6 @@ public class UcscReferenceGenomeConnectorTest extends AnnotationTestFunctions { assertEquals(warningCount + 1, getWarnings().size()); connector.removeGenomeVersion(yeast, version); - - } catch (Exception e) { - e.printStackTrace(); - throw e; } finally { connector.setBigFileCache(bigFileCache); } @@ -495,10 +428,6 @@ public class UcscReferenceGenomeConnectorTest extends AnnotationTestFunctions { connector.removeGeneMapping(genome.getGeneMapping().get(1)); connector.removeGeneMapping(genome.getGeneMapping().get(0)); connector.removeGenomeVersion(yeast, version); - - } catch (Exception e) { - e.printStackTrace(); - throw e; } finally { connector.setBigFileCache(bigFileCache); } @@ -597,10 +526,6 @@ public class UcscReferenceGenomeConnectorTest extends AnnotationTestFunctions { connector.removeGeneMapping(genome.getGeneMapping().get(1)); connector.removeGeneMapping(genome.getGeneMapping().get(0)); connector.removeGenomeVersion(yeast, version); - - } catch (Exception e) { - e.printStackTrace(); - throw e; } finally { connector.setBigFileCache(bigFileCache); } @@ -610,154 +535,89 @@ public class UcscReferenceGenomeConnectorTest extends AnnotationTestFunctions { public void testGetGenomeVersionFile() throws Exception { MiriamData yeast = new MiriamData(MiriamType.TAXONOMY, "4932"); String version = "sacCer3"; - try { - String url = connector.getGenomeVersionFile(yeast, version); - assertNotNull(url); - url.contains("sacCer3.2bit"); - url.contains("ftp"); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String url = connector.getGenomeVersionFile(yeast, version); + assertNotNull(url); + url.contains("sacCer3.2bit"); + url.contains("ftp"); } - @Test - public void testGetUnknownGenomeVersionFile() { + @Test(expected = FileNotAvailableException.class) + public void testGetUnknownGenomeVersionFile() throws FileNotAvailableException { MiriamData human = new MiriamData(MiriamType.TAXONOMY, "9606"); String version = "hg8"; - try { - connector.getGenomeVersionFile(human, version); - fail("Exception expected"); - } catch (FileNotAvailableException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + connector.getGenomeVersionFile(human, version); } - @Test + @Test(expected = InvalidArgumentException.class) public void testRefreshInvalid() throws Exception { - try { - connector.refreshCacheQuery("invalid query"); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - assertTrue(e.getMessage().contains("Don't know what to do")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + connector.refreshCacheQuery("invalid query"); } - @Test + @Test(expected = InvalidArgumentException.class) public void testRefreshInvalid2() throws Exception { - try { - connector.refreshCacheQuery(new Object()); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - assertTrue(e.getMessage().contains("Don't know what to do")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + connector.refreshCacheQuery(new Object()); } @Test public void testRefresh() throws Exception { - try { - MiriamData yeast = new MiriamData(MiriamType.TAXONOMY, "4932"); - String version = "sacCer3"; - - String query = UcscReferenceGenomeConnector.FILENAME_BY_ORGANISM_VERSION_PREFIX + yeast.getResource() + "\n" - + version; - Object res = connector.refreshCacheQuery(query); - assertNotNull(res); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + MiriamData yeast = new MiriamData(MiriamType.TAXONOMY, "4932"); + String version = "sacCer3"; + + String query = UcscReferenceGenomeConnector.FILENAME_BY_ORGANISM_VERSION_PREFIX + yeast.getResource() + "\n" + + version; + Object res = connector.refreshCacheQuery(query); + assertNotNull(res); } - @Test + @Test(expected = SourceNotAvailable.class) public void testRefreshUnknownFile() throws Exception { - try { - MiriamData yeast = new MiriamData(MiriamType.TAXONOMY, "4932"); - String version = "unkVer"; - - String query = UcscReferenceGenomeConnector.FILENAME_BY_ORGANISM_VERSION_PREFIX + yeast.getResource() + "\n" - + version; - connector.refreshCacheQuery(query); - } catch (SourceNotAvailable e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + MiriamData yeast = new MiriamData(MiriamType.TAXONOMY, "4932"); + String version = "unkVer"; + + String query = UcscReferenceGenomeConnector.FILENAME_BY_ORGANISM_VERSION_PREFIX + yeast.getResource() + "\n" + + version; + connector.refreshCacheQuery(query); } @Test public void testGetters() throws Exception { - try { - UcscReferenceGenomeConnector connectorUnderTest = new UcscReferenceGenomeConnector(null); - connectorUnderTest.setBigFileCache(connector.getBigFileCache()); - connectorUnderTest.setDbUtils(connector.getDbUtils()); - connectorUnderTest.setReferenceGenomeDao(connector.getReferenceGenomeDao()); - connectorUnderTest.setReferenceGenomeGeneMappingDao(connector.getReferenceGenomeGeneMappingDao()); - - assertEquals(connector.getBigFileCache(), connectorUnderTest.getBigFileCache()); - assertEquals(connector.getDbUtils(), connectorUnderTest.getDbUtils()); - assertEquals(connector.getReferenceGenomeDao(), connectorUnderTest.getReferenceGenomeDao()); - assertEquals(connector.getReferenceGenomeGeneMappingDao(), connectorUnderTest.getReferenceGenomeGeneMappingDao()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + UcscReferenceGenomeConnector connectorUnderTest = new UcscReferenceGenomeConnector(null); + connectorUnderTest.setBigFileCache(connector.getBigFileCache()); + connectorUnderTest.setDbUtils(connector.getDbUtils()); + connectorUnderTest.setReferenceGenomeDao(connector.getReferenceGenomeDao()); + connectorUnderTest.setReferenceGenomeGeneMappingDao(connector.getReferenceGenomeGeneMappingDao()); + + assertEquals(connector.getBigFileCache(), connectorUnderTest.getBigFileCache()); + assertEquals(connector.getDbUtils(), connectorUnderTest.getDbUtils()); + assertEquals(connector.getReferenceGenomeDao(), connectorUnderTest.getReferenceGenomeDao()); + assertEquals(connector.getReferenceGenomeGeneMappingDao(), connectorUnderTest.getReferenceGenomeGeneMappingDao()); } @Test public void testGenomeVersionExtractorForInvalidGenome() throws Exception { - try { - int version = connector.extractInt(""); - assertEquals(0, version); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + int version = connector.extractInt(""); + assertEquals(0, version); } @Test public void testGenomeVersionExtractorForInvalidGenome2() throws Exception { - try { - int version = connector.extractInt("x"); - assertEquals(0, version); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + int version = connector.extractInt("x"); + assertEquals(0, version); } @Test public void testGenomeVersionExtractorForValid() throws Exception { - try { - int version = connector.extractInt("x1"); - assertEquals(1, version); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + int version = connector.extractInt("x1"); + assertEquals(1, version); } @Test public void testGenomeVersionExtractorForValid2() throws Exception { - try { - int version = connector.extractInt("xy12z"); - assertEquals(12, version); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + int version = connector.extractInt("xy12z"); + assertEquals(12, version); } - @Test + @Test(expected = SourceNotAvailable.class) public void testRefreshCacheQueryNotAvailable() throws Exception { WebPageDownloader downloader = connector.getWebPageDownloader(); GeneralCacheInterface originalCache = connector.getCache(); @@ -769,18 +629,13 @@ public class UcscReferenceGenomeConnectorTest extends AnnotationTestFunctions { .thenThrow(new IOException()); connector.setWebPageDownloader(mockDownloader); connector.refreshCacheQuery("http://google.pl/"); - fail("Exception expected"); - } catch (SourceNotAvailable e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; } finally { connector.setWebPageDownloader(downloader); connector.setCache(originalCache); } } - @Test + @Test(expected = FileNotAvailableException.class) public void testRefreshCacheQueryWhenFtpConnectionFails() throws Exception { MiriamData yeast = new MiriamData(MiriamType.TAXONOMY, "4932"); String version = "sacCer3"; @@ -794,19 +649,11 @@ public class UcscReferenceGenomeConnectorTest extends AnnotationTestFunctions { } }; - try { - // exclude first cached value - connectorUnderTest.getGenomeVersionFile(yeast, version); - fail("Exception expected"); - } catch (FileNotAvailableException e) { - assertTrue(e.getMessage().contains("FTP server refused connection")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + // exclude first cached value + connectorUnderTest.getGenomeVersionFile(yeast, version); } - @Test + @Test(expected = FileNotAvailableException.class) public void testGetGenomeVersionFileWhenFtpConnectionFails2() throws Exception { MiriamData yeast = new MiriamData(MiriamType.TAXONOMY, "4932"); String version = "sacCer3"; @@ -824,19 +671,11 @@ public class UcscReferenceGenomeConnectorTest extends AnnotationTestFunctions { return mockClient; } }; - - try { - // exclude first cached value - connectorUnderTest.getGenomeVersionFile(yeast, version); - fail("Exception expected"); - } catch (FileNotAvailableException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + // exclude first cached value + connectorUnderTest.getGenomeVersionFile(yeast, version); } - @Test + @Test(expected = FileNotAvailableException.class) public void testGetGenomeVersionFileWhenFtpConnectionFails() throws Exception { MiriamData yeast = new MiriamData(MiriamType.TAXONOMY, "4932"); String version = "sacCer3"; @@ -854,19 +693,11 @@ public class UcscReferenceGenomeConnectorTest extends AnnotationTestFunctions { return mockClient; } }; - - try { - // exclude first cached value - connectorUnderTest.getGenomeVersionFile(yeast, version); - fail("Exception expected"); - } catch (FileNotAvailableException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + // exclude first cached value + connectorUnderTest.getGenomeVersionFile(yeast, version); } - @Test + @Test(expected = FileNotAvailableException.class) public void testGetGenomeVersionFileWhenFtpConnectionFails3() throws Exception { MiriamData yeast = new MiriamData(MiriamType.TAXONOMY, "4932"); String version = "sacCer3"; @@ -886,18 +717,11 @@ public class UcscReferenceGenomeConnectorTest extends AnnotationTestFunctions { } }; - try { - // exclude first cached value - connectorUnderTest.getGenomeVersionFile(yeast, version); - fail("Exception expected"); - } catch (FileNotAvailableException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + // exclude first cached value + connectorUnderTest.getGenomeVersionFile(yeast, version); } - @Test + @Test(expected = FileNotAvailableException.class) public void testGetGenomeVersionFileWhenFtpDisconnectConnectionFails() throws Exception { MiriamData yeast = new MiriamData(MiriamType.TAXONOMY, "4932"); String version = "sacCer3"; @@ -918,16 +742,8 @@ public class UcscReferenceGenomeConnectorTest extends AnnotationTestFunctions { } }; - try { - // exclude first cached value - connectorUnderTest.getGenomeVersionFile(yeast, version); - fail("Exception expected"); - } catch (FileNotAvailableException e) { - assertTrue(e.getMessage().contains("Problem with ftp connection")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + // exclude first cached value + connectorUnderTest.getGenomeVersionFile(yeast, version); } @Test @@ -955,15 +771,10 @@ public class UcscReferenceGenomeConnectorTest extends AnnotationTestFunctions { } }; - try { - // exclude first cached value - String url = connectorUnderTest.getGenomeVersionFile(yeast, version); - assertEquals(1, getWarnings().size()); - assertTrue(url.endsWith("1.2bit")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + // exclude first cached value + String url = connectorUnderTest.getGenomeVersionFile(yeast, version); + assertEquals(1, getWarnings().size()); + assertTrue(url.endsWith("1.2bit")); } private void waitForDownload() throws InterruptedException { diff --git a/commons/pom.xml b/commons/pom.xml index f79c5aa52845f4e9852ee19ddbb8d32c6114e3c6..c006871d911bb43669340e1924054e2b2aabd53b 100644 --- a/commons/pom.xml +++ b/commons/pom.xml @@ -58,7 +58,6 @@ <groupId>junit</groupId> <artifactId>junit</artifactId> <version>${junit.version}</version> - <scope>test</scope> </dependency> </dependencies> diff --git a/commons/src/main/java/lcsb/mapviewer/common/UnitTestFailedWatcher.java b/commons/src/main/java/lcsb/mapviewer/common/UnitTestFailedWatcher.java new file mode 100644 index 0000000000000000000000000000000000000000..cf8337839412ceb899d0adb94ed415855aaa1b53 --- /dev/null +++ b/commons/src/main/java/lcsb/mapviewer/common/UnitTestFailedWatcher.java @@ -0,0 +1,11 @@ +package lcsb.mapviewer.common; + +import org.junit.rules.TestWatcher; +import org.junit.runner.Description; + +public class UnitTestFailedWatcher extends TestWatcher { + @Override + protected void failed(Throwable e, Description description) { + e.printStackTrace(); + } +} diff --git a/commons/src/test/java/lcsb/mapviewer/common/CommonTestFunctions.java b/commons/src/test/java/lcsb/mapviewer/common/CommonTestFunctions.java index b13706a0c64b95160f369e2ad7fde2f858202ec7..d043c3030892150392a67ca8a30731defc071612 100644 --- a/commons/src/test/java/lcsb/mapviewer/common/CommonTestFunctions.java +++ b/commons/src/test/java/lcsb/mapviewer/common/CommonTestFunctions.java @@ -3,11 +3,13 @@ package lcsb.mapviewer.common; import java.util.List; import org.apache.logging.log4j.core.LogEvent; -import org.junit.After; -import org.junit.Before; +import org.junit.*; public class CommonTestFunctions { + @Rule + public UnitTestFailedWatcher ruleExample = new UnitTestFailedWatcher(); + private MinervaLoggerAppender appender; @Before diff --git a/commons/src/test/java/lcsb/mapviewer/common/GlobalLoggerAppenderTest.java b/commons/src/test/java/lcsb/mapviewer/common/GlobalLoggerAppenderTest.java index bfcb56d53d0b2c4082b645797bebcbec1d823659..d96a0f688379fc1f57f451d88ecde206d04eea74 100644 --- a/commons/src/test/java/lcsb/mapviewer/common/GlobalLoggerAppenderTest.java +++ b/commons/src/test/java/lcsb/mapviewer/common/GlobalLoggerAppenderTest.java @@ -1,16 +1,12 @@ package lcsb.mapviewer.common; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.*; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; -public class GlobalLoggerAppenderTest { +public class GlobalLoggerAppenderTest extends CommonTestFunctions { Logger logger = LogManager.getLogger(GlobalLoggerAppenderTest.class); @AfterClass @@ -27,40 +23,30 @@ public class GlobalLoggerAppenderTest { @Test public void testLogCatching() { - try { - MinervaLoggerAppender appender = MinervaLoggerAppender.createAppender(); - logger.warn("test"); - logger.debug("1"); - logger.error("2"); - logger.info("3"); - logger.fatal("4"); - logger.trace("5"); - assertEquals(1, appender.getDebugs().size()); - assertEquals(1, appender.getWarnings().size()); - assertEquals(1, appender.getFatals().size()); - assertEquals(1, appender.getErrors().size()); - MinervaLoggerAppender.unregisterLogEventStorage(appender); - logger.warn("test"); - assertEquals(1, appender.getWarnings().size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + MinervaLoggerAppender appender = MinervaLoggerAppender.createAppender(); + logger.warn("test"); + logger.debug("1"); + logger.error("2"); + logger.info("3"); + logger.fatal("4"); + logger.trace("5"); + assertEquals(1, appender.getDebugs().size()); + assertEquals(1, appender.getWarnings().size()); + assertEquals(1, appender.getFatals().size()); + assertEquals(1, appender.getErrors().size()); + MinervaLoggerAppender.unregisterLogEventStorage(appender); + logger.warn("test"); + assertEquals(1, appender.getWarnings().size()); } @Test public void testLogContent() { - try { - MinervaLoggerAppender appender = MinervaLoggerAppender.createAppender(); - logger.warn("test"); - logger.warn("xyz"); - assertEquals(2, appender.getWarnings().size()); - assertNotEquals(appender.getWarnings().get(0),appender.getWarnings().get(1)); - MinervaLoggerAppender.unregisterLogEventStorage(appender); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + MinervaLoggerAppender appender = MinervaLoggerAppender.createAppender(); + logger.warn("test"); + logger.warn("xyz"); + assertEquals(2, appender.getWarnings().size()); + assertNotEquals(appender.getWarnings().get(0), appender.getWarnings().get(1)); + MinervaLoggerAppender.unregisterLogEventStorage(appender); } } diff --git a/commons/src/test/java/lcsb/mapviewer/common/ObjectUtilsTest.java b/commons/src/test/java/lcsb/mapviewer/common/ObjectUtilsTest.java index ff8b79effc9a6a3d43d3f3d886865f4664e8d23a..7cf9e2ff1abf875b08a7bba0dd11dc3b42dbed99 100644 --- a/commons/src/test/java/lcsb/mapviewer/common/ObjectUtilsTest.java +++ b/commons/src/test/java/lcsb/mapviewer/common/ObjectUtilsTest.java @@ -1,58 +1,45 @@ package lcsb.mapviewer.common; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import java.lang.reflect.Constructor; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import lcsb.mapviewer.common.exception.InvalidArgumentException; -public class ObjectUtilsTest { - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testGetIdOfObject() { - Object obj = new Object() { - @SuppressWarnings("unused") - public int getId() { - return 107; - } - }; - assertEquals((Integer) 107, ObjectUtils.getIdOfObject(obj)); - } - - @Test - public void testGetIdOfObjectWithoutId() { - Object obj = new Object(); - try { - ObjectUtils.getIdOfObject(obj); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - - } - } - - @Test - public void testPrivateConstructor() throws Exception { - try { - Constructor<?> constr = ObjectUtils.class.getDeclaredConstructor(new Class<?>[] {}); - constr.setAccessible(true); - assertNotNull(constr.newInstance(new Object[] {})); - } catch (Exception e) { - throw e; - } - } +public class ObjectUtilsTest extends CommonTestFunctions { + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testGetIdOfObject() { + Object obj = new Object() { + @SuppressWarnings("unused") + public int getId() { + return 107; + } + }; + assertEquals((Integer) 107, ObjectUtils.getIdOfObject(obj)); + } + + @Test(expected = InvalidArgumentException.class) + public void testGetIdOfObjectWithoutId() { + Object obj = new Object(); + ObjectUtils.getIdOfObject(obj); + } + + @Test + public void testPrivateConstructor() throws Exception { + Constructor<?> constr = ObjectUtils.class.getDeclaredConstructor(new Class<?>[] {}); + constr.setAccessible(true); + assertNotNull(constr.newInstance(new Object[] {})); + } } diff --git a/commons/src/test/java/lcsb/mapviewer/common/SystemClipboardTest.java b/commons/src/test/java/lcsb/mapviewer/common/SystemClipboardTest.java index de178fef22bce295d08e0afb4789765b521bfb50..938661d59e31e3d8b3fb6986cf20f3d0366c5a64 100644 --- a/commons/src/test/java/lcsb/mapviewer/common/SystemClipboardTest.java +++ b/commons/src/test/java/lcsb/mapviewer/common/SystemClipboardTest.java @@ -1,99 +1,72 @@ package lcsb.mapviewer.common; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import static org.junit.Assert.*; import java.awt.Toolkit; -import java.awt.datatransfer.Clipboard; -import java.awt.datatransfer.DataFlavor; -import java.awt.datatransfer.Transferable; -import java.awt.datatransfer.UnsupportedFlavorException; +import java.awt.datatransfer.*; import java.io.IOException; import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.*; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -public class SystemClipboardTest { - Logger logger = LogManager.getLogger(SystemClipboardTest.class); - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testClipboard() throws Exception { - try { - SystemClipboard sc = new SystemClipboard(); - sc.setClipboardContents("TEST"); - - SystemClipboard sc2 = new SystemClipboard(); - assertEquals("TEST",sc2.getClipboardContents()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testInvalidClipboard() throws Exception { - try { - SystemClipboard sc2 = new SystemClipboard(); - - Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); - clipboard.setContents(new Transferable() { - - @Override - public boolean isDataFlavorSupported(DataFlavor flavor) { - return true; - } - - @Override - public DataFlavor[] getTransferDataFlavors() { - return null; - } - - @Override - public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException { - throw new UnsupportedFlavorException(flavor); - } - }, sc2); - - assertEquals(null,sc2.getClipboardContents()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testLostOwnership() throws Exception { - try { - SystemClipboard sc = new SystemClipboard(); - sc.lostOwnership(null, null); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testEmpty() throws Exception { - try { - SystemClipboard sc2 = new SystemClipboard(); - sc2.setClipboardContents(null); - assertNull(sc2.getClipboardContents()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } +import org.apache.logging.log4j.Logger; +import org.junit.*; +public class SystemClipboardTest extends CommonTestFunctions { + Logger logger = LogManager.getLogger(SystemClipboardTest.class); + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testClipboard() throws Exception { + SystemClipboard sc = new SystemClipboard(); + sc.setClipboardContents("TEST"); + + SystemClipboard sc2 = new SystemClipboard(); + assertEquals("TEST", sc2.getClipboardContents()); + } + + @Test + public void testInvalidClipboard() throws Exception { + SystemClipboard sc2 = new SystemClipboard(); + + Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); + clipboard.setContents(new Transferable() { + + @Override + public boolean isDataFlavorSupported(DataFlavor flavor) { + return true; + } + + @Override + public DataFlavor[] getTransferDataFlavors() { + return null; + } + + @Override + public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException { + throw new UnsupportedFlavorException(flavor); + } + }, sc2); + + assertEquals(null, sc2.getClipboardContents()); + } + + @Test + public void testLostOwnership() throws Exception { + SystemClipboard sc = new SystemClipboard(); + sc.lostOwnership(null, null); + } + + @Test + public void testEmpty() throws Exception { + SystemClipboard sc2 = new SystemClipboard(); + sc2.setClipboardContents(null); + assertNull(sc2.getClipboardContents()); + } } diff --git a/commons/src/test/java/lcsb/mapviewer/common/TextFileUtilsTest.java b/commons/src/test/java/lcsb/mapviewer/common/TextFileUtilsTest.java index 635e492efe3492c570bbc46307403a1ad31d65c3..c756075a533e4a2a52dd233aec01bf67a94a759e 100644 --- a/commons/src/test/java/lcsb/mapviewer/common/TextFileUtilsTest.java +++ b/commons/src/test/java/lcsb/mapviewer/common/TextFileUtilsTest.java @@ -1,78 +1,57 @@ package lcsb.mapviewer.common; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.junit.Assert.*; -import java.io.ByteArrayInputStream; -import java.io.FileInputStream; -import java.io.InputStream; +import java.io.*; import java.lang.reflect.Constructor; import java.nio.charset.StandardCharsets; import java.util.Map; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -public class TextFileUtilsTest { - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testGetHeaderParametersFromFile() throws Exception { - try { - String fileContent = "#header\n" + - "#param1=value1\n" + - "#\n" + - "no header\n" + - "#param2=value\n"; - - Map<String, String> params = TextFileUtils.getHeaderParametersFromFile(new ByteArrayInputStream(fileContent.getBytes(StandardCharsets.UTF_8))); - assertTrue(params.keySet().size() >= 1); - assertNull(params.get("param2")); - assertEquals("value1", params.get("param1")); - assertNull(params.get("header")); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testParseHeader() throws Exception { - try { - InputStream is = new FileInputStream("testFiles/fileHeader.txt"); - Map<String, String> map = TextFileUtils.getHeaderParametersFromFile(is); - - assertEquals("1.0", map.get("VERSION")); - assertEquals("example name", map.get("NAME")); - assertEquals("layout description", map.get("DESCRIPTION")); - assertEquals("", map.get("MISSING")); - assertEquals("A=B", map.get("TRICKY")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testPrivateConstructor() throws Exception { - try { - Constructor<?> constr = TextFileUtils.class.getDeclaredConstructor(new Class<?>[] {}); - constr.setAccessible(true); - assertNotNull(constr.newInstance(new Object[] {})); - } catch (Exception e) { - throw e; - } - } +import org.junit.*; + +public class TextFileUtilsTest extends CommonTestFunctions { + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testGetHeaderParametersFromFile() throws Exception { + String fileContent = "#header\n" + + "#param1=value1\n" + + "#\n" + + "no header\n" + + "#param2=value\n"; + + Map<String, String> params = TextFileUtils + .getHeaderParametersFromFile(new ByteArrayInputStream(fileContent.getBytes(StandardCharsets.UTF_8))); + assertTrue(params.keySet().size() >= 1); + assertNull(params.get("param2")); + assertEquals("value1", params.get("param1")); + assertNull(params.get("header")); + } + + @Test + public void testParseHeader() throws Exception { + InputStream is = new FileInputStream("testFiles/fileHeader.txt"); + Map<String, String> map = TextFileUtils.getHeaderParametersFromFile(is); + + assertEquals("1.0", map.get("VERSION")); + assertEquals("example name", map.get("NAME")); + assertEquals("layout description", map.get("DESCRIPTION")); + assertEquals("", map.get("MISSING")); + assertEquals("A=B", map.get("TRICKY")); + } + + @Test + public void testPrivateConstructor() throws Exception { + Constructor<?> constr = TextFileUtils.class.getDeclaredConstructor(new Class<?>[] {}); + constr.setAccessible(true); + assertNotNull(constr.newInstance(new Object[] {})); + } } diff --git a/commons/src/test/java/lcsb/mapviewer/common/XmlParserTest.java b/commons/src/test/java/lcsb/mapviewer/common/XmlParserTest.java index 375481170770160cbb9b8f8a7ccd62b9617142b5..fbaed58e7896e6fc25658a279f3ebee15b00888f 100644 --- a/commons/src/test/java/lcsb/mapviewer/common/XmlParserTest.java +++ b/commons/src/test/java/lcsb/mapviewer/common/XmlParserTest.java @@ -1,36 +1,24 @@ package lcsb.mapviewer.common; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import java.awt.Color; -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; +import java.io.*; import java.nio.charset.StandardCharsets; import java.util.List; import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.Logger; import org.apache.xerces.dom.DocumentImpl; import org.apache.xerces.dom.ElementImpl; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.w3c.dom.Document; -import org.w3c.dom.Element; -import org.w3c.dom.NamedNodeMap; -import org.w3c.dom.Node; +import org.junit.*; +import org.w3c.dom.*; import org.xml.sax.InputSource; import lcsb.mapviewer.common.exception.InvalidArgumentException; import lcsb.mapviewer.common.exception.InvalidXmlSchemaException; -public class XmlParserTest { +public class XmlParserTest extends CommonTestFunctions { Logger logger = LogManager.getLogger(XmlParserTest.class); @Before @@ -43,427 +31,262 @@ public class XmlParserTest { @Test public void testColorParsing() { - try { - String strColor = "ffcbcd09"; - - Color c = XmlParser.stringToColor(strColor); - String resultString = XmlParser.colorToString(c); - assertTrue("Different string representation: " + strColor + " - " + resultString, - strColor.equalsIgnoreCase(resultString)); - - Color c2 = XmlParser.stringToColor(resultString); - - assertEquals(c.getRed(), c2.getRed()); - assertEquals(c.getGreen(), c2.getGreen()); - assertEquals(c.getBlue(), c2.getBlue()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String strColor = "ffcbcd09"; + + Color c = XmlParser.stringToColor(strColor); + String resultString = XmlParser.colorToString(c); + assertTrue("Different string representation: " + strColor + " - " + resultString, + strColor.equalsIgnoreCase(resultString)); + + Color c2 = XmlParser.stringToColor(resultString); + + assertEquals(c.getRed(), c2.getRed()); + assertEquals(c.getGreen(), c2.getGreen()); + assertEquals(c.getBlue(), c2.getBlue()); } - @Test + @Test(expected = InvalidArgumentException.class) public void testInvalidColorParsing() { - try { - String strColor = "hello world"; - - XmlParser.stringToColor(strColor); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String strColor = "hello world"; + + XmlParser.stringToColor(strColor); } @Test public void testColorParsingWithAlpha() { - try { - String strColor = "fecbcd09"; - - Color c = XmlParser.stringToColor(strColor); - String resultString = XmlParser.colorToString(c); - assertTrue("Different string representation: " + strColor + " - " + resultString, - strColor.equalsIgnoreCase(resultString)); - - Color c2 = XmlParser.stringToColor(resultString); - - assertEquals(c.getRed(), c2.getRed()); - assertEquals(c.getGreen(), c2.getGreen()); - assertEquals(c.getBlue(), c2.getBlue()); - assertEquals(c.getAlpha(), c2.getAlpha()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String strColor = "fecbcd09"; + + Color c = XmlParser.stringToColor(strColor); + String resultString = XmlParser.colorToString(c); + assertTrue("Different string representation: " + strColor + " - " + resultString, + strColor.equalsIgnoreCase(resultString)); + + Color c2 = XmlParser.stringToColor(resultString); + + assertEquals(c.getRed(), c2.getRed()); + assertEquals(c.getGreen(), c2.getGreen()); + assertEquals(c.getBlue(), c2.getBlue()); + assertEquals(c.getAlpha(), c2.getAlpha()); } @Test public void testGetXmlDocumentFromString() throws Exception { - try { - Document validDoc = XmlParser.getXmlDocumentFromString("<node>test</node>"); - assertNotNull(validDoc); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Document validDoc = XmlParser.getXmlDocumentFromString("<node>test</node>"); + assertNotNull(validDoc); } @Test public void testNodeToString() throws Exception { - try { - String xml = "<test_node>test_x</test_node>"; - Document validDoc = XmlParser.getXmlDocumentFromString(xml); - String str = XmlParser.nodeToString(validDoc); - assertEquals(xml.trim(), str.trim()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - + String xml = "<test_node>test_x</test_node>"; + Document validDoc = XmlParser.getXmlDocumentFromString(xml); + String str = XmlParser.nodeToString(validDoc); + assertEquals(xml.trim(), str.trim()); } @Test public void testEmptyNodeToString() throws Exception { - try { - String str = XmlParser.nodeToString(null); - assertNull(str); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - + String str = XmlParser.nodeToString(null); + assertNull(str); } @Test public void testNodeToStringWithHeader() throws Exception { - try { - String xml = "<test_node>test_x</test_node>"; - Document validDoc = XmlParser.getXmlDocumentFromString(xml); - String str = XmlParser.nodeToString(validDoc, true); - assertTrue(str.contains(xml)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String xml = "<test_node>test_x</test_node>"; + Document validDoc = XmlParser.getXmlDocumentFromString(xml); + String str = XmlParser.nodeToString(validDoc, true); + assertTrue(str.contains(xml)); } boolean threadSucceded; @Test public void testConcurrencyParse() throws Exception { - try { - StringBuilder builder = new StringBuilder("<doc>"); - for (int i = 0; i < 30000; i++) - builder.append("<test_node>test_x</test_node>"); - builder.append("</doc>"); - final String xml = builder.toString(); - threadSucceded = false; - Thread t1 = new Thread(new Runnable() { - @Override - public void run() { - try { - Document validDoc = XmlParser.getXmlDocumentFromString(xml); - assertNotNull(validDoc); - threadSucceded = true; - } catch (InvalidXmlSchemaException e) { - e.printStackTrace(); - } + StringBuilder builder = new StringBuilder("<doc>"); + for (int i = 0; i < 30000; i++) + builder.append("<test_node>test_x</test_node>"); + builder.append("</doc>"); + final String xml = builder.toString(); + threadSucceded = false; + Thread t1 = new Thread(new Runnable() { + @Override + public void run() { + try { + Document validDoc = XmlParser.getXmlDocumentFromString(xml); + assertNotNull(validDoc); + threadSucceded = true; + } catch (InvalidXmlSchemaException e) { + e.printStackTrace(); } - }); - t1.start(); - assertNotNull(XmlParser.getXmlDocumentFromString(xml)); - t1.join(); - assertTrue("There was a problem with multithreading", threadSucceded); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - + } + }); + t1.start(); + assertNotNull(XmlParser.getXmlDocumentFromString(xml)); + t1.join(); + assertTrue("There was a problem with multithreading", threadSucceded); } @Test public void testInvalidNodeToString() throws Exception { - try { - final DocumentImpl xmlDoc = new DocumentImpl(); - - Element root = xmlDoc.createElement("booking"); + final DocumentImpl xmlDoc = new DocumentImpl(); - class Tmp extends ElementImpl { - /** - * - */ - private static final long serialVersionUID = 1L; + Element root = xmlDoc.createElement("booking"); - public Tmp() { - this.ownerDocument = xmlDoc; - } + class Tmp extends ElementImpl { + /** + * + */ + private static final long serialVersionUID = 1L; - @Override - public NamedNodeMap getAttributes() { - return null; - } + public Tmp() { + this.ownerDocument = xmlDoc; + } + @Override + public NamedNodeMap getAttributes() { + return null; } - ; - Element el = new Tmp(); - root.appendChild(el); - assertNotNull(XmlParser.nodeToString(root, true)); - } catch (Exception e) { - e.printStackTrace(); - throw e; + } + ; + Element el = new Tmp(); + root.appendChild(el); + assertNotNull(XmlParser.nodeToString(root, true)); } - @Test + @Test(expected = InvalidXmlSchemaException.class) public void testGetXmlDocumentFromInvalidString() throws Exception { - try { - XmlParser.getXmlDocumentFromString("<node>test<node>"); - fail("Exception expected"); - } catch (InvalidXmlSchemaException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - + XmlParser.getXmlDocumentFromString("<node>test<node>"); } - @Test + @Test(expected = InvalidXmlSchemaException.class) public void testGetXmlDocumentFromInvalidInputStream() throws Exception { - try { - XmlParser.getXmlDocumentFromInputSource(new InputSource(), true); - fail("Exception expected"); - } catch (InvalidXmlSchemaException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - + XmlParser.getXmlDocumentFromInputSource(new InputSource(), true); } @Test public void testEscapeXml() throws Exception { - try { - String str = XmlParser.escapeXml("<xml>node</xml>"); - assertFalse(str.contains("<")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - + String str = XmlParser.escapeXml("<xml>node</xml>"); + assertFalse(str.contains("<")); } @Test public void testEscapeNullXml() throws Exception { - try { - String str = XmlParser.escapeXml(null); - assertNull(str); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - + String str = XmlParser.escapeXml(null); + assertNull(str); } @Test public void testFileToString() throws Exception { - try { - String str = XmlParser.fileToString("testFiles/test.txt"); - assertTrue(str.contains("test")); - assertTrue(str.contains("file")); - assertTrue(str.contains("with some content")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - + String str = XmlParser.fileToString("testFiles/test.txt"); + assertTrue(str.contains("test")); + assertTrue(str.contains("file")); + assertTrue(str.contains("with some content")); } @Test public void testInputStreamToString() throws Exception { - try { - InputStream stream = new ByteArrayInputStream("stream string".getBytes(StandardCharsets.UTF_8)); - String str = XmlParser.inputStreamToString(stream); - assertEquals("stream string", str); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - + InputStream stream = new ByteArrayInputStream("stream string".getBytes(StandardCharsets.UTF_8)); + String str = XmlParser.inputStreamToString(stream); + assertEquals("stream string", str); } @Test public void testGetNodeValue() throws Exception { - try { - Document document = XmlParser.getXmlDocumentFromString("<node>content</node>"); - Node node = XmlParser.getNode("node", document); - String str = XmlParser.getNodeValue(node); - assertEquals("content", str); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - + Document document = XmlParser.getXmlDocumentFromString("<node>content</node>"); + Node node = XmlParser.getNode("node", document); + String str = XmlParser.getNodeValue(node); + assertEquals("content", str); } @Test public void testGetNodeValue2() throws Exception { - try { - String str = XmlParser.getNodeValue(null); - assertEquals("", str); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - + String str = XmlParser.getNodeValue(null); + assertEquals("", str); } @Test public void testGetNodeValue3() throws Exception { - try { - Document document = XmlParser.getXmlDocumentFromString("<node></node>"); - Node node = XmlParser.getNode("node", document); - String str = XmlParser.getNodeValue(node); - assertEquals("", str); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - + Document document = XmlParser.getXmlDocumentFromString("<node></node>"); + Node node = XmlParser.getNode("node", document); + String str = XmlParser.getNodeValue(node); + assertEquals("", str); } @Test public void testGetNodeValue4() throws Exception { - try { - Document document = XmlParser.getXmlDocumentFromString("<node><subnode/></node>"); - Node node = XmlParser.getNode("node", document); - String str = XmlParser.getNodeValue(node); - assertEquals("", str); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - + Document document = XmlParser.getXmlDocumentFromString("<node><subnode/></node>"); + Node node = XmlParser.getNode("node", document); + String str = XmlParser.getNodeValue(node); + assertEquals("", str); } - @Test + @Test(expected = IOException.class) public void testInputStreamToStringThrowsException() throws Exception { - try { - XmlParser.inputStreamToString(new InputStream() { - @Override - public int read() throws IOException { - throw new IOException(); - } - }); - fail("Exception expected"); - } catch (IOException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - + XmlParser.inputStreamToString(new InputStream() { + @Override + public int read() throws IOException { + throw new IOException(); + } + }); } - @Test + @Test(expected = IOException.class) public void testFileToStringThrowsException() throws Exception { - try { - XmlParser.fileToString("testFiles/unknown file.txt"); - fail("Exception expected"); - } catch (IOException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - + XmlParser.fileToString("testFiles/unknown file.txt"); } @Test public void testGetNodeAttr() throws Exception { - try { - Document document = XmlParser.getXmlDocumentFromString("<node attr=\"val\">content</node>"); - Node node = XmlParser.getNode("node", document); - String str = XmlParser.getNodeAttr("attr", node); - assertEquals("val", str); - str = XmlParser.getNodeAttr("attr2", node); - assertEquals("", str); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - + Document document = XmlParser.getXmlDocumentFromString("<node attr=\"val\">content</node>"); + Node node = XmlParser.getNode("node", document); + String str = XmlParser.getNodeAttr("attr", node); + assertEquals("val", str); + str = XmlParser.getNodeAttr("attr2", node); + assertEquals("", str); } @Test public void testGetNodes() throws Exception { - try { - Document document = XmlParser - .getXmlDocumentFromString("<node><subnode>content1</subnode><subnode>content2</subnode><other/></node>"); - Node node = XmlParser.getNode("node", document); - List<Node> nodes = XmlParser.getNodes("subnode", node.getChildNodes()); - assertEquals(2, nodes.size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - + Document document = XmlParser + .getXmlDocumentFromString("<node><subnode>content1</subnode><subnode>content2</subnode><other/></node>"); + Node node = XmlParser.getNode("node", document); + List<Node> nodes = XmlParser.getNodes("subnode", node.getChildNodes()); + assertEquals(2, nodes.size()); } @Test public void testGetNode() throws Exception { - try { - Document document = XmlParser - .getXmlDocumentFromString("<node><subnode>content1</subnode><subnode>content2</subnode><other/></node>"); - Node node = XmlParser.getNode("node", document); - Node child = XmlParser.getNode("other", node.getChildNodes()); - assertNotNull(child); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - + Document document = XmlParser + .getXmlDocumentFromString("<node><subnode>content1</subnode><subnode>content2</subnode><other/></node>"); + Node node = XmlParser.getNode("node", document); + Node child = XmlParser.getNode("other", node.getChildNodes()); + assertNotNull(child); } @Test public void testGetNode2() throws Exception { - try { - Document document = XmlParser.getXmlDocumentFromString( - "<node attr=\"x\"><subnode>content1</subnode><subnode>content2</subnode><other/></node>"); - Node node = XmlParser.getNode("node", document); - Node child = XmlParser.getNode("other2", node.getChildNodes()); - assertNull(child); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - + Document document = XmlParser.getXmlDocumentFromString( + "<node attr=\"x\"><subnode>content1</subnode><subnode>content2</subnode><other/></node>"); + Node node = XmlParser.getNode("node", document); + Node child = XmlParser.getNode("other2", node.getChildNodes()); + assertNull(child); } @Test public void testGetNode3() throws Exception { - try { - Document document = XmlParser.getXmlDocumentFromString("<node attr=\"x\">xxx</node>"); - Node node = XmlParser.getNode("node", document); - Node child = XmlParser.getNode("other2", node.getChildNodes()); - assertNull(child); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Document document = XmlParser.getXmlDocumentFromString("<node attr=\"x\">xxx</node>"); + Node node = XmlParser.getNode("node", document); + Node child = XmlParser.getNode("other2", node.getChildNodes()); + assertNull(child); } @Test public void testLowercaseXmlNames() throws Exception { - try { - String inputXml = "<node><ASD>Test</ASD></node>"; - String outputXml = XmlParser.lowercaseXmlNames(inputXml); + String inputXml = "<node><ASD>Test</ASD></node>"; + String outputXml = XmlParser.lowercaseXmlNames(inputXml); - assertTrue(outputXml.indexOf("asd") >= 0); - assertTrue(outputXml.indexOf("Test") >= 0); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertTrue(outputXml.indexOf("asd") >= 0); + assertTrue(outputXml.indexOf("Test") >= 0); } } diff --git a/commons/src/test/java/lcsb/mapviewer/common/geometry/ColorParserTest.java b/commons/src/test/java/lcsb/mapviewer/common/geometry/ColorParserTest.java index 4b927108fbb9285709a30cc13d0643cd5bd45be5..bc6e7abe34323157a43430de9cae714bccda1830 100644 --- a/commons/src/test/java/lcsb/mapviewer/common/geometry/ColorParserTest.java +++ b/commons/src/test/java/lcsb/mapviewer/common/geometry/ColorParserTest.java @@ -1,18 +1,15 @@ package lcsb.mapviewer.common.geometry; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import java.awt.Color; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; +import lcsb.mapviewer.common.CommonTestFunctions; import lcsb.mapviewer.common.exception.InvalidArgumentException; -public class ColorParserTest { +public class ColorParserTest extends CommonTestFunctions { @AfterClass public static void tearDownAfterClass() throws Exception { @@ -26,72 +23,48 @@ public class ColorParserTest { public void tearDown() throws Exception { } - @Test + @Test(expected = InvalidArgumentException.class) public void testSetInvalidColor() throws Exception { - try { - ColorParser parser = new ColorParser(); - parser.parse("qwe"); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + ColorParser parser = new ColorParser(); + parser.parse("qwe"); } - @Test + @Test(expected = InvalidArgumentException.class) public void testSetInvalidColor2() throws Exception { - try { - ColorParser parser = new ColorParser(); - parser.parse("fffffff"); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + ColorParser parser = new ColorParser(); + parser.parse("fffffff"); } @Test public void testSetColor() throws Exception { - try { - ColorParser parser = new ColorParser(); - Color color = parser.parse("#ffffff"); - assertEquals(Color.WHITE, color); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + ColorParser parser = new ColorParser(); + Color color = parser.parse("#ffffff"); + assertEquals(Color.WHITE, color); } - @Test(expected=InvalidArgumentException.class) + @Test(expected = InvalidArgumentException.class) public void testParseNull() throws Exception { - ColorParser parser = new ColorParser(); - parser.parse(null); + ColorParser parser = new ColorParser(); + parser.parse(null); } - @Test(expected=InvalidArgumentException.class) + @Test(expected = InvalidArgumentException.class) public void testParseEmpty() throws Exception { - ColorParser parser = new ColorParser(); - parser.parse(""); + ColorParser parser = new ColorParser(); + parser.parse(""); } @Test public void testSetColorToHtmlString() throws Exception { - try { - ColorParser parser = new ColorParser(); - - String colorString = "#ffffff"; - Color color = parser.parse(colorString); - assertEquals(colorString, parser.colorToHtml(color)); - - colorString = "#fc00ff"; - color = parser.parse(colorString); - assertEquals(colorString, parser.colorToHtml(color)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + ColorParser parser = new ColorParser(); + + String colorString = "#ffffff"; + Color color = parser.parse(colorString); + assertEquals(colorString, parser.colorToHtml(color)); + + colorString = "#fc00ff"; + color = parser.parse(colorString); + assertEquals(colorString, parser.colorToHtml(color)); } } diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/CellDesignerElementCollectionTest.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/CellDesignerElementCollectionTest.java index 48d06d7037c40b5f5e626c95aadbfe36ff23ff39..0a81b273b7781d7af46ace32343ab990d2fe6b08 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/CellDesignerElementCollectionTest.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/CellDesignerElementCollectionTest.java @@ -1,43 +1,31 @@ package lcsb.mapviewer.converter.model.celldesigner; -import static org.junit.Assert.fail; - -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import lcsb.mapviewer.common.exception.InvalidArgumentException; import lcsb.mapviewer.converter.model.celldesigner.structure.CellDesignerComplexSpecies; -public class CellDesignerElementCollectionTest { - - @AfterClass - public static void tearDownAfterClass() throws Exception { - } - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testAddTheSameElementTwice() { - try { - CellDesignerElementCollection collection = new CellDesignerElementCollection(); - CellDesignerComplexSpecies complex = new CellDesignerComplexSpecies(); - complex.setElementId("id"); - collection.addElement(complex); - collection.addElement(complex); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } +public class CellDesignerElementCollectionTest extends CellDesignerTestFunctions { + + @AfterClass + public static void tearDownAfterClass() throws Exception { + } + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test(expected = InvalidArgumentException.class) + public void testAddTheSameElementTwice() { + CellDesignerElementCollection collection = new CellDesignerElementCollection(); + CellDesignerComplexSpecies complex = new CellDesignerComplexSpecies(); + complex.setElementId("id"); + collection.addElement(complex); + collection.addElement(complex); + } } diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/CellDesignerTestFunctions.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/CellDesignerTestFunctions.java index 5f45574f219dbb2d19a8ecf21e99612d68060368..9e1b17f23e66d8efd938ebc7924268d713b8920a 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/CellDesignerTestFunctions.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/CellDesignerTestFunctions.java @@ -31,18 +31,14 @@ import javax.xml.transform.stream.StreamResult; import org.apache.logging.log4j.*; import org.apache.logging.log4j.core.LogEvent; - -import org.junit.After; -import org.junit.Before; +import org.junit.*; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; import org.xml.sax.SAXException; -import lcsb.mapviewer.common.Configuration; - -import lcsb.mapviewer.common.MinervaLoggerAppender; +import lcsb.mapviewer.common.*; import lcsb.mapviewer.common.exception.InvalidXmlSchemaException; import lcsb.mapviewer.converter.ConverterParams; import lcsb.mapviewer.converter.InvalidInputDataExecption; @@ -58,6 +54,9 @@ public abstract class CellDesignerTestFunctions { private MinervaLoggerAppender appender; + @Rule + public UnitTestFailedWatcher unitTestFailedWatcher = new UnitTestFailedWatcher(); + @Before public final void _setUp() throws Exception { MinervaLoggerAppender.unregisterLogEventStorage(appender); diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/CellDesignerXmlParserTest.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/CellDesignerXmlParserTest.java index 31079efea29e8084ffecb4b97f9c80d1bcae6cb0..b2c402159dc644454e8b130f83e15be11059b003 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/CellDesignerXmlParserTest.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/CellDesignerXmlParserTest.java @@ -1,33 +1,17 @@ package lcsb.mapviewer.converter.model.celldesigner; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; -import static org.mockito.Mockito.when; +import static org.junit.Assert.*; +import static org.mockito.Mockito.*; import java.awt.Color; -import java.awt.geom.Line2D; -import java.awt.geom.Point2D; -import java.awt.geom.Rectangle2D; -import java.io.BufferedReader; -import java.io.ByteArrayInputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; +import java.awt.geom.*; +import java.io.*; import java.nio.charset.StandardCharsets; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import org.apache.logging.log4j.*; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import java.util.*; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.junit.*; import org.mockito.Mockito; import lcsb.mapviewer.common.Configuration; @@ -38,24 +22,11 @@ import lcsb.mapviewer.converter.model.celldesigner.annotation.RestAnnotationPars import lcsb.mapviewer.model.graphics.PolylineData; import lcsb.mapviewer.model.map.BioEntity; import lcsb.mapviewer.model.map.compartment.Compartment; -import lcsb.mapviewer.model.map.layout.graphics.Layer; -import lcsb.mapviewer.model.map.layout.graphics.LayerOval; -import lcsb.mapviewer.model.map.layout.graphics.LayerRect; -import lcsb.mapviewer.model.map.layout.graphics.LayerText; -import lcsb.mapviewer.model.map.model.Author; -import lcsb.mapviewer.model.map.model.Model; -import lcsb.mapviewer.model.map.model.ModelComparator; -import lcsb.mapviewer.model.map.model.ModelFullIndexed; -import lcsb.mapviewer.model.map.reaction.AbstractNode; -import lcsb.mapviewer.model.map.reaction.Product; -import lcsb.mapviewer.model.map.reaction.Reactant; -import lcsb.mapviewer.model.map.reaction.Reaction; +import lcsb.mapviewer.model.map.layout.graphics.*; +import lcsb.mapviewer.model.map.model.*; +import lcsb.mapviewer.model.map.reaction.*; import lcsb.mapviewer.model.map.reaction.type.StateTransitionReaction; -import lcsb.mapviewer.model.map.species.Element; -import lcsb.mapviewer.model.map.species.Gene; -import lcsb.mapviewer.model.map.species.GenericProtein; -import lcsb.mapviewer.model.map.species.SimpleMolecule; -import lcsb.mapviewer.model.map.species.Species; +import lcsb.mapviewer.model.map.species.*; public class CellDesignerXmlParserTest extends CellDesignerTestFunctions { Logger logger = LogManager.getLogger(CellDesignerXmlParserTest.class); @@ -72,765 +43,502 @@ public class CellDesignerXmlParserTest extends CellDesignerTestFunctions { @Test public void testOpenFromInputStream() throws Exception { - try { - CellDesignerXmlParser parser = new CellDesignerXmlParser(); - FileInputStream fis = new FileInputStream("testFiles/sample.xml"); - Model model = parser.createModel(new ConverterParams().inputStream(fis)); - assertNotNull(model); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + CellDesignerXmlParser parser = new CellDesignerXmlParser(); + FileInputStream fis = new FileInputStream("testFiles/sample.xml"); + Model model = parser.createModel(new ConverterParams().inputStream(fis)); + assertNotNull(model); } @Test public void testZIndexAvailableForBioEntities() throws Exception { - try { - CellDesignerXmlParser parser = new CellDesignerXmlParser(); - Model model = parser.createModel(new ConverterParams().filename("testFiles/sample.xml")); - for (BioEntity bioEntity : model.getBioEntities()) { - assertNotNull(bioEntity.getZ()); - } - } catch (Exception e) { - e.printStackTrace(); - throw e; + CellDesignerXmlParser parser = new CellDesignerXmlParser(); + Model model = parser.createModel(new ConverterParams().filename("testFiles/sample.xml")); + for (BioEntity bioEntity : model.getBioEntities()) { + assertNotNull(bioEntity.getZ()); } } @Test public void testOpenFromFile() throws Exception { - try { - CellDesignerXmlParser parser = new CellDesignerXmlParser(); - Model model = parser.createModel(new ConverterParams().filename("testFiles/sample.xml")); - assertNotNull(model); - assertEquals("sample", model.getName()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + CellDesignerXmlParser parser = new CellDesignerXmlParser(); + Model model = parser.createModel(new ConverterParams().filename("testFiles/sample.xml")); + assertNotNull(model); + assertEquals("sample", model.getName()); } @Test public void testParseTransparency() throws Exception { - try { - CellDesignerXmlParser parser = new CellDesignerXmlParser(); - Model model = parser.createModel(new ConverterParams().filename("testFiles/model_with_transparency.xml")); - assertFalse(model.getCompartments().get(0).getTransparencyLevel().isEmpty()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + CellDesignerXmlParser parser = new CellDesignerXmlParser(); + Model model = parser.createModel(new ConverterParams().filename("testFiles/model_with_transparency.xml")); + assertFalse(model.getCompartments().get(0).getTransparencyLevel().isEmpty()); } @Test public void testParseTransparencyDeprecated() throws Exception { - try { - CellDesignerXmlParser parser = new CellDesignerXmlParser(); - Model model = parser.createModel(new ConverterParams().filename("testFiles/model_with_transparency_old.xml")); - assertFalse(model.getCompartments().get(0).getTransparencyLevel().isEmpty()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + CellDesignerXmlParser parser = new CellDesignerXmlParser(); + Model model = parser.createModel(new ConverterParams().filename("testFiles/model_with_transparency_old.xml")); + assertFalse(model.getCompartments().get(0).getTransparencyLevel().isEmpty()); } @Test public void testParseVcard() throws Exception { - try { - CellDesignerXmlParser parser = new CellDesignerXmlParser(); - Model model = parser.createModel(new ConverterParams().filename("testFiles/model_with_vcard.xml")); - assertEquals("There is one author defined", 1, model.getAuthors().size()); - Author author = model.getAuthors().get(0); - assertNotNull("Author data cannot be null", author); - assertEquals("Piotr", author.getFirstName()); - assertEquals("Gawron", author.getLastName()); - assertEquals("piotr.gawron@uni.lu", author.getEmail()); - assertEquals("LCSB", author.getOrganisation()); - assertEquals("Modification date is not defined", 1, model.getModificationDates().size()); - assertNotNull("Creation date is not defined", model.getCreationDate()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test + CellDesignerXmlParser parser = new CellDesignerXmlParser(); + Model model = parser.createModel(new ConverterParams().filename("testFiles/model_with_vcard.xml")); + assertEquals("There is one author defined", 1, model.getAuthors().size()); + Author author = model.getAuthors().get(0); + assertNotNull("Author data cannot be null", author); + assertEquals("Piotr", author.getFirstName()); + assertEquals("Gawron", author.getLastName()); + assertEquals("piotr.gawron@uni.lu", author.getEmail()); + assertEquals("LCSB", author.getOrganisation()); + assertEquals("Modification date is not defined", 1, model.getModificationDates().size()); + assertNotNull("Creation date is not defined", model.getCreationDate()); + } + + @Test(expected = InvalidInputDataExecption.class) public void testOpenFromInvalidFile() throws Exception { - try { - CellDesignerXmlParser parser = new CellDesignerXmlParser(); - parser.createModel(new ConverterParams().filename("testFiles/invalid/sample.xml")); - fail("Exceptin expected"); - } catch (InvalidInputDataExecption e) { - assertTrue(e.getMessage().contains("blablablabla")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + CellDesignerXmlParser parser = new CellDesignerXmlParser(); + parser.createModel(new ConverterParams().filename("testFiles/invalid/sample.xml")); } - @Test + @Test(expected = InvalidInputDataExecption.class) public void testOpenFromInvalidFile2() throws Exception { - try { - CellDesignerXmlParser parser = new CellDesignerXmlParser(); - parser.createModel(new ConverterParams().filename("testFiles/invalid/sample2.xml")); - fail("Exceptin expected"); - } catch (InvalidInputDataExecption e) { - assertTrue(e.getMessage().contains("No celldesigner:extension node in SBML/model/annotation")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + CellDesignerXmlParser parser = new CellDesignerXmlParser(); + parser.createModel(new ConverterParams().filename("testFiles/invalid/sample2.xml")); } - @Test + @Test(expected = InvalidInputDataExecption.class) public void testOpenFromInvalidFile3() throws Exception { - try { - CellDesignerXmlParser parser = new CellDesignerXmlParser(); - parser.createModel(new ConverterParams().filename("testFiles/invalid/sample10.xml")); - fail("Exceptin expected"); - } catch (InvalidInputDataExecption e) { - assertTrue(e.getMessage().contains("No type information for modification")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + CellDesignerXmlParser parser = new CellDesignerXmlParser(); + parser.createModel(new ConverterParams().filename("testFiles/invalid/sample10.xml")); } - @Test + @Test(expected = InvalidXmlSchemaException.class) public void testParseAnnotationComplexAliasesConnections() throws Exception { - try { - Model model = new ModelFullIndexed(null); - CellDesignerXmlParser parser = new CellDesignerXmlParser(); - parser.parseAnnotationComplexAliasesConnections(model, - super.getNodeFromXmlString(readFile("testFiles/invalid/complex_species_alias.xml"))); - fail("Exceptin expected"); - } catch (InvalidXmlSchemaException e) { - assertTrue(e.getMessage().contains("Alias does not exist")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Model model = new ModelFullIndexed(null); + CellDesignerXmlParser parser = new CellDesignerXmlParser(); + parser.parseAnnotationComplexAliasesConnections(model, + super.getNodeFromXmlString(readFile("testFiles/invalid/complex_species_alias.xml"))); } - @Test + @Test(expected = InvalidXmlSchemaException.class) public void testParseAnnotationComplexAliasesConnections2() throws Exception { - try { - Model model = new ModelFullIndexed(null); - CellDesignerXmlParser parser = new CellDesignerXmlParser(); - parser.parseAnnotationComplexAliasesConnections(model, - super.getNodeFromXmlString(readFile("testFiles/invalid/complex_species_alias2.xml"))); - fail("Exceptin expected"); - } catch (InvalidXmlSchemaException e) { - assertTrue(e.getMessage().contains("Unknown element of celldesigner:listOfComplexSpeciesAliases")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Model model = new ModelFullIndexed(null); + CellDesignerXmlParser parser = new CellDesignerXmlParser(); + parser.parseAnnotationComplexAliasesConnections(model, + super.getNodeFromXmlString(readFile("testFiles/invalid/complex_species_alias2.xml"))); } - @Test + @Test(expected = InvalidXmlSchemaException.class) public void testParseAnnotationAliasesConnections() throws Exception { - try { - Model model = new ModelFullIndexed(null); - CellDesignerXmlParser parser = new CellDesignerXmlParser(); - parser.parseAnnotationAliasesConnections(model, - super.getNodeFromXmlString(readFile("testFiles/invalid/list_of_species_alias.xml"))); - fail("Exceptin expected"); - } catch (InvalidXmlSchemaException e) { - assertTrue("Invalid message: " + e.getMessage(), e.getMessage().contains("Alias does not exist")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Model model = new ModelFullIndexed(null); + CellDesignerXmlParser parser = new CellDesignerXmlParser(); + parser.parseAnnotationAliasesConnections(model, + super.getNodeFromXmlString(readFile("testFiles/invalid/list_of_species_alias.xml"))); } - @Test + @Test(expected = InvalidXmlSchemaException.class) public void testParseAnnotationAliasesConnections2() throws Exception { - try { - Model model = new ModelFullIndexed(null); - CellDesignerXmlParser parser = new CellDesignerXmlParser(); - parser.parseAnnotationAliasesConnections(model, - super.getNodeFromXmlString(readFile("testFiles/invalid/list_of_species_alias2.xml"))); - fail("Exceptin expected"); - } catch (InvalidXmlSchemaException e) { - assertTrue("Invalid message: " + e.getMessage(), - e.getMessage().contains("Unknown element of celldesigner:listOfSpeciesAliases")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Model model = new ModelFullIndexed(null); + CellDesignerXmlParser parser = new CellDesignerXmlParser(); + parser.parseAnnotationAliasesConnections(model, + super.getNodeFromXmlString(readFile("testFiles/invalid/list_of_species_alias2.xml"))); } @Test public void testEmptyModelToXml() throws Exception { - try { - CellDesignerXmlParser parser = new CellDesignerXmlParser(); - FileInputStream fis = new FileInputStream("testFiles/empty.xml"); - Model model = parser.createModel(new ConverterParams().inputStream(fis)); - String xmlString = parser.model2String(model); - InputStream is = new ByteArrayInputStream(xmlString.getBytes("UTF-8")); + CellDesignerXmlParser parser = new CellDesignerXmlParser(); + FileInputStream fis = new FileInputStream("testFiles/empty.xml"); + Model model = parser.createModel(new ConverterParams().inputStream(fis)); + String xmlString = parser.model2String(model); + InputStream is = new ByteArrayInputStream(xmlString.getBytes("UTF-8")); - Model model2 = parser.createModel(new ConverterParams().inputStream(is)); + Model model2 = parser.createModel(new ConverterParams().inputStream(is)); - assertNotNull(model2); + assertNotNull(model2); - ModelComparator comparator = new ModelComparator(); - assertEquals(0, comparator.compare(model, model2)); + ModelComparator comparator = new ModelComparator(); + assertEquals(0, comparator.compare(model, model2)); - // default compartment definition looks like (but properties order might - // be different) - // <compartment metaid="default" id="default" size="1" units="volume"/> + // default compartment definition looks like (but properties order might + // be different) + // <compartment metaid="default" id="default" size="1" units="volume"/> - assertTrue("There is no default compartment", xmlString.indexOf("id=\"default\"") >= 0); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertTrue("There is no default compartment", xmlString.indexOf("id=\"default\"") >= 0); } @Test public void testSimpleModelToXml() throws Exception { - try { - CellDesignerXmlParser parser = new CellDesignerXmlParser(); - FileInputStream fis = new FileInputStream("testFiles/sample.xml"); - Model model = parser.createModel(new ConverterParams().inputStream(fis)); - String xmlString = parser.model2String(model); + CellDesignerXmlParser parser = new CellDesignerXmlParser(); + FileInputStream fis = new FileInputStream("testFiles/sample.xml"); + Model model = parser.createModel(new ConverterParams().inputStream(fis)); + String xmlString = parser.model2String(model); - InputStream is = new ByteArrayInputStream(xmlString.getBytes("UTF-8")); + InputStream is = new ByteArrayInputStream(xmlString.getBytes("UTF-8")); - Model model2 = parser.createModel(new ConverterParams().inputStream(is)); + Model model2 = parser.createModel(new ConverterParams().inputStream(is)); - // we have to replace size of the map because of auto resizing during - // reading - model2.setWidth(model.getWidth()); - model2.setHeight(model.getHeight()); + // we have to replace size of the map because of auto resizing during + // reading + model2.setWidth(model.getWidth()); + model2.setHeight(model.getHeight()); - assertNotNull(model2); + assertNotNull(model2); - ModelComparator comparator = new ModelComparator(); - assertEquals(0, comparator.compare(model, model2)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + ModelComparator comparator = new ModelComparator(); + assertEquals(0, comparator.compare(model, model2)); } @Test public void testModifierReactionModelToXml() throws Exception { - try { - CellDesignerXmlParser parser = new CellDesignerXmlParser(); - FileInputStream fis = new FileInputStream("testFiles/reactions/modification_reaction/catalysis.xml"); - Model model = parser.createModel(new ConverterParams().inputStream(fis)); - String xmlString = parser.model2String(model); - - InputStream is = new ByteArrayInputStream(xmlString.getBytes("UTF-8")); - - Model model2 = parser.createModel(new ConverterParams().inputStream(is).sizeAutoAdjust(false)); - ModelComparator comparator = new ModelComparator(); - assertEquals(0, comparator.compare(model, model2)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } + CellDesignerXmlParser parser = new CellDesignerXmlParser(); + FileInputStream fis = new FileInputStream("testFiles/reactions/modification_reaction/catalysis.xml"); + Model model = parser.createModel(new ConverterParams().inputStream(fis)); + String xmlString = parser.model2String(model); - @Test - public void testAutoMapWidth() { - try { - CellDesignerXmlParser parser = new CellDesignerXmlParser(); - FileInputStream fis = new FileInputStream("testFiles/autoMapWidth.xml"); - Model model = parser.createModel(new ConverterParams().inputStream(fis)); - assertTrue(model.getWidth() > 700); - assertTrue(model.getHeight() > 500); - } catch (Exception e) { - e.printStackTrace(); - fail("Exception occured: " + e.getMessage()); - } + InputStream is = new ByteArrayInputStream(xmlString.getBytes("UTF-8")); + + Model model2 = parser.createModel(new ConverterParams().inputStream(is).sizeAutoAdjust(false)); + ModelComparator comparator = new ModelComparator(); + assertEquals(0, comparator.compare(model, model2)); } @Test - public void testThrowIOException() { - try { - CellDesignerXmlParser parser = new CellDesignerXmlParser(); - InputStream fis = Mockito.mock(InputStream.class); - when(fis.read()).thenThrow(new IOException()); + public void testAutoMapWidth() throws Exception { + CellDesignerXmlParser parser = new CellDesignerXmlParser(); + FileInputStream fis = new FileInputStream("testFiles/autoMapWidth.xml"); + Model model = parser.createModel(new ConverterParams().inputStream(fis)); + assertTrue(model.getWidth() > 700); + assertTrue(model.getHeight() > 500); + } - parser.createModel(new ConverterParams().inputStream(fis)); - fail("Exception expected"); - } catch (InvalidInputDataExecption e) { + @Test(expected = InvalidInputDataExecption.class) + public void testThrowIOException() throws Exception { + CellDesignerXmlParser parser = new CellDesignerXmlParser(); + InputStream fis = Mockito.mock(InputStream.class); + when(fis.read()).thenThrow(new IOException()); - } catch (Exception e) { - e.printStackTrace(); - fail("Exception occured: " + e.getMessage()); - } + parser.createModel(new ConverterParams().inputStream(fis)); } - @Test - public void testInvalidInputFile1() { - try { - CellDesignerXmlParser parser = new CellDesignerXmlParser(); - FileInputStream fis = new FileInputStream("testFiles/invalid/invalid_CD_1.xml"); - parser.createModel(new ConverterParams().inputStream(fis)); - fail("Exception expected"); - } catch (InvalidInputDataExecption e) { - - } catch (Exception e) { - e.printStackTrace(); - fail("Exception occured: " + e.getMessage()); - } + @Test(expected = InvalidInputDataExecption.class) + public void testInvalidInputFile1() throws Exception { + CellDesignerXmlParser parser = new CellDesignerXmlParser(); + FileInputStream fis = new FileInputStream("testFiles/invalid/invalid_CD_1.xml"); + parser.createModel(new ConverterParams().inputStream(fis)); } - @Test - public void testInvalidInputFile2() { - try { - CellDesignerXmlParser parser = new CellDesignerXmlParser(); - FileInputStream fis = new FileInputStream("testFiles/invalid/invalid_CD_2.xml"); - parser.createModel(new ConverterParams().inputStream(fis)); - fail("Exception expected"); - } catch (InvalidInputDataExecption e) { - - } catch (Exception e) { - e.printStackTrace(); - fail("Exception occured: " + e.getMessage()); - } + @Test(expected = InvalidInputDataExecption.class) + public void testInvalidInputFile2() throws Exception { + CellDesignerXmlParser parser = new CellDesignerXmlParser(); + FileInputStream fis = new FileInputStream("testFiles/invalid/invalid_CD_2.xml"); + parser.createModel(new ConverterParams().inputStream(fis)); } - @Test - public void testInvalidInputFile3() { - try { - CellDesignerXmlParser parser = new CellDesignerXmlParser(); - FileInputStream fis = new FileInputStream("testFiles/invalid/invalid_CD_3.xml"); - parser.createModel(new ConverterParams().inputStream(fis)); - fail("Exception expected"); - } catch (InvalidInputDataExecption e) { - - } catch (Exception e) { - e.printStackTrace(); - fail("Exception occured: " + e.getMessage()); - } + @Test(expected = InvalidInputDataExecption.class) + public void testInvalidInputFile3() throws Exception { + CellDesignerXmlParser parser = new CellDesignerXmlParser(); + FileInputStream fis = new FileInputStream("testFiles/invalid/invalid_CD_3.xml"); + parser.createModel(new ConverterParams().inputStream(fis)); } - @Test - public void testInvalidInputFile4() { - try { - CellDesignerXmlParser parser = new CellDesignerXmlParser(); - FileInputStream fis = new FileInputStream("testFiles/invalid/invalid_CD_4.xml"); - parser.createModel(new ConverterParams().inputStream(fis)); - fail("Exception expected"); - } catch (InvalidInputDataExecption e) { - - } catch (Exception e) { - e.printStackTrace(); - fail("Exception occured: " + e.getMessage()); - } + @Test(expected = InvalidInputDataExecption.class) + public void testInvalidInputFile4() throws Exception { + CellDesignerXmlParser parser = new CellDesignerXmlParser(); + FileInputStream fis = new FileInputStream("testFiles/invalid/invalid_CD_4.xml"); + parser.createModel(new ConverterParams().inputStream(fis)); } - @Test - public void testInvalidBrokenTypeReaction() { - try { - CellDesignerXmlParser parser = new CellDesignerXmlParser(); - FileInputStream fis = new FileInputStream("testFiles/invalid/broken_type_reaction.xml"); - parser.createModel(new ConverterParams().inputStream(fis)); - fail("Exception expected"); - } catch (InvalidInputDataExecption e) { - assertTrue(e.getMessage().contains("Unknown CellDesigner class type")); - } catch (Exception e) { - e.printStackTrace(); - fail("Exception occured: " + e.getMessage()); - } + @Test(expected = InvalidInputDataExecption.class) + public void testInvalidBrokenTypeReaction() throws Exception { + CellDesignerXmlParser parser = new CellDesignerXmlParser(); + FileInputStream fis = new FileInputStream("testFiles/invalid/broken_type_reaction.xml"); + parser.createModel(new ConverterParams().inputStream(fis)); } @Test public void testToXmlAfterAnnotating() throws Exception { - try { - Model model = new ModelFullIndexed(null); - model.setIdModel("as"); - model.setWidth(10); - model.setHeight(10); - Species speciesAlias = new GenericProtein("id1"); - speciesAlias.setName("ROS"); - RestAnnotationParser rap = new RestAnnotationParser(); - rap.processNotes( - "Symbol: ROS1\r\nName: c-ros oncogene 1 , receptor tyrosine kinase\r\nDescription: RecName: Full=Proto-oncogene tyrosine-protein kinase ROS; EC=2.7.10.1; AltName: Full=Proto-oncogene c-Ros; AltName: Full=Proto-oncogene c-Ros-1; AltName: Full=Receptor tyrosine kinase c-ros oncogene 1; AltName: Full=c-Ros receptor tyrosine kinase; Flags: Precursor;\r\nPrevious Symbols:\r\nSynonyms: ROS, MCF3", - speciesAlias); - model.addElement(speciesAlias); - - GenericProtein alias = new GenericProtein("id"); - alias.setName("ROS2"); - model.addElement(alias); - - SimpleMolecule speciesAlias2 = new SimpleMolecule("id2"); - speciesAlias2.setName("PDK1"); - rap.processNotes( - "Symbol: ROS1\r\nName: c-ros oncogene 1 , receptor tyrosine kinase\r\nDescription: RecName: Full=Proto-oncogene tyrosine-protein kinase ROS; EC=2.7.10.1; AltName: Full=Proto-oncogene c-Ros; AltName: Full=Proto-oncogene c-Ros-1; AltName: Full=Receptor tyrosine kinase c-ros oncogene 1; AltName: Full=c-Ros receptor tyrosine kinase; Flags: Precursor;\r\nPrevious Symbols:\r\nSynonyms: ROS, MCF3", - speciesAlias2); - model.addElement(speciesAlias2); - - SimpleMolecule alias2 = new SimpleMolecule("id3"); - alias2.setName("PDK2"); - model.addElement(alias2); - - Model model2 = serializeModel(model); - - assertEquals(0, modelComparator.compare(model, model2)); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Model model = new ModelFullIndexed(null); + model.setIdModel("as"); + model.setWidth(10); + model.setHeight(10); + Species speciesAlias = new GenericProtein("id1"); + speciesAlias.setName("ROS"); + RestAnnotationParser rap = new RestAnnotationParser(); + rap.processNotes( + "Symbol: ROS1\r\nName: c-ros oncogene 1 , receptor tyrosine kinase\r\nDescription: RecName: Full=Proto-oncogene tyrosine-protein kinase ROS; EC=2.7.10.1; AltName: Full=Proto-oncogene c-Ros; AltName: Full=Proto-oncogene c-Ros-1; AltName: Full=Receptor tyrosine kinase c-ros oncogene 1; AltName: Full=c-Ros receptor tyrosine kinase; Flags: Precursor;\r\nPrevious Symbols:\r\nSynonyms: ROS, MCF3", + speciesAlias); + model.addElement(speciesAlias); + + GenericProtein alias = new GenericProtein("id"); + alias.setName("ROS2"); + model.addElement(alias); + + SimpleMolecule speciesAlias2 = new SimpleMolecule("id2"); + speciesAlias2.setName("PDK1"); + rap.processNotes( + "Symbol: ROS1\r\nName: c-ros oncogene 1 , receptor tyrosine kinase\r\nDescription: RecName: Full=Proto-oncogene tyrosine-protein kinase ROS; EC=2.7.10.1; AltName: Full=Proto-oncogene c-Ros; AltName: Full=Proto-oncogene c-Ros-1; AltName: Full=Receptor tyrosine kinase c-ros oncogene 1; AltName: Full=c-Ros receptor tyrosine kinase; Flags: Precursor;\r\nPrevious Symbols:\r\nSynonyms: ROS, MCF3", + speciesAlias2); + model.addElement(speciesAlias2); + + SimpleMolecule alias2 = new SimpleMolecule("id3"); + alias2.setName("PDK2"); + model.addElement(alias2); + + Model model2 = serializeModel(model); + + assertEquals(0, modelComparator.compare(model, model2)); } @Test public void testModelWithNullNotesToXml() throws Exception { - try { - CellDesignerXmlParser parser = new CellDesignerXmlParser(); - Model model = new ModelFullIndexed(null); - model.setWidth(20); - model.setHeight(20); - model.setNotes(null); - model.setIdModel("id"); - String xmlString = parser.model2String(model); - InputStream is = new ByteArrayInputStream(xmlString.getBytes("UTF-8")); + CellDesignerXmlParser parser = new CellDesignerXmlParser(); + Model model = new ModelFullIndexed(null); + model.setWidth(20); + model.setHeight(20); + model.setNotes(null); + model.setIdModel("id"); + String xmlString = parser.model2String(model); + InputStream is = new ByteArrayInputStream(xmlString.getBytes("UTF-8")); - Model model2 = parser.createModel(new ConverterParams().inputStream(is)); + Model model2 = parser.createModel(new ConverterParams().inputStream(is)); - assertNotNull(model2); + assertNotNull(model2); - assertTrue(model2.getNotes() == null || model2.getNotes().isEmpty()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertTrue(model2.getNotes() == null || model2.getNotes().isEmpty()); } @Test public void testExportXmlForEmptyModel() throws Exception { - try { - CellDesignerXmlParser parser = new CellDesignerXmlParser(); - Model model = new ModelFullIndexed(null); - model.setWidth(20); - model.setHeight(20); - model.setNotes(null); - model.setIdModel("id"); - Species alias = new GenericProtein("a"); - alias.setName("AA"); - model.addElement(alias); - - parser.model2String(model); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + CellDesignerXmlParser parser = new CellDesignerXmlParser(); + Model model = new ModelFullIndexed(null); + model.setWidth(20); + model.setHeight(20); + model.setNotes(null); + model.setIdModel("id"); + Species alias = new GenericProtein("a"); + alias.setName("AA"); + model.addElement(alias); + + parser.model2String(model); } @Test public void testExportXmlForEmptyModel2() throws Exception { - try { - CellDesignerXmlParser parser = new CellDesignerXmlParser(); - Model model = new ModelFullIndexed(null); - model.setWidth(20); - model.setHeight(20); - model.setNotes(null); - model.setIdModel("id"); - - parser.model2String(model); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + CellDesignerXmlParser parser = new CellDesignerXmlParser(); + Model model = new ModelFullIndexed(null); + model.setWidth(20); + model.setHeight(20); + model.setNotes(null); + model.setIdModel("id"); + + parser.model2String(model); } @Test public void testExportImportModelWithSpecialCharacterInNotes() throws Exception { - try { - CellDesignerXmlParser parser = new CellDesignerXmlParser(); - Model model = new ModelFullIndexed(null); - model.setWidth(20); - model.setHeight(20); - model.setNotes(">"); - model.setIdModel("id"); - String xmlString = parser.model2String(model); - InputStream is = new ByteArrayInputStream(xmlString.getBytes("UTF-8")); - - Model model2 = parser.createModel(new ConverterParams().inputStream(is)); - - assertNotNull(model2); - - ModelComparator comparator = new ModelComparator(); - assertEquals(0, comparator.compare(model, model2)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + CellDesignerXmlParser parser = new CellDesignerXmlParser(); + Model model = new ModelFullIndexed(null); + model.setWidth(20); + model.setHeight(20); + model.setNotes(">"); + model.setIdModel("id"); + String xmlString = parser.model2String(model); + InputStream is = new ByteArrayInputStream(xmlString.getBytes("UTF-8")); + + Model model2 = parser.createModel(new ConverterParams().inputStream(is)); + + assertNotNull(model2); + + ModelComparator comparator = new ModelComparator(); + assertEquals(0, comparator.compare(model, model2)); } @Test public void testHomodimerSpecies() throws Exception { - try { - CellDesignerXmlParser parser = new CellDesignerXmlParser(); - FileInputStream fis = new FileInputStream("testFiles/homodimer.xml"); - Model model = parser.createModel(new ConverterParams().inputStream(fis)); - for (Element element : model.getElements()) { - if (element instanceof Species) { - assertTrue("Homodimer value for class" + element.getClass() + " not upadted", - ((Species) element).getHomodimer() > 1); - } + CellDesignerXmlParser parser = new CellDesignerXmlParser(); + FileInputStream fis = new FileInputStream("testFiles/homodimer.xml"); + Model model = parser.createModel(new ConverterParams().inputStream(fis)); + for (Element element : model.getElements()) { + if (element instanceof Species) { + assertTrue("Homodimer value for class" + element.getClass() + " not upadted", + ((Species) element).getHomodimer() > 1); } - } catch (Exception e) { - e.printStackTrace(); - throw e; } } @Test public void testReactionWithNegativeCoords() throws Exception { - try { - CellDesignerXmlParser parser = new CellDesignerXmlParser(); - FileInputStream fis = new FileInputStream("testFiles/negativeCoords.xml"); - Model model = parser.createModel(new ConverterParams().inputStream(fis)); - assertTrue(model.getWidth() >= 0); - assertTrue(model.getHeight() >= 0); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + CellDesignerXmlParser parser = new CellDesignerXmlParser(); + FileInputStream fis = new FileInputStream("testFiles/negativeCoords.xml"); + Model model = parser.createModel(new ConverterParams().inputStream(fis)); + assertTrue(model.getWidth() >= 0); + assertTrue(model.getHeight() >= 0); } @Test public void testaAnnotations() throws Exception { - try { - CellDesignerXmlParser cellDesignerXmlParser = new CellDesignerXmlParser(); - Model model = cellDesignerXmlParser - .createModel(new ConverterParams().filename("testFiles/problematic/invalidAlias.xml")); - assertNotNull(model); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + CellDesignerXmlParser cellDesignerXmlParser = new CellDesignerXmlParser(); + Model model = cellDesignerXmlParser + .createModel(new ConverterParams().filename("testFiles/problematic/invalidAlias.xml")); + assertNotNull(model); } @Test public void testProblematicModification() throws Exception { - try { - CellDesignerXmlParser parser = new CellDesignerXmlParser(); - Model model = parser - .createModel(new ConverterParams().filename("testFiles/problematic/problematic_modification.xml")); - assertNotNull(model); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + CellDesignerXmlParser parser = new CellDesignerXmlParser(); + Model model = parser + .createModel(new ConverterParams().filename("testFiles/problematic/problematic_modification.xml")); + assertNotNull(model); } - @Test + @Test(expected = InvalidInputDataExecption.class) public void testInvalidModifierType() throws Exception { - try { - CellDesignerXmlParser parser = new CellDesignerXmlParser(); - parser.createModel(new ConverterParams().filename("testFiles/problematic/problematic_modifier_type.xml")); - fail("Exception expected."); - } catch (InvalidInputDataExecption e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + CellDesignerXmlParser parser = new CellDesignerXmlParser(); + parser.createModel(new ConverterParams().filename("testFiles/problematic/problematic_modifier_type.xml")); } @Test public void testHtmlTagInSymbolName() throws Exception { - try { - CellDesignerXmlParser parser = new CellDesignerXmlParser(); - Model model = parser.createModel(new ConverterParams().filename("testFiles/notes_with_html_coding.xml")); - - Element p = model.getElementByElementId("sa1"); + CellDesignerXmlParser parser = new CellDesignerXmlParser(); + Model model = parser.createModel(new ConverterParams().filename("testFiles/notes_with_html_coding.xml")); - assertEquals(">symbol<", p.getSymbol()); + Element p = model.getElementByElementId("sa1"); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(">symbol<", p.getSymbol()); } @Test public void testModelBound() { - try { - CellDesignerXmlParser parser = new CellDesignerXmlParser(); - - Model model = new ModelFullIndexed(null); - model.setWidth(0); - model.setHeight(0); + CellDesignerXmlParser parser = new CellDesignerXmlParser(); - Rectangle2D bound = parser.getModelBound(model); - assertEquals(0, bound.getWidth(), EPSILON); - assertEquals(0, bound.getHeight(), EPSILON); + Model model = new ModelFullIndexed(null); + model.setWidth(0); + model.setHeight(0); - } catch (Exception e) { - e.printStackTrace(); - fail("Exception occured: " + e.getMessage()); - } + Rectangle2D bound = parser.getModelBound(model); + assertEquals(0, bound.getWidth(), EPSILON); + assertEquals(0, bound.getHeight(), EPSILON); } @Test public void testModelBoundWithLine() { - try { - CellDesignerXmlParser parser = new CellDesignerXmlParser(); + CellDesignerXmlParser parser = new CellDesignerXmlParser(); - Layer layer = new Layer(); - PolylineData line = new PolylineData(new Point2D.Double(2, 3), new Point2D.Double(20, 30)); - layer.addLayerLine(line); + Layer layer = new Layer(); + PolylineData line = new PolylineData(new Point2D.Double(2, 3), new Point2D.Double(20, 30)); + layer.addLayerLine(line); - Model model = new ModelFullIndexed(null); - model.addLayer(layer); - model.setWidth(100); - model.setHeight(100); - - Rectangle2D bound = parser.getModelBound(model); - assertEquals(18, bound.getWidth(), EPSILON); - assertEquals(27, bound.getHeight(), EPSILON); + Model model = new ModelFullIndexed(null); + model.addLayer(layer); + model.setWidth(100); + model.setHeight(100); - } catch (Exception e) { - e.printStackTrace(); - fail("Exception occured: " + e.getMessage()); - } + Rectangle2D bound = parser.getModelBound(model); + assertEquals(18, bound.getWidth(), EPSILON); + assertEquals(27, bound.getHeight(), EPSILON); } @Test public void testModelBoundWithRectangle() { - try { - CellDesignerXmlParser parser = new CellDesignerXmlParser(); + CellDesignerXmlParser parser = new CellDesignerXmlParser(); - Layer layer = new Layer(); - LayerRect rect = new LayerRect(); - rect.setX(10.0); - rect.setY(20.0); - rect.setWidth(30.0); - rect.setHeight(45.0); - layer.addLayerRect(rect); + Layer layer = new Layer(); + LayerRect rect = new LayerRect(); + rect.setX(10.0); + rect.setY(20.0); + rect.setWidth(30.0); + rect.setHeight(45.0); + layer.addLayerRect(rect); - Model model = new ModelFullIndexed(null); - model.addLayer(layer); - model.setWidth(100); - model.setHeight(100); - - Rectangle2D bound = parser.getModelBound(model); - assertEquals(30, bound.getWidth(), EPSILON); - assertEquals(45, bound.getHeight(), EPSILON); + Model model = new ModelFullIndexed(null); + model.addLayer(layer); + model.setWidth(100); + model.setHeight(100); - } catch (Exception e) { - e.printStackTrace(); - fail("Exception occured: " + e.getMessage()); - } + Rectangle2D bound = parser.getModelBound(model); + assertEquals(30, bound.getWidth(), EPSILON); + assertEquals(45, bound.getHeight(), EPSILON); } @Test public void testModelBoundWithOval() { - try { - CellDesignerXmlParser parser = new CellDesignerXmlParser(); + CellDesignerXmlParser parser = new CellDesignerXmlParser(); - Layer layer = new Layer(); - LayerOval oval = new LayerOval(); - oval.setX(11.0); - oval.setY(21.0); - oval.setWidth(31.0); - oval.setHeight(46.0); - layer.addLayerOval(oval); + Layer layer = new Layer(); + LayerOval oval = new LayerOval(); + oval.setX(11.0); + oval.setY(21.0); + oval.setWidth(31.0); + oval.setHeight(46.0); + layer.addLayerOval(oval); - Model model = new ModelFullIndexed(null); - model.addLayer(layer); - model.setWidth(100); - model.setHeight(100); + Model model = new ModelFullIndexed(null); + model.addLayer(layer); + model.setWidth(100); + model.setHeight(100); - Rectangle2D bound = parser.getModelBound(model); - assertEquals(31, bound.getWidth(), EPSILON); - assertEquals(46, bound.getHeight(), EPSILON); - - } catch (Exception e) { - e.printStackTrace(); - fail("Exception occured: " + e.getMessage()); - } + Rectangle2D bound = parser.getModelBound(model); + assertEquals(31, bound.getWidth(), EPSILON); + assertEquals(46, bound.getHeight(), EPSILON); } @Test public void testModelBoundWithText() { - try { - CellDesignerXmlParser parser = new CellDesignerXmlParser(); - - Layer layer = new Layer(); - LayerText text = new LayerText(); - text.setX(12.0); - text.setY(31.0); - text.setWidth(56.0); - text.setHeight(52.0); - layer.addLayerText(text); + CellDesignerXmlParser parser = new CellDesignerXmlParser(); - Model model = new ModelFullIndexed(null); - model.addLayer(layer); - model.setWidth(100); - model.setHeight(100); + Layer layer = new Layer(); + LayerText text = new LayerText(); + text.setX(12.0); + text.setY(31.0); + text.setWidth(56.0); + text.setHeight(52.0); + layer.addLayerText(text); - Rectangle2D bound = parser.getModelBound(model); - assertEquals(56, bound.getWidth(), EPSILON); - assertEquals(52, bound.getHeight(), EPSILON); + Model model = new ModelFullIndexed(null); + model.addLayer(layer); + model.setWidth(100); + model.setHeight(100); - } catch (Exception e) { - e.printStackTrace(); - fail("Exception occured: " + e.getMessage()); - } + Rectangle2D bound = parser.getModelBound(model); + assertEquals(56, bound.getWidth(), EPSILON); + assertEquals(52, bound.getHeight(), EPSILON); } @Test public void testGetters() { - try { - CellDesignerXmlParser parser = new CellDesignerXmlParser(); - assertNotNull(parser.getCommonName()); - assertNotNull(parser.getMimeType()); - assertNotNull(parser.getFileExtension()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + CellDesignerXmlParser parser = new CellDesignerXmlParser(); + assertNotNull(parser.getCommonName()); + assertNotNull(parser.getMimeType()); + assertNotNull(parser.getFileExtension()); } @Test public void testToXmlWithGene() throws Exception { - try { - CellDesignerXmlParser parser = new CellDesignerXmlParser(); - Model model = new ModelFullIndexed(null); - model.setWidth(100); - model.setHeight(100); - Gene gene = new Gene("gene_id_1"); - gene.setName("geneNAME"); - model.addElement(gene); - String xmlString = parser.model2String(model); - assertTrue(xmlString.contains("gene_id_1")); - assertTrue(xmlString.contains("geneNAME")); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + CellDesignerXmlParser parser = new CellDesignerXmlParser(); + Model model = new ModelFullIndexed(null); + model.setWidth(100); + model.setHeight(100); + Gene gene = new Gene("gene_id_1"); + gene.setName("geneNAME"); + model.addElement(gene); + String xmlString = parser.model2String(model); + assertTrue(xmlString.contains("gene_id_1")); + assertTrue(xmlString.contains("geneNAME")); } @Test public void testToInputString() throws Exception { - try { - CellDesignerXmlParser parser = new CellDesignerXmlParser(); - Model model = new ModelFullIndexed(null); - model.setWidth(100); - model.setHeight(100); - InputStream is = parser.model2InputStream(model); - BufferedReader in = new BufferedReader(new InputStreamReader(is)); - String str = in.readLine(); - assertNotNull(str); - assertFalse(str.isEmpty()); - is.close(); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + CellDesignerXmlParser parser = new CellDesignerXmlParser(); + Model model = new ModelFullIndexed(null); + model.setWidth(100); + model.setHeight(100); + InputStream is = parser.model2InputStream(model); + BufferedReader in = new BufferedReader(new InputStreamReader(is)); + String str = in.readLine(); + assertNotNull(str); + assertFalse(str.isEmpty()); + is.close(); } @Test @@ -848,10 +556,6 @@ public class CellDesignerXmlParserTest extends CellDesignerTestFunctions { File file = new File(filename); assertTrue(file.exists()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; } finally { if (new File(filename).exists()) { new File(filename).delete(); @@ -859,296 +563,199 @@ public class CellDesignerXmlParserTest extends CellDesignerTestFunctions { } } - @Test + @Test(expected = InvalidInputDataExecption.class) public void testOpenFromInvalidSpeciesStateFile() throws Exception { - try { - CellDesignerXmlParser parser = new CellDesignerXmlParser(); - parser.createModel(new ConverterParams().filename("testFiles/invalid/sample5.xml")); - fail("Exceptin expected"); - } catch (InvalidInputDataExecption e) { - assertTrue(e.getMessage().contains("Unknown element of celldesigner:listOfStructuralStates")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + CellDesignerXmlParser parser = new CellDesignerXmlParser(); + parser.createModel(new ConverterParams().filename("testFiles/invalid/sample5.xml")); } - @Test + @Test(expected = InvalidInputDataExecption.class) public void testOpenFromInvalidSpeciesStateFile2() throws Exception { - try { - CellDesignerXmlParser parser = new CellDesignerXmlParser(); - parser.createModel(new ConverterParams().filename("testFiles/invalid/sample6.xml")); - fail("Exceptin expected"); - } catch (InvalidInputDataExecption e) { - assertTrue("Invalid message: " + e.getMessage(), - e.getMessage().contains("Unknown element of celldesigner:listOfModifications")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + CellDesignerXmlParser parser = new CellDesignerXmlParser(); + parser.createModel(new ConverterParams().filename("testFiles/invalid/sample6.xml")); } - @Test + @Test(expected = InvalidInputDataExecption.class) public void testOpenFromInvalidSpeciesStateFile3() throws Exception { - try { - CellDesignerXmlParser parser = new CellDesignerXmlParser(); - parser.createModel(new ConverterParams().filename("testFiles/invalid/sample7.xml")); - fail("Exceptin expected"); - } catch (InvalidInputDataExecption e) { - assertTrue("Invalid message: " + e.getMessage(), - e.getMessage().contains("Unknown element of celldesigner:state")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + CellDesignerXmlParser parser = new CellDesignerXmlParser(); + parser.createModel(new ConverterParams().filename("testFiles/invalid/sample7.xml")); } - @Test + @Test(expected = InvalidInputDataExecption.class) public void testOpenFromInvalidSpeciesStateFile5() throws Exception { - try { - CellDesignerXmlParser parser = new CellDesignerXmlParser(); - parser.createModel(new ConverterParams().filename("testFiles/invalid/sample8.xml")); - fail("Exceptin expected"); - } catch (InvalidInputDataExecption e) { - assertTrue("Invalid message: " + e.getMessage(), e.getMessage().contains("Unknown modification state")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + CellDesignerXmlParser parser = new CellDesignerXmlParser(); + parser.createModel(new ConverterParams().filename("testFiles/invalid/sample8.xml")); } - @Test + @Test(expected = InvalidInputDataExecption.class) public void testOpenFromInvalidSpeciesStateFile6() throws Exception { - try { - CellDesignerXmlParser parser = new CellDesignerXmlParser(); - parser.createModel(new ConverterParams().filename("testFiles/invalid/sample9.xml")); - fail("Exceptin expected"); - } catch (InvalidInputDataExecption e) { - assertTrue("Invalid message: " + e.getMessage(), - e.getMessage().contains("Unknown element of celldesigner:modification")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + CellDesignerXmlParser parser = new CellDesignerXmlParser(); + parser.createModel(new ConverterParams().filename("testFiles/invalid/sample9.xml")); } @Test public void testOpenProblematicFile() throws Exception { - try { - CellDesignerXmlParser parser = new CellDesignerXmlParser(); - Model model = parser.createModel(new ConverterParams().filename("testFiles/problematic/problematic_notes.xml")); - Element element = model.getElementByElementId("sa2338"); - assertFalse("Element note cannot contain head html tag", element.getNotes().contains("</head>")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + CellDesignerXmlParser parser = new CellDesignerXmlParser(); + Model model = parser.createModel(new ConverterParams().filename("testFiles/problematic/problematic_notes.xml")); + Element element = model.getElementByElementId("sa2338"); + assertFalse("Element note cannot contain head html tag", element.getNotes().contains("</head>")); } @Test public void testNestedComp() throws Exception { - try { - CellDesignerXmlParser parser = new CellDesignerXmlParser(); - Model model = parser.createModel(new ConverterParams().filename("testFiles/compartment/nested_compartments.xml")); + CellDesignerXmlParser parser = new CellDesignerXmlParser(); + Model model = parser.createModel(new ConverterParams().filename("testFiles/compartment/nested_compartments.xml")); - assertNotNull(model.getElementByElementId("ca2").getCompartment()); - assertNotNull(model.getElementByElementId("sa1").getCompartment()); + assertNotNull(model.getElementByElementId("ca2").getCompartment()); + assertNotNull(model.getElementByElementId("sa1").getCompartment()); - String xml = parser.model2String(model); + String xml = parser.model2String(model); - Model model2 = parser.createModel( - new ConverterParams().inputStream(new ByteArrayInputStream(xml.getBytes(StandardCharsets.UTF_8)))); + Model model2 = parser.createModel( + new ConverterParams().inputStream(new ByteArrayInputStream(xml.getBytes(StandardCharsets.UTF_8)))); - ModelComparator comparator = new ModelComparator(); + ModelComparator comparator = new ModelComparator(); - model.setName(null); - assertEquals(0, comparator.compare(model, model2)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + model.setName(null); + assertEquals(0, comparator.compare(model, model2)); } @Test public void testCompartmentWithNotes() throws Exception { - try { - CellDesignerXmlParser parser = new CellDesignerXmlParser(); - Model model = parser.createModel(new ConverterParams().filename("testFiles/compartment_with_notes.xml")); - model.setName(null); - assertNotNull(model); - String str = parser.model2String(model); - Model model2 = parser.createModel( - new ConverterParams().inputStream(new ByteArrayInputStream(str.getBytes(StandardCharsets.UTF_8)))); - assertEquals(0, new ModelComparator().compare(model, model2)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + CellDesignerXmlParser parser = new CellDesignerXmlParser(); + Model model = parser.createModel(new ConverterParams().filename("testFiles/compartment_with_notes.xml")); + model.setName(null); + assertNotNull(model); + String str = parser.model2String(model); + Model model2 = parser.createModel( + new ConverterParams().inputStream(new ByteArrayInputStream(str.getBytes(StandardCharsets.UTF_8)))); + assertEquals(0, new ModelComparator().compare(model, model2)); } @Test public void testCompartmentWithSubcompartments() throws Exception { - try { - CellDesignerXmlParser parser = new CellDesignerXmlParser(); - Model model = parser.createModel( - new ConverterParams().filename("testFiles/compartment/nested_compartments_in_few_compartments.xml")); - Compartment c3 = model.getElementByElementId("ca3"); - Compartment c4 = model.getElementByElementId("ca4"); - Compartment c1 = model.getElementByElementId("ca1"); - Compartment c2 = model.getElementByElementId("ca2"); - assertEquals("ca1", c3.getCompartment().getElementId()); - assertEquals("ca2", c4.getCompartment().getElementId()); - - assertEquals(1, c1.getElements().size()); - assertEquals(1, c2.getElements().size()); - assertEquals(0, c3.getElements().size()); - assertEquals(0, c4.getElements().size()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + CellDesignerXmlParser parser = new CellDesignerXmlParser(); + Model model = parser.createModel( + new ConverterParams().filename("testFiles/compartment/nested_compartments_in_few_compartments.xml")); + Compartment c3 = model.getElementByElementId("ca3"); + Compartment c4 = model.getElementByElementId("ca4"); + Compartment c1 = model.getElementByElementId("ca1"); + Compartment c2 = model.getElementByElementId("ca2"); + assertEquals("ca1", c3.getCompartment().getElementId()); + assertEquals("ca2", c4.getCompartment().getElementId()); + + assertEquals(1, c1.getElements().size()); + assertEquals(1, c2.getElements().size()); + assertEquals(0, c3.getElements().size()); + assertEquals(0, c4.getElements().size()); } @Test public void testReactionWithStochiometry() throws Exception { - try { - CellDesignerXmlParser parser = new CellDesignerXmlParser(); - Model model = parser.createModel(new ConverterParams().filename("testFiles/stochiometry.xml")); - Reaction reaction = model.getReactionByReactionId("re1"); + CellDesignerXmlParser parser = new CellDesignerXmlParser(); + Model model = parser.createModel(new ConverterParams().filename("testFiles/stochiometry.xml")); + Reaction reaction = model.getReactionByReactionId("re1"); - assertEquals(2.0, reaction.getReactants().get(0).getStoichiometry(), Configuration.EPSILON); - assertNull(reaction.getProducts().get(0).getStoichiometry()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(2.0, reaction.getReactants().get(0).getStoichiometry(), Configuration.EPSILON); + assertNull(reaction.getProducts().get(0).getStoichiometry()); } @Test public void testModelWithSelfReactionToXml() throws Exception { - try { - Model model = new ModelFullIndexed(null); - model.setIdModel("as"); - model.setWidth(10); - model.setHeight(10); - Species protein = new GenericProtein("id1"); - protein.setName("ROS"); - model.addElement(protein); - - Reaction reaction = new StateTransitionReaction(); - reaction.setIdReaction("re1"); - Product product = new Product(protein); - product.setLine(new PolylineData(new Point2D.Double(0, 0), new Point2D.Double(20, 20))); - reaction.addProduct(product); - Reactant reactant = new Reactant(protein); - reactant.setLine(new PolylineData(new Point2D.Double(20, 20), new Point2D.Double(0, 0))); - reaction.addReactant(reactant); - model.addReaction(reaction); + Model model = new ModelFullIndexed(null); + model.setIdModel("as"); + model.setWidth(10); + model.setHeight(10); + Species protein = new GenericProtein("id1"); + protein.setName("ROS"); + model.addElement(protein); - CellDesignerXmlParser parser = new CellDesignerXmlParser(); - String xmlString = parser.model2String(model); + Reaction reaction = new StateTransitionReaction(); + reaction.setIdReaction("re1"); + Product product = new Product(protein); + product.setLine(new PolylineData(new Point2D.Double(0, 0), new Point2D.Double(20, 20))); + reaction.addProduct(product); + Reactant reactant = new Reactant(protein); + reactant.setLine(new PolylineData(new Point2D.Double(20, 20), new Point2D.Double(0, 0))); + reaction.addReactant(reactant); + model.addReaction(reaction); - assertNotNull(xmlString); - assertTrue(xmlString.contains("omitted")); - assertTrue(xmlString.contains("re1")); + CellDesignerXmlParser parser = new CellDesignerXmlParser(); + String xmlString = parser.model2String(model); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertNotNull(xmlString); + assertTrue(xmlString.contains("omitted")); + assertTrue(xmlString.contains("re1")); } @Test public void testSpeciesWithSpecialSynonym() throws Exception { - try { - Model model = new ModelFullIndexed(null); - model.setIdModel("as"); - model.setWidth(10); - model.setHeight(10); - Species protein = new GenericProtein("id1"); - protein.setWidth(10); - protein.setHeight(10); - protein.setName("ROS"); - protein.addSynonym("&"); - model.addElement(protein); - - Model model2 = serializeModel(model); - - assertEquals(0, modelComparator.compare(model, model2)); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Model model = new ModelFullIndexed(null); + model.setIdModel("as"); + model.setWidth(10); + model.setHeight(10); + Species protein = new GenericProtein("id1"); + protein.setWidth(10); + protein.setHeight(10); + protein.setName("ROS"); + protein.addSynonym("&"); + model.addElement(protein); + + Model model2 = serializeModel(model); + + assertEquals(0, modelComparator.compare(model, model2)); } @Test public void testReactionCoordsEqual() throws Exception { - try { - CellDesignerXmlParser parser = new CellDesignerXmlParser(); - Model model = parser.createModel(new ConverterParams().filename("testFiles/reaction_coords_different.xml")); + CellDesignerXmlParser parser = new CellDesignerXmlParser(); + Model model = parser.createModel(new ConverterParams().filename("testFiles/reaction_coords_different.xml")); - String xmlString = parser.model2String(model); - InputStream is = new ByteArrayInputStream(xmlString.getBytes("UTF-8")); + String xmlString = parser.model2String(model); + InputStream is = new ByteArrayInputStream(xmlString.getBytes("UTF-8")); - Model model2 = parser.createModel(new ConverterParams().inputStream(is)); + Model model2 = parser.createModel(new ConverterParams().inputStream(is)); - Reaction r1 = model.getReactions().iterator().next(); - Reaction r2 = model2.getReactions().iterator().next(); + Reaction r1 = model.getReactions().iterator().next(); + Reaction r2 = model2.getReactions().iterator().next(); - List<Line2D> lines1 = r1.getLines(); - List<Line2D> lines2 = r2.getLines(); - for (int i = 0; i < lines1.size(); i++) { - Line2D line1 = lines1.get(i); - Line2D line2 = lines2.get(i); - assertEquals("Distance between points too big:" + line1.getP1() + ";" + line2.getP1(), 0, - line1.getP1().distance(line2.getP1()), Configuration.EPSILON); - assertEquals("Distance between points too big:" + line1.getP2() + ";" + line2.getP2(), 0, - line1.getP2().distance(line2.getP2()), Configuration.EPSILON); - } - } catch (Exception e) { - e.printStackTrace(); - throw e; + List<Line2D> lines1 = r1.getLines(); + List<Line2D> lines2 = r2.getLines(); + for (int i = 0; i < lines1.size(); i++) { + Line2D line1 = lines1.get(i); + Line2D line2 = lines2.get(i); + assertEquals("Distance between points too big:" + line1.getP1() + ";" + line2.getP1(), 0, + line1.getP1().distance(line2.getP1()), Configuration.EPSILON); + assertEquals("Distance between points too big:" + line1.getP2() + ";" + line2.getP2(), 0, + line1.getP2().distance(line2.getP2()), Configuration.EPSILON); } } @Test public void testParseReactionWithColors() throws Exception { - try { - CellDesignerXmlParser parser = new CellDesignerXmlParser(); - Model model = parser.createModel(new ConverterParams().filename("testFiles/reactions/coloring.xml")); + CellDesignerXmlParser parser = new CellDesignerXmlParser(); + Model model = parser.createModel(new ConverterParams().filename("testFiles/reactions/coloring.xml")); - Reaction r1 = model.getReactionByReactionId("re1"); - Set<Color> colors = new HashSet<>(); - for (AbstractNode node : r1.getNodes()) { - colors.add(node.getLine().getColor()); - } - assertEquals("Four different colors were used to draw the reaction", 4, colors.size()); - assertFalse("Black wasn't used in reaction coloring", colors.contains(Color.BLACK)); - } catch (Exception e) { - e.printStackTrace(); - throw e; + Reaction r1 = model.getReactionByReactionId("re1"); + Set<Color> colors = new HashSet<>(); + for (AbstractNode node : r1.getNodes()) { + colors.add(node.getLine().getColor()); } + assertEquals("Four different colors were used to draw the reaction", 4, colors.size()); + assertFalse("Black wasn't used in reaction coloring", colors.contains(Color.BLACK)); } @Test public void testExportReactionWithColors() throws Exception { - try { - CellDesignerXmlParser parser = new CellDesignerXmlParser(); - Model model = parser.createModel(new ConverterParams().filename("testFiles/reactions/coloring.xml")); - - model.setName(null); - assertNotNull(model); - String str = parser.model2String(model); - Model model2 = parser.createModel( - new ConverterParams().inputStream(new ByteArrayInputStream(str.getBytes(StandardCharsets.UTF_8)))); - assertEquals(0, new ModelComparator().compare(model, model2)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + CellDesignerXmlParser parser = new CellDesignerXmlParser(); + Model model = parser.createModel(new ConverterParams().filename("testFiles/reactions/coloring.xml")); + + model.setName(null); + assertNotNull(model); + String str = parser.model2String(model); + Model model2 = parser.createModel( + new ConverterParams().inputStream(new ByteArrayInputStream(str.getBytes(StandardCharsets.UTF_8)))); + assertEquals(0, new ModelComparator().compare(model, model2)); } } diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/ComplexParserTests.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/ComplexParserTests.java index b11d90a33c33a210652988c51797de27fcf63654..2b3f5b5628fadd59f7b7129541301dba8746d2a9 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/ComplexParserTests.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/ComplexParserTests.java @@ -53,419 +53,283 @@ public class ComplexParserTests extends CellDesignerTestFunctions { @Test public void testParseFunctions() throws Exception { - try { - Model model = getModelForFile("testFiles/function.xml"); + Model model = getModelForFile("testFiles/function.xml"); - assertEquals(1, model.getFunctions().size()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(1, model.getFunctions().size()); } @Test public void testParseModelAnnotations() throws Exception { - try { - Model model = getModelForFile("testFiles/model_with_annotations.xml"); - - assertEquals(2, model.getMiriamData().size()); + Model model = getModelForFile("testFiles/model_with_annotations.xml"); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(2, model.getMiriamData().size()); } @Test public void testExportModelAnnotations() throws Exception { - try { - Model model = getModelForFile("testFiles/model_with_annotations.xml"); - model.setName(null); - - String xml = new CellDesignerXmlParser().model2String(model); - ByteArrayInputStream bais = new ByteArrayInputStream(xml.getBytes()); - Model model2 = new CellDesignerXmlParser() - .createModel(new ConverterParams().sizeAutoAdjust(false).inputStream(bais)); - - ModelComparator modelComparator = new ModelComparator(); - assertEquals(0, modelComparator.compare(model, model2)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Model model = getModelForFile("testFiles/model_with_annotations.xml"); + model.setName(null); + + String xml = new CellDesignerXmlParser().model2String(model); + ByteArrayInputStream bais = new ByteArrayInputStream(xml.getBytes()); + Model model2 = new CellDesignerXmlParser() + .createModel(new ConverterParams().sizeAutoAdjust(false).inputStream(bais)); + + ModelComparator modelComparator = new ModelComparator(); + assertEquals(0, modelComparator.compare(model, model2)); } @Test public void testParseTextWithBackground() throws Exception { - try { - Model model = getModelForFile("testFiles/layer_text_with_background.xml"); - - Layer layer = model.getLayers().iterator().next(); - LayerText text = layer.getTexts().get(0); - assertFalse(text.getBackgroundColor().equals(Color.LIGHT_GRAY)); - assertFalse(text.getNotes().contains("BackgroundColor")); - text = layer.getTexts().get(1); - assertTrue(text.getBackgroundColor().equals(Color.LIGHT_GRAY)); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Model model = getModelForFile("testFiles/layer_text_with_background.xml"); + + Layer layer = model.getLayers().iterator().next(); + LayerText text = layer.getTexts().get(0); + assertFalse(text.getBackgroundColor().equals(Color.LIGHT_GRAY)); + assertFalse(text.getNotes().contains("BackgroundColor")); + text = layer.getTexts().get(1); + assertTrue(text.getBackgroundColor().equals(Color.LIGHT_GRAY)); } @Test public void testParseParameters() throws Exception { - try { - Model model = getModelForFile("testFiles/parameter.xml"); + Model model = getModelForFile("testFiles/parameter.xml"); - assertEquals(1, model.getParameters().size()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(1, model.getParameters().size()); } @Test public void testParseElementKinetics() throws Exception { - try { - Model model = getModelForFile("testFiles/elements_with_kinetic_data.xml"); - - GenericProtein protein1 = model.getElementByElementId("sa1"); - assertEquals(2.5, protein1.getInitialAmount(), Configuration.EPSILON); - assertTrue("hasOnlySubstance property is not parsed properly", protein1.hasOnlySubstanceUnits()); - assertTrue("boundaryCondition property is not parsed properly", protein1.isBoundaryCondition()); - assertTrue("constant property is not parsed properly", protein1.isConstant()); - assertEquals(SbmlUnitType.GRAM, protein1.getSubstanceUnits()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Model model = getModelForFile("testFiles/elements_with_kinetic_data.xml"); + + GenericProtein protein1 = model.getElementByElementId("sa1"); + assertEquals(2.5, protein1.getInitialAmount(), Configuration.EPSILON); + assertTrue("hasOnlySubstance property is not parsed properly", protein1.hasOnlySubstanceUnits()); + assertTrue("boundaryCondition property is not parsed properly", protein1.isBoundaryCondition()); + assertTrue("constant property is not parsed properly", protein1.isConstant()); + assertEquals(SbmlUnitType.GRAM, protein1.getSubstanceUnits()); } @Test public void testParseAndSerializeKineticsElements() throws Exception { - try { - Model model = getModelForFile("testFiles/elements_with_kinetic_data.xml"); - model.setName(null); - - String xml = new CellDesignerXmlParser().model2String(model); - ByteArrayInputStream bais = new ByteArrayInputStream(xml.getBytes()); - Model model2 = new CellDesignerXmlParser() - .createModel(new ConverterParams().sizeAutoAdjust(false).inputStream(bais)); - - ModelComparator modelComparator = new ModelComparator(); - assertEquals(0, modelComparator.compare(model, model2)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Model model = getModelForFile("testFiles/elements_with_kinetic_data.xml"); + model.setName(null); + + String xml = new CellDesignerXmlParser().model2String(model); + ByteArrayInputStream bais = new ByteArrayInputStream(xml.getBytes()); + Model model2 = new CellDesignerXmlParser() + .createModel(new ConverterParams().sizeAutoAdjust(false).inputStream(bais)); + + ModelComparator modelComparator = new ModelComparator(); + assertEquals(0, modelComparator.compare(model, model2)); } @Test public void testParseAndSerializeKineticsReaction() throws Exception { - try { - Model model = getModelForFile("testFiles/reactions/kinetics.xml"); - model.setName(null); - - String xml = new CellDesignerXmlParser().model2String(model); - ByteArrayInputStream bais = new ByteArrayInputStream(xml.getBytes()); - Model model2 = new CellDesignerXmlParser() - .createModel(new ConverterParams().sizeAutoAdjust(false).inputStream(bais)); - - ModelComparator modelComparator = new ModelComparator(); - assertEquals(0, modelComparator.compare(model, model2)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Model model = getModelForFile("testFiles/reactions/kinetics.xml"); + model.setName(null); + + String xml = new CellDesignerXmlParser().model2String(model); + ByteArrayInputStream bais = new ByteArrayInputStream(xml.getBytes()); + Model model2 = new CellDesignerXmlParser() + .createModel(new ConverterParams().sizeAutoAdjust(false).inputStream(bais)); + + ModelComparator modelComparator = new ModelComparator(); + assertEquals(0, modelComparator.compare(model, model2)); } @Test public void testParseUnits() throws Exception { - try { - Model model = getModelForFile("testFiles/unit.xml"); - - assertEquals(1, model.getUnits().size()); + Model model = getModelForFile("testFiles/unit.xml"); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(1, model.getUnits().size()); } @Test public void testParseCompartmens() throws Exception { - Model model; - try { - model = getModelForFile("testFiles/reactions/centeredAnchorInModifier.xml"); - - assertEquals(0, model.getCompartments().size()); + Model model = getModelForFile("testFiles/reactions/centeredAnchorInModifier.xml"); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, model.getCompartments().size()); } @Test public void testParseBubbles() throws Exception { - Model model; - try { - model = getModelForFile("testFiles/bubbles.xml"); - - Element species = model.getElementByElementId("sa6"); - assertNotNull(species); - Protein protein = (Protein) species; - assertTrue(protein.getModificationResidues().size() > 0); - assertNotNull(protein.getStructuralState()); - assertFalse(protein.getStructuralState().equals("")); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Model model = getModelForFile("testFiles/bubbles.xml"); + + Element species = model.getElementByElementId("sa6"); + assertNotNull(species); + Protein protein = (Protein) species; + assertTrue(protein.getModificationResidues().size() > 0); + assertNotNull(protein.getStructuralState()); + assertFalse(protein.getStructuralState().equals("")); } @Test public void testParseCompartmensRelation() throws Exception { - Model model; - try { - model = getModelForFile("testFiles/problematic/elements_in_compartments.xml"); - - List<Element> aliases = new ArrayList<>(); - aliases.add(model.getElementByElementId("csa3")); - aliases.add(model.getElementByElementId("csa4")); - aliases.add(model.getElementByElementId("csa5")); - aliases.add(model.getElementByElementId("csa6")); - aliases.add(model.getElementByElementId("sa3")); - aliases.add(model.getElementByElementId("sa5")); - aliases.add(model.getElementByElementId("sa6")); - aliases.add(model.getElementByElementId("sa7")); - aliases.add(model.getElementByElementId("sa8")); - aliases.add(model.getElementByElementId("sa9")); - aliases.add(model.getElementByElementId("sa10")); - aliases.add(model.getElementByElementId("sa11")); - aliases.add(model.getElementByElementId("sa12")); - aliases.add(model.getElementByElementId("sa13")); - aliases.add(model.getElementByElementId("sa14")); - aliases.add(model.getElementByElementId("sa15")); - aliases.add(model.getElementByElementId("sa16")); - aliases.add(model.getElementByElementId("sa17")); - aliases.add(model.getElementByElementId("sa18")); - aliases.add(model.getElementByElementId("sa19")); - aliases.add(model.getElementByElementId("sa20")); - for (Element alias : aliases) { - assertNotNull(eu.getElementTag(alias) + " does not contain info about compartment", alias.getCompartment()); - } - - } catch (Exception e) { - e.printStackTrace(); - throw e; + Model model = getModelForFile("testFiles/problematic/elements_in_compartments.xml"); + + List<Element> aliases = new ArrayList<>(); + aliases.add(model.getElementByElementId("csa3")); + aliases.add(model.getElementByElementId("csa4")); + aliases.add(model.getElementByElementId("csa5")); + aliases.add(model.getElementByElementId("csa6")); + aliases.add(model.getElementByElementId("sa3")); + aliases.add(model.getElementByElementId("sa5")); + aliases.add(model.getElementByElementId("sa6")); + aliases.add(model.getElementByElementId("sa7")); + aliases.add(model.getElementByElementId("sa8")); + aliases.add(model.getElementByElementId("sa9")); + aliases.add(model.getElementByElementId("sa10")); + aliases.add(model.getElementByElementId("sa11")); + aliases.add(model.getElementByElementId("sa12")); + aliases.add(model.getElementByElementId("sa13")); + aliases.add(model.getElementByElementId("sa14")); + aliases.add(model.getElementByElementId("sa15")); + aliases.add(model.getElementByElementId("sa16")); + aliases.add(model.getElementByElementId("sa17")); + aliases.add(model.getElementByElementId("sa18")); + aliases.add(model.getElementByElementId("sa19")); + aliases.add(model.getElementByElementId("sa20")); + for (Element alias : aliases) { + assertNotNull(eu.getElementTag(alias) + " does not contain info about compartment", alias.getCompartment()); } } @Test public void testParseProteins() throws Exception { - Model model; - try { - model = getModelForFile("testFiles/problematic/acetyled_protein.xml"); - - Set<ModificationState> residues = new HashSet<>(); - for (Element element : model.getElements()) { - if (element instanceof Species) { - Protein protein = (Protein) element; - for (ModificationResidue mr : protein.getModificationResidues()) { - if (mr instanceof AbstractSiteModification) { - residues.add(((AbstractSiteModification) mr).getState()); - } + Model model = getModelForFile("testFiles/problematic/acetyled_protein.xml"); + + Set<ModificationState> residues = new HashSet<>(); + for (Element element : model.getElements()) { + if (element instanceof Species) { + Protein protein = (Protein) element; + for (ModificationResidue mr : protein.getModificationResidues()) { + if (mr instanceof AbstractSiteModification) { + residues.add(((AbstractSiteModification) mr).getState()); } } } - // we have a protein which is acetylated and not acetylated so two types - // of residues - assertEquals(2, residues.size()); - - AbstractSiteModification modification = (AbstractSiteModification) ((Protein) model.getElementByElementId("sa2")) - .getModificationResidues().get(0); - assertEquals(ModificationState.ACETYLATED, modification.getState()); - } catch (Exception e) { - e.printStackTrace(); - throw e; } + // we have a protein which is acetylated and not acetylated so two types + // of residues + assertEquals(2, residues.size()); + + AbstractSiteModification modification = (AbstractSiteModification) ((Protein) model.getElementByElementId("sa2")) + .getModificationResidues().get(0); + assertEquals(ModificationState.ACETYLATED, modification.getState()); } @Test public void testNotesComplexesInNested() throws Exception { - Model model; - try { - model = getModelForFile("testFiles/includedSpecies.xml"); - Element species = model.getElementByElementId("sa1"); - assertNotNull(species); - assertNotNull(species.getNotes()); - assertTrue("Wrong notes: " + species.getNotes(), species.getNotes().contains("hello world")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Model model = getModelForFile("testFiles/includedSpecies.xml"); + Element species = model.getElementByElementId("sa1"); + assertNotNull(species); + assertNotNull(species.getNotes()); + assertTrue("Wrong notes: " + species.getNotes(), species.getNotes().contains("hello world")); } @Test public void testHypotheticalComplex() throws Exception { - Model model; - try { - model = getModelForFile("testFiles/problematic/hypothetical_complex.xml"); - Complex species = (Complex) model.getElementByElementId("csa1"); - assertTrue(species.isHypothetical()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Model model = getModelForFile("testFiles/problematic/hypothetical_complex.xml"); + Complex species = (Complex) model.getElementByElementId("csa1"); + assertTrue(species.isHypothetical()); } @Test public void testProblematicAcetylation() throws Exception { - Model model; - try { - model = getModelForFile("testFiles/problematic/problematic_acetylation.xml"); - Protein p1 = (Protein) model.getElementByElementId("sa73"); - Protein p2 = (Protein) model.getElementByElementId("sa27"); - assertEquals(ModificationState.ACETYLATED, ((Residue) p1.getModificationResidues().get(0)).getState()); - assertFalse(ModificationState.ACETYLATED.equals(((Residue) p2.getModificationResidues().get(0)).getState())); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Model model = getModelForFile("testFiles/problematic/problematic_acetylation.xml"); + Protein p1 = (Protein) model.getElementByElementId("sa73"); + Protein p2 = (Protein) model.getElementByElementId("sa27"); + assertEquals(ModificationState.ACETYLATED, ((Residue) p1.getModificationResidues().get(0)).getState()); + assertFalse(ModificationState.ACETYLATED.equals(((Residue) p2.getModificationResidues().get(0)).getState())); } @Test public void testDuplicateMiriam() throws Exception { - Model model; - try { - model = getModelForFile("testFiles/problematic/duplicated_miriam.xml"); - Protein p1 = (Protein) model.getElementByElementId("sa1"); - Set<String> ids = new HashSet<>(); - - assertTrue(p1.getMiriamData().size() > 0); - for (MiriamData md : p1.getMiriamData()) { - if (md.getDataType().equals(MiriamType.PUBMED)) { - assertFalse("Protein contains double pubmed annotation for pubmed id: " + md.getResource(), - ids.contains(md.getResource())); - ids.add(md.getResource()); - } + Model model = getModelForFile("testFiles/problematic/duplicated_miriam.xml"); + Protein p1 = (Protein) model.getElementByElementId("sa1"); + Set<String> ids = new HashSet<>(); + + assertTrue(p1.getMiriamData().size() > 0); + for (MiriamData md : p1.getMiriamData()) { + if (md.getDataType().equals(MiriamType.PUBMED)) { + assertFalse("Protein contains double pubmed annotation for pubmed id: " + md.getResource(), + ids.contains(md.getResource())); + ids.add(md.getResource()); } - assertTrue(ids.size() > 0); - assertEquals(2, getWarnings().size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; } + assertTrue(ids.size() > 0); + assertEquals(2, getWarnings().size()); } @Test public void testKappaInDescription() throws Exception { - try { - Model model = getModelForFile("testFiles/problematic/kappa_example.xml"); - - Element species = model.getElementByElementId("sa1"); + Model model = getModelForFile("testFiles/problematic/kappa_example.xml"); - assertFalse(species.getName().toLowerCase().contains("kappa")); + Element species = model.getElementByElementId("sa1"); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertFalse(species.getName().toLowerCase().contains("kappa")); } @Test public void testMissingXmlNodes() throws Exception { - try { - Model model = getModelForFile("testFiles/missing_xml_nodes.xml"); - - assertTrue(((Species) model.getElementByElementId("sa3")).isHypothetical()); - assertTrue(((Species) model.getElementByElementId("sa4")).isHypothetical()); - assertTrue(((Species) model.getElementByElementId("sa5")).isHypothetical()); + Model model = getModelForFile("testFiles/missing_xml_nodes.xml"); - assertFalse(((Species) model.getElementByElementId("sa12")).isHypothetical()); - assertFalse(((Species) model.getElementByElementId("sa13")).isHypothetical()); - assertFalse(((Species) model.getElementByElementId("sa14")).isHypothetical()); - assertFalse(((Species) model.getElementByElementId("sa15")).isHypothetical()); + assertTrue(((Species) model.getElementByElementId("sa3")).isHypothetical()); + assertTrue(((Species) model.getElementByElementId("sa4")).isHypothetical()); + assertTrue(((Species) model.getElementByElementId("sa5")).isHypothetical()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertFalse(((Species) model.getElementByElementId("sa12")).isHypothetical()); + assertFalse(((Species) model.getElementByElementId("sa13")).isHypothetical()); + assertFalse(((Species) model.getElementByElementId("sa14")).isHypothetical()); + assertFalse(((Species) model.getElementByElementId("sa15")).isHypothetical()); } @Test public void testParsingSpecialCharactersInName() throws Exception { - try { - Model model = new ModelFullIndexed(null); - model.setIdModel("as"); - model.setWidth(100); - model.setHeight(100); - GenericProtein alias = new GenericProtein("aid"); - alias.setName("name & no-name"); - model.addElement(alias); + Model model = new ModelFullIndexed(null); + model.setIdModel("as"); + model.setWidth(100); + model.setHeight(100); + GenericProtein alias = new GenericProtein("aid"); + alias.setName("name & no-name"); + model.addElement(alias); - Model model2 = serializeModel(model); + Model model2 = serializeModel(model); - ModelComparator comparator = new ModelComparator(); + ModelComparator comparator = new ModelComparator(); - assertEquals(0, comparator.compare(model, model2)); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, comparator.compare(model, model2)); } @Test public void testParsingEndLineInName() throws Exception { - try { - Model model = new ModelFullIndexed(null); - model.setIdModel("as"); - model.setWidth(100); - model.setHeight(100); - GenericProtein alias = new GenericProtein("aid"); - alias.setName("name\rno-name"); - model.addElement(alias); + Model model = new ModelFullIndexed(null); + model.setIdModel("as"); + model.setWidth(100); + model.setHeight(100); + GenericProtein alias = new GenericProtein("aid"); + alias.setName("name\rno-name"); + model.addElement(alias); - Model model2 = serializeModel(model); + Model model2 = serializeModel(model); - ModelComparator comparator = new ModelComparator(); + ModelComparator comparator = new ModelComparator(); - assertEquals(0, comparator.compare(model, model2)); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, comparator.compare(model, model2)); } @Test public void testWarningInParser() throws Exception { - try { - getModelForFile("testFiles/problematic/invalid_elements_name.xml"); - assertTrue(getWarnings().size() > 0); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + getModelForFile("testFiles/problematic/invalid_elements_name.xml"); + assertTrue(getWarnings().size() > 0); } @Test public void testExportVcard() throws Exception { - try { - CellDesignerXmlParser parser = new CellDesignerXmlParser(); - Model model = parser.createModel(new ConverterParams().filename("testFiles/model_with_vcard.xml")); - testXmlSerialization(model); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + CellDesignerXmlParser parser = new CellDesignerXmlParser(); + Model model = parser.createModel(new ConverterParams().filename("testFiles/model_with_vcard.xml")); + testXmlSerialization(model); } } diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/LayerXmlParserTest.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/LayerXmlParserTest.java index 6c40043d8a5260b75ccebc2fe670260de792c720..efd8836919613e15090568af91c17e32ab83e697 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/LayerXmlParserTest.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/LayerXmlParserTest.java @@ -1,34 +1,21 @@ package lcsb.mapviewer.converter.model.celldesigner; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import java.awt.Color; import java.awt.geom.Rectangle2D; import java.util.Collection; -import org.apache.logging.log4j.*; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.junit.*; import org.w3c.dom.Node; import lcsb.mapviewer.common.exception.InvalidXmlSchemaException; import lcsb.mapviewer.model.graphics.PolylineData; import lcsb.mapviewer.model.graphics.PolylineDataComparator; import lcsb.mapviewer.model.map.layout.ElementGroup; -import lcsb.mapviewer.model.map.layout.graphics.Layer; -import lcsb.mapviewer.model.map.layout.graphics.LayerComparator; -import lcsb.mapviewer.model.map.layout.graphics.LayerOval; -import lcsb.mapviewer.model.map.layout.graphics.LayerOvalComparator; -import lcsb.mapviewer.model.map.layout.graphics.LayerRect; -import lcsb.mapviewer.model.map.layout.graphics.LayerRectComparator; -import lcsb.mapviewer.model.map.layout.graphics.LayerText; -import lcsb.mapviewer.model.map.layout.graphics.LayerTextComparator; +import lcsb.mapviewer.model.map.layout.graphics.*; import lcsb.mapviewer.model.map.model.Model; import lcsb.mapviewer.model.map.model.ModelFullIndexed; import lcsb.mapviewer.model.map.species.GenericProtein; @@ -50,489 +37,285 @@ public class LayerXmlParserTest extends CellDesignerTestFunctions { @Test public void testParseLayers() throws Exception { LayerComparator comparator = new LayerComparator(); - try { - String xmlString = readFile("testFiles/xmlNodeTestExamples/layer_collection.xml"); - Node node = getNodeFromXmlString(xmlString); - Collection<Layer> layers = parser.parseLayers(node); - assertNotNull(layers); - assertEquals(1, layers.size()); - - xmlString = parser.layerCollectionToXml(layers); - node = getNodeFromXmlString(xmlString); - Collection<Layer> layers2 = parser.parseLayers(node); - assertNotNull(layers2); - assertEquals(1, layers2.size()); - assertEquals(0, comparator.compare(layers.iterator().next(), layers2.iterator().next())); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String xmlString = readFile("testFiles/xmlNodeTestExamples/layer_collection.xml"); + Node node = getNodeFromXmlString(xmlString); + Collection<Layer> layers = parser.parseLayers(node); + assertNotNull(layers); + assertEquals(1, layers.size()); + + xmlString = parser.layerCollectionToXml(layers); + node = getNodeFromXmlString(xmlString); + Collection<Layer> layers2 = parser.parseLayers(node); + assertNotNull(layers2); + assertEquals(1, layers2.size()); + assertEquals(0, comparator.compare(layers.iterator().next(), layers2.iterator().next())); } - @Test + @Test(expected = InvalidXmlSchemaException.class) public void testParseInvalidLayers() throws Exception { - try { - String xmlString = readFile("testFiles/invalid/layer_collection.xml"); - Node node = getNodeFromXmlString(xmlString); - parser.parseLayers(node); - fail("Exception expected"); - } catch (InvalidXmlSchemaException e) { - assertTrue(e.getMessage().contains("Unknown element of celldesigner:listOfLayers")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String xmlString = readFile("testFiles/invalid/layer_collection.xml"); + Node node = getNodeFromXmlString(xmlString); + parser.parseLayers(node); } @Test public void testParseBlockDiagrams() throws Exception { - try { - Model model = new ModelFullIndexed(null); - String xmlString = readFile("testFiles/xmlNodeTestExamples/block_diagrams.xml"); - Node node = getNodeFromXmlString(xmlString); - parser.parseBlocks(model, node); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Model model = new ModelFullIndexed(null); + String xmlString = readFile("testFiles/xmlNodeTestExamples/block_diagrams.xml"); + Node node = getNodeFromXmlString(xmlString); + parser.parseBlocks(model, node); } - @Test + @Test(expected = InvalidXmlSchemaException.class) public void testParseInvalidBlockDiagrams() throws Exception { - try { - Model model = new ModelFullIndexed(null); - String xmlString = readFile("testFiles/invalid/block_diagrams.xml"); - Node node = getNodeFromXmlString(xmlString); - parser.parseBlocks(model, node); - fail("Exception expected"); - } catch (InvalidXmlSchemaException e) { - assertTrue(e.getMessage().contains("Unknown element of celldesigner:listOfBlockDiagrams")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Model model = new ModelFullIndexed(null); + String xmlString = readFile("testFiles/invalid/block_diagrams.xml"); + Node node = getNodeFromXmlString(xmlString); + parser.parseBlocks(model, node); } - @Test + @Test(expected = InvalidXmlSchemaException.class) public void testParseInvalidGroups() throws Exception { - try { - Model model = new ModelFullIndexed(null); - String xmlString = readFile("testFiles/invalid/group_collection.xml"); - Node node = getNodeFromXmlString(xmlString); - parser.parseGroups(model, node); - fail("Exception expected"); - } catch (InvalidXmlSchemaException e) { - assertTrue(e.getMessage().contains("Unknown element of celldesigner:listOfGroups")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Model model = new ModelFullIndexed(null); + String xmlString = readFile("testFiles/invalid/group_collection.xml"); + Node node = getNodeFromXmlString(xmlString); + parser.parseGroups(model, node); } - @Test + @Test(expected = InvalidGroupException.class) public void testParseInvalidGroups2() throws Exception { - try { - Model model = new ModelFullIndexed(null); - String xmlString = readFile("testFiles/invalid/group_collection2.xml"); - Node node = getNodeFromXmlString(xmlString); - parser.parseGroups(model, node); - fail("Exception expected"); - } catch (InvalidGroupException e) { - assertTrue(e.getMessage().contains("such alias doesn't exist in the model")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Model model = new ModelFullIndexed(null); + String xmlString = readFile("testFiles/invalid/group_collection2.xml"); + Node node = getNodeFromXmlString(xmlString); + parser.parseGroups(model, node); } - @Test + @Test(expected = InvalidXmlSchemaException.class) public void testParseInvalidGroups3() throws Exception { - try { - Model model = new ModelFullIndexed(null); - GenericProtein alias = new GenericProtein("sa1"); - model.addElement(alias); - - String xmlString = readFile("testFiles/invalid/group_collection3.xml"); - Node node = getNodeFromXmlString(xmlString); - parser.parseGroups(model, node); - fail("Exception expected"); - } catch (InvalidXmlSchemaException e) { - assertTrue(e.getMessage().contains("Unknown element of celldesigner:group")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Model model = new ModelFullIndexed(null); + GenericProtein alias = new GenericProtein("sa1"); + model.addElement(alias); + + String xmlString = readFile("testFiles/invalid/group_collection3.xml"); + Node node = getNodeFromXmlString(xmlString); + parser.parseGroups(model, node); } @Test public void testGetLayer() throws Exception { LayerComparator comparator = new LayerComparator(); - try { - String xmlString = readFile("testFiles/xmlNodeTestExamples/layer.xml"); - Node node = getNodeFromXmlString(xmlString); - Layer layer = parser.getLayer(node); - assertNotNull(layer); + String xmlString = readFile("testFiles/xmlNodeTestExamples/layer.xml"); + Node node = getNodeFromXmlString(xmlString); + Layer layer = parser.getLayer(node); + assertNotNull(layer); - xmlString = parser.layerToXml(layer); - node = getNodeFromXmlString(xmlString); - Layer layers2 = parser.getLayer(node); - assertNotNull(layers2); - assertEquals(0, comparator.compare(layer, layers2)); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + xmlString = parser.layerToXml(layer); + node = getNodeFromXmlString(xmlString); + Layer layers2 = parser.getLayer(node); + assertNotNull(layers2); + assertEquals(0, comparator.compare(layer, layers2)); } - @Test + @Test(expected = InvalidXmlSchemaException.class) public void testParseInvalidLayer() throws Exception { - try { - String xmlString = readFile("testFiles/invalid/layer.xml"); - Node node = getNodeFromXmlString(xmlString); - parser.getLayer(node); - fail("Exception expected"); - } catch (InvalidXmlSchemaException e) { - assertTrue(e.getMessage().contains("Unknown element of celldesigner:listOfTexts")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String xmlString = readFile("testFiles/invalid/layer.xml"); + Node node = getNodeFromXmlString(xmlString); + parser.getLayer(node); } - @Test + @Test(expected = InvalidXmlSchemaException.class) public void testParseInvalidLayer2() throws Exception { - try { - String xmlString = readFile("testFiles/invalid/layer2.xml"); - Node node = getNodeFromXmlString(xmlString); - parser.getLayer(node); - fail("Exception expected"); - } catch (InvalidXmlSchemaException e) { - assertTrue(e.getMessage().contains("Unknown celldesigner:layerCompartmentAlias type")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String xmlString = readFile("testFiles/invalid/layer2.xml"); + Node node = getNodeFromXmlString(xmlString); + parser.getLayer(node); } - @Test + @Test(expected = InvalidXmlSchemaException.class) public void testParseInvalidLayer3() throws Exception { - try { - String xmlString = readFile("testFiles/invalid/layer3.xml"); - Node node = getNodeFromXmlString(xmlString); - parser.getLayer(node); - fail("Exception expected"); - } catch (InvalidXmlSchemaException e) { - assertTrue(e.getMessage().contains("Unknown element of celldesigner:listOfSquares")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String xmlString = readFile("testFiles/invalid/layer3.xml"); + Node node = getNodeFromXmlString(xmlString); + parser.getLayer(node); } - @Test + @Test(expected = InvalidXmlSchemaException.class) public void testParseInvalidLayer4() throws Exception { - try { - String xmlString = readFile("testFiles/invalid/layer4.xml"); - Node node = getNodeFromXmlString(xmlString); - parser.getLayer(node); - fail("Exception expected"); - } catch (InvalidXmlSchemaException e) { - assertTrue(e.getMessage().contains("Unknown element of celldesigner:listOfFreeLines")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String xmlString = readFile("testFiles/invalid/layer4.xml"); + Node node = getNodeFromXmlString(xmlString); + parser.getLayer(node); } - @Test + @Test(expected = InvalidXmlSchemaException.class) public void testParseInvalidLayer5() throws Exception { - try { - String xmlString = readFile("testFiles/invalid/layer5.xml"); - Node node = getNodeFromXmlString(xmlString); - parser.getLayer(node); - fail("Exception expected"); - } catch (InvalidXmlSchemaException e) { - assertTrue(e.getMessage().contains("Unknown element of celldesigner:layer")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String xmlString = readFile("testFiles/invalid/layer5.xml"); + Node node = getNodeFromXmlString(xmlString); + parser.getLayer(node); } @Test public void testGetLayerRect() throws Exception { - try { - LayerRectComparator comparator = new LayerRectComparator(); - String xmlString = readFile("testFiles/xmlNodeTestExamples/layer_square.xml"); - Node node = getNodeFromXmlString(xmlString); - LayerRect layer = parser.getLayerRect(node); - assertNotNull(layer); - - xmlString = parser.layerRectToXml(layer); - node = getNodeFromXmlString(xmlString); - LayerRect layers2 = parser.getLayerRect(node); - assertNotNull(layers2); - assertEquals(0, comparator.compare(layer, layers2)); + LayerRectComparator comparator = new LayerRectComparator(); + String xmlString = readFile("testFiles/xmlNodeTestExamples/layer_square.xml"); + Node node = getNodeFromXmlString(xmlString); + LayerRect layer = parser.getLayerRect(node); + assertNotNull(layer); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + xmlString = parser.layerRectToXml(layer); + node = getNodeFromXmlString(xmlString); + LayerRect layers2 = parser.getLayerRect(node); + assertNotNull(layers2); + assertEquals(0, comparator.compare(layer, layers2)); } - @Test + @Test(expected = InvalidXmlSchemaException.class) public void testParseInvalidLayerRect() throws Exception { - try { - String xmlString = readFile("testFiles/invalid/layer_square.xml"); - Node node = getNodeFromXmlString(xmlString); - parser.getLayerRect(node); - fail("Exception expected"); - } catch (InvalidXmlSchemaException e) { - assertTrue(e.getMessage().contains("Unknown element of celldesigner:layerCompartmentAlias")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String xmlString = readFile("testFiles/invalid/layer_square.xml"); + Node node = getNodeFromXmlString(xmlString); + parser.getLayerRect(node); } @Test - public void testGetLayerLine() { - try { - PolylineDataComparator comparator = new PolylineDataComparator(); - String xmlString = readFile("testFiles/xmlNodeTestExamples/layer_line.xml"); - Node node = getNodeFromXmlString(xmlString); - PolylineData layer = parser.getLayerLine(node); - assertNotNull(layer); - - xmlString = parser.layerLineToXml(layer); - node = getNodeFromXmlString(xmlString); - PolylineData layers2 = parser.getLayerLine(node); - assertNotNull(layers2); - assertEquals(0, comparator.compare(layer, layers2)); - - } catch (Exception e) { - e.printStackTrace(); - fail("Unknown exception"); - } + public void testGetLayerLine() throws Exception { + PolylineDataComparator comparator = new PolylineDataComparator(); + String xmlString = readFile("testFiles/xmlNodeTestExamples/layer_line.xml"); + Node node = getNodeFromXmlString(xmlString); + PolylineData layer = parser.getLayerLine(node); + assertNotNull(layer); + + xmlString = parser.layerLineToXml(layer); + node = getNodeFromXmlString(xmlString); + PolylineData layers2 = parser.getLayerLine(node); + assertNotNull(layers2); + assertEquals(0, comparator.compare(layer, layers2)); } - @Test + @Test(expected = InvalidXmlSchemaException.class) public void testParseInvalidLayerLine() throws Exception { - try { - String xmlString = readFile("testFiles/invalid/layer_line.xml"); - Node node = getNodeFromXmlString(xmlString); - parser.getLayerLine(node); - fail("Exception expected"); - } catch (InvalidXmlSchemaException e) { - assertTrue(e.getMessage().contains("Unknown element of celldesigner:layerFreeLine")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String xmlString = readFile("testFiles/invalid/layer_line.xml"); + Node node = getNodeFromXmlString(xmlString); + parser.getLayerLine(node); } @Test - public void testGetLayerOval() { - try { - LayerOvalComparator comparator = new LayerOvalComparator(); - String xmlString = readFile("testFiles/xmlNodeTestExamples/layer_oval.xml"); - Node node = getNodeFromXmlString(xmlString); - LayerOval layer = parser.getLayerOval(node); - assertNotNull(layer); - - xmlString = parser.layerOvalToXml(layer); - node = getNodeFromXmlString(xmlString); - LayerOval layers2 = parser.getLayerOval(node); - assertNotNull(layers2); - assertEquals(0, comparator.compare(layer, layers2)); - - } catch (Exception e) { - e.printStackTrace(); - fail("Unknown exception"); - } + public void testGetLayerOval() throws Exception { + LayerOvalComparator comparator = new LayerOvalComparator(); + String xmlString = readFile("testFiles/xmlNodeTestExamples/layer_oval.xml"); + Node node = getNodeFromXmlString(xmlString); + LayerOval layer = parser.getLayerOval(node); + assertNotNull(layer); + + xmlString = parser.layerOvalToXml(layer); + node = getNodeFromXmlString(xmlString); + LayerOval layers2 = parser.getLayerOval(node); + assertNotNull(layers2); + assertEquals(0, comparator.compare(layer, layers2)); } - @Test + @Test(expected = InvalidXmlSchemaException.class) public void testParseInvalidLayerOval() throws Exception { - try { - String xmlString = readFile("testFiles/invalid/layer_oval.xml"); - Node node = getNodeFromXmlString(xmlString); - parser.getLayerOval(node); - fail("Exception expected"); - - } catch (InvalidXmlSchemaException e) { - assertTrue(e.getMessage().contains("Unknown element of celldesigner:layerCompartmentAlias")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String xmlString = readFile("testFiles/invalid/layer_oval.xml"); + Node node = getNodeFromXmlString(xmlString); + parser.getLayerOval(node); } @Test - public void testGetLayerText() { - try { - LayerTextComparator comparator = new LayerTextComparator(); - String xmlString = readFile("testFiles/xmlNodeTestExamples/layer_text.xml"); - Node node = getNodeFromXmlString(xmlString); - LayerText layer = parser.getLayerText(node); - assertNotNull(layer); - - xmlString = parser.layerTextToXml(layer); - node = getNodeFromXmlString(xmlString); - LayerText layers2 = parser.getLayerText(node); - assertNotNull(layers2); - assertEquals(0, comparator.compare(layer, layers2)); - - } catch (Exception e) { - e.printStackTrace(); - fail("Unknown exception"); - } + public void testGetLayerText() throws Exception { + LayerTextComparator comparator = new LayerTextComparator(); + String xmlString = readFile("testFiles/xmlNodeTestExamples/layer_text.xml"); + Node node = getNodeFromXmlString(xmlString); + LayerText layer = parser.getLayerText(node); + assertNotNull(layer); + + xmlString = parser.layerTextToXml(layer); + node = getNodeFromXmlString(xmlString); + LayerText layers2 = parser.getLayerText(node); + assertNotNull(layers2); + assertEquals(0, comparator.compare(layer, layers2)); } @Test public void testGetLayerTextWithZIndex() throws Exception { - try { - String xmlString = readFile("testFiles/xmlNodeTestExamples/layer_text_with_z_index.xml"); - Node node = getNodeFromXmlString(xmlString); - LayerText layer = parser.getLayerText(node); - assertEquals((Integer) 19, layer.getZ()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String xmlString = readFile("testFiles/xmlNodeTestExamples/layer_text_with_z_index.xml"); + Node node = getNodeFromXmlString(xmlString); + LayerText layer = parser.getLayerText(node); + assertEquals((Integer) 19, layer.getZ()); } - @Test + @Test(expected = InvalidXmlSchemaException.class) public void testParseInvalidLayerText() throws Exception { - try { - String xmlString = readFile("testFiles/invalid/layer_text.xml"); - Node node = getNodeFromXmlString(xmlString); - parser.getLayerText(node); - fail("Exception expected"); - - } catch (InvalidXmlSchemaException e) { - assertTrue(e.getMessage().contains("Unknown element of celldesigner:layerSpeciesAlias")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String xmlString = readFile("testFiles/invalid/layer_text.xml"); + Node node = getNodeFromXmlString(xmlString); + parser.getLayerText(node); } @Test public void testGetAliasGroup() throws Exception { - try { - Model model = new ModelFullIndexed(null); - Species alias = new GenericProtein("sa1035"); - model.addElement(alias); + Model model = new ModelFullIndexed(null); + Species alias = new GenericProtein("sa1035"); + model.addElement(alias); - alias = new GenericProtein("sa1036"); - model.addElement(alias); + alias = new GenericProtein("sa1036"); + model.addElement(alias); - alias = new GenericProtein("sa1037"); - model.addElement(alias); + alias = new GenericProtein("sa1037"); + model.addElement(alias); - alias = new GenericProtein("sa1038"); - model.addElement(alias); + alias = new GenericProtein("sa1038"); + model.addElement(alias); - String string = "<celldesigner:group id=\"g74\" members=\"sa1035,sa1036,sa1037,sa1038\"/>"; - Node node = getNodeFromXmlString(string); - ElementGroup group = parser.getAliasGroup(node, model); - assertNotNull(group); + String string = "<celldesigner:group id=\"g74\" members=\"sa1035,sa1036,sa1037,sa1038\"/>"; + Node node = getNodeFromXmlString(string); + ElementGroup group = parser.getAliasGroup(node, model); + assertNotNull(group); - assertEquals(4, group.getElements().size()); + assertEquals(4, group.getElements().size()); - assertEquals("g74", group.getIdGroup()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals("g74", group.getIdGroup()); } @Test public void testLayerTextToXml() throws Exception { - try { - LayerText text = new LayerText(new Rectangle2D.Double(1, 2, 3, 4), "DF"); - String xml = parser.layerTextToXml(text); - assertNotNull(xml); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + LayerText text = new LayerText(new Rectangle2D.Double(1, 2, 3, 4), "DF"); + String xml = parser.layerTextToXml(text); + assertNotNull(xml); } @Test public void testExtractBackgroundColor() throws Exception { - try { - Color color = parser.extractBackgroundColor("dcxvxcvxcvx\nBackgroundColor=#ccffcc"); - assertNotNull(color); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Color color = parser.extractBackgroundColor("dcxvxcvxcvx\nBackgroundColor=#ccffcc"); + assertNotNull(color); } @Test public void testExtractNonExistingBackgroundColor() throws Exception { - try { - Color color = parser.extractBackgroundColor("dcxvxcvxcvx\nBackgroundCffcc"); - assertNull(color); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Color color = parser.extractBackgroundColor("dcxvxcvxcvx\nBackgroundCffcc"); + assertNull(color); } @Test public void testRemoveBackgroundColor() throws Exception { - try { - String notes = parser.removeBackgroundColor("dcxvxcvxcvx\nBackgroundColor=#ccffcc"); - assertFalse(notes.contains("BackgroundColor")); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String notes = parser.removeBackgroundColor("dcxvxcvxcvx\nBackgroundColor=#ccffcc"); + assertFalse(notes.contains("BackgroundColor")); } @Test public void testRemoveNonExistingBackgroundColor() throws Exception { - try { - String notes = parser.removeBackgroundColor("dcxvxcvxcvx\nBckgroundColor=#ccffcc"); - assertTrue(notes.contains("dcxvxcvxcvx\nBckgroundColor=#ccffcc")); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String notes = parser.removeBackgroundColor("dcxvxcvxcvx\nBckgroundColor=#ccffcc"); + assertTrue(notes.contains("dcxvxcvxcvx\nBckgroundColor=#ccffcc")); } @Test public void testLayerTextToXmlWithDefaultBackgroundColor() throws Exception { - try { - LayerText text = new LayerText(); - String xml = parser.layerTextToXml(text); - assertFalse(xml.contains("BackgroundColor")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + LayerText text = new LayerText(); + String xml = parser.layerTextToXml(text); + assertFalse(xml.contains("BackgroundColor")); } @Test public void testLayerTextToXmlWithCustomDefaultBackgroundColor() throws Exception { - try { - LayerText text = new LayerText(); - text.setBackgroundColor(Color.BLUE); - String xml = parser.layerTextToXml(text); - assertTrue(xml.contains("BackgroundColor")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + LayerText text = new LayerText(); + text.setBackgroundColor(Color.BLUE); + String xml = parser.layerTextToXml(text); + assertTrue(xml.contains("BackgroundColor")); } } diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/ModificationTest.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/ModificationTest.java index 154ccbef7d995ad305b469c3c98f1ac8bac7725c..70c7d8920e135c192f645369ca807cfd84700331 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/ModificationTest.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/ModificationTest.java @@ -1,29 +1,15 @@ package lcsb.mapviewer.converter.model.celldesigner; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.Assert.*; -import org.apache.logging.log4j.*; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.junit.*; import lcsb.mapviewer.common.Configuration; import lcsb.mapviewer.model.map.model.Model; -import lcsb.mapviewer.model.map.species.AntisenseRna; -import lcsb.mapviewer.model.map.species.Gene; -import lcsb.mapviewer.model.map.species.Protein; -import lcsb.mapviewer.model.map.species.Rna; -import lcsb.mapviewer.model.map.species.field.BindingRegion; -import lcsb.mapviewer.model.map.species.field.CodingRegion; -import lcsb.mapviewer.model.map.species.field.ModificationResidue; -import lcsb.mapviewer.model.map.species.field.ModificationSite; -import lcsb.mapviewer.model.map.species.field.ModificationState; -import lcsb.mapviewer.model.map.species.field.ProteinBindingDomain; -import lcsb.mapviewer.model.map.species.field.RegulatoryRegion; -import lcsb.mapviewer.model.map.species.field.Residue; -import lcsb.mapviewer.model.map.species.field.TranscriptionSite; +import lcsb.mapviewer.model.map.species.*; +import lcsb.mapviewer.model.map.species.field.*; public class ModificationTest extends CellDesignerTestFunctions { Logger logger = LogManager.getLogger(ModificationTest.class); @@ -38,203 +24,150 @@ public class ModificationTest extends CellDesignerTestFunctions { @Test public void testBindingRegion() throws Exception { - try { - Model model = getModelForFile("testFiles/modifications/protein_with_binding_region.xml"); - Protein protein = model.getElementByElementId("sa1"); - assertEquals(1, protein.getModificationResidues().size()); - ModificationResidue residue = protein.getModificationResidues().get(0); - - assertTrue(residue instanceof BindingRegion); - BindingRegion bindingRegion = (BindingRegion) residue; - assertEquals(bindingRegion.getPosition().getX(), protein.getX(), Configuration.EPSILON); - assertTrue(bindingRegion.getWidth() < bindingRegion.getHeight()); - - testXmlSerialization(model); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Model model = getModelForFile("testFiles/modifications/protein_with_binding_region.xml"); + Protein protein = model.getElementByElementId("sa1"); + assertEquals(1, protein.getModificationResidues().size()); + ModificationResidue residue = protein.getModificationResidues().get(0); + + assertTrue(residue instanceof BindingRegion); + BindingRegion bindingRegion = (BindingRegion) residue; + assertEquals(bindingRegion.getPosition().getX(), protein.getX(), Configuration.EPSILON); + assertTrue(bindingRegion.getWidth() < bindingRegion.getHeight()); + + testXmlSerialization(model); } @Test public void testRegulatoryRegion() throws Exception { - try { - Model model = getModelForFile("testFiles/modifications/gene_with_regulatory_region.xml"); - Gene gene = model.getElementByElementId("sa1"); - assertEquals(1, gene.getModificationResidues().size()); - - ModificationResidue residue = gene.getModificationResidues().get(0); - assertTrue(residue instanceof RegulatoryRegion); - RegulatoryRegion bindingRegion = (RegulatoryRegion) residue; - assertEquals(bindingRegion.getPosition().getY(), gene.getY(), Configuration.EPSILON); - assertTrue(bindingRegion.getWidth() > bindingRegion.getHeight()); - - testXmlSerialization(model); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Model model = getModelForFile("testFiles/modifications/gene_with_regulatory_region.xml"); + Gene gene = model.getElementByElementId("sa1"); + assertEquals(1, gene.getModificationResidues().size()); + + ModificationResidue residue = gene.getModificationResidues().get(0); + assertTrue(residue instanceof RegulatoryRegion); + RegulatoryRegion bindingRegion = (RegulatoryRegion) residue; + assertEquals(bindingRegion.getPosition().getY(), gene.getY(), Configuration.EPSILON); + assertTrue(bindingRegion.getWidth() > bindingRegion.getHeight()); + + testXmlSerialization(model); } @Test public void testGeneCodingRegion() throws Exception { - try { - Model model = getModelForFile("testFiles/modifications/gene_with_coding_region.xml"); - Gene gene = model.getElementByElementId("sa1"); - assertEquals(1, gene.getModificationResidues().size()); - - ModificationResidue residue = gene.getModificationResidues().get(0); - assertTrue(residue instanceof CodingRegion); - CodingRegion bindingRegion = (CodingRegion) residue; - assertEquals(bindingRegion.getPosition().getY(), gene.getY(), Configuration.EPSILON); - assertTrue(bindingRegion.getWidth() > bindingRegion.getHeight()); - - testXmlSerialization(model); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Model model = getModelForFile("testFiles/modifications/gene_with_coding_region.xml"); + Gene gene = model.getElementByElementId("sa1"); + assertEquals(1, gene.getModificationResidues().size()); + + ModificationResidue residue = gene.getModificationResidues().get(0); + assertTrue(residue instanceof CodingRegion); + CodingRegion bindingRegion = (CodingRegion) residue; + assertEquals(bindingRegion.getPosition().getY(), gene.getY(), Configuration.EPSILON); + assertTrue(bindingRegion.getWidth() > bindingRegion.getHeight()); + + testXmlSerialization(model); } @Test public void testGeneModificationSite() throws Exception { - try { - Model model = getModelForFile("testFiles/modifications/gene_with_modification_site.xml"); - Gene gene = model.getElementByElementId("sa1"); - assertEquals(1, gene.getModificationResidues().size()); - - ModificationResidue residue = gene.getModificationResidues().get(0); - assertTrue(residue instanceof ModificationSite); - ModificationSite bindingRegion = (ModificationSite) residue; - assertEquals(bindingRegion.getPosition().getY(), gene.getY(), Configuration.EPSILON); - - testXmlSerialization(model); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Model model = getModelForFile("testFiles/modifications/gene_with_modification_site.xml"); + Gene gene = model.getElementByElementId("sa1"); + assertEquals(1, gene.getModificationResidues().size()); + + ModificationResidue residue = gene.getModificationResidues().get(0); + assertTrue(residue instanceof ModificationSite); + ModificationSite bindingRegion = (ModificationSite) residue; + assertEquals(bindingRegion.getPosition().getY(), gene.getY(), Configuration.EPSILON); + + testXmlSerialization(model); } @Test public void testRegulatoryTranscriptionSiteRight() throws Exception { - try { - Model model = getModelForFile("testFiles/modifications/gene_with_transcription_site_right.xml"); - Gene gene = model.getElementByElementId("sa1"); - assertEquals(1, gene.getModificationResidues().size()); - ModificationResidue residue = gene.getModificationResidues().get(0); - - assertTrue(residue instanceof TranscriptionSite); - TranscriptionSite transcriptionSite = (TranscriptionSite) residue; - assertEquals(transcriptionSite.getPosition().getY(), gene.getY(), Configuration.EPSILON); - assertEquals("RIGHT", transcriptionSite.getDirection()); - assertTrue(transcriptionSite.getActive()); - - testXmlSerialization(model); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Model model = getModelForFile("testFiles/modifications/gene_with_transcription_site_right.xml"); + Gene gene = model.getElementByElementId("sa1"); + assertEquals(1, gene.getModificationResidues().size()); + ModificationResidue residue = gene.getModificationResidues().get(0); + + assertTrue(residue instanceof TranscriptionSite); + TranscriptionSite transcriptionSite = (TranscriptionSite) residue; + assertEquals(transcriptionSite.getPosition().getY(), gene.getY(), Configuration.EPSILON); + assertEquals("RIGHT", transcriptionSite.getDirection()); + assertTrue(transcriptionSite.getActive()); + + testXmlSerialization(model); } @Test public void testRegulatoryTranscriptionSiteLeft() throws Exception { - try { - Model model = getModelForFile("testFiles/modifications/gene_with_transcription_site_left.xml"); - Gene gene = model.getElementByElementId("sa1"); - assertEquals(1, gene.getModificationResidues().size()); - ModificationResidue residue = gene.getModificationResidues().get(0); - - assertTrue(residue instanceof TranscriptionSite); - TranscriptionSite transcriptionSite = (TranscriptionSite) residue; - assertEquals(transcriptionSite.getPosition().getY(), gene.getY(), Configuration.EPSILON); - assertEquals("LEFT", transcriptionSite.getDirection()); - assertFalse(transcriptionSite.getActive()); - - testXmlSerialization(model); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Model model = getModelForFile("testFiles/modifications/gene_with_transcription_site_left.xml"); + Gene gene = model.getElementByElementId("sa1"); + assertEquals(1, gene.getModificationResidues().size()); + ModificationResidue residue = gene.getModificationResidues().get(0); + + assertTrue(residue instanceof TranscriptionSite); + TranscriptionSite transcriptionSite = (TranscriptionSite) residue; + assertEquals(transcriptionSite.getPosition().getY(), gene.getY(), Configuration.EPSILON); + assertEquals("LEFT", transcriptionSite.getDirection()); + assertFalse(transcriptionSite.getActive()); + + testXmlSerialization(model); } @Test public void testProtinWithResidues() throws Exception { - try { - Model model = getModelForFile("testFiles/modifications/protein_with_residues.xml"); - Protein protein = (Protein) model.getElementByElementId("sa1"); - assertEquals(14, protein.getModificationResidues().size()); - - ModificationResidue residue = protein.getModificationResidues().get(0); + Model model = getModelForFile("testFiles/modifications/protein_with_residues.xml"); + Protein protein = (Protein) model.getElementByElementId("sa1"); + assertEquals(14, protein.getModificationResidues().size()); - assertTrue(residue instanceof Residue); + ModificationResidue residue = protein.getModificationResidues().get(0); - testXmlSerialization(model); + assertTrue(residue instanceof Residue); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + testXmlSerialization(model); } @Test public void testRnaWithRegion() throws Exception { - try { - Model model = getModelForFile("testFiles/modifications/rna_with_region.xml"); - Rna rna = model.getElementByElementId("sa1"); - assertEquals(1, rna.getRegions().size()); - assertTrue(rna.getRegions().get(0) instanceof CodingRegion); - - rna = model.getElementByElementId("sa2"); - assertEquals(1, rna.getRegions().size()); - assertTrue(rna.getRegions().get(0) instanceof ProteinBindingDomain); - - rna = model.getElementByElementId("sa3"); - assertEquals(1, rna.getRegions().size()); - assertTrue(rna.getRegions().get(0) instanceof ModificationSite); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Model model = getModelForFile("testFiles/modifications/rna_with_region.xml"); + Rna rna = model.getElementByElementId("sa1"); + assertEquals(1, rna.getRegions().size()); + assertTrue(rna.getRegions().get(0) instanceof CodingRegion); + + rna = model.getElementByElementId("sa2"); + assertEquals(1, rna.getRegions().size()); + assertTrue(rna.getRegions().get(0) instanceof ProteinBindingDomain); + + rna = model.getElementByElementId("sa3"); + assertEquals(1, rna.getRegions().size()); + assertTrue(rna.getRegions().get(0) instanceof ModificationSite); } @Test public void testAntisenseRnaWithRegion() throws Exception { - try { - Model model = getModelForFile("testFiles/modifications/antisense_rna_with_region.xml"); - AntisenseRna rna = model.getElementByElementId("sa1"); - assertEquals(1, rna.getRegions().size()); - assertTrue(rna.getRegions().get(0) instanceof CodingRegion); - - rna = model.getElementByElementId("sa2"); - assertEquals(1, rna.getRegions().size()); - assertTrue(rna.getRegions().get(0) instanceof ProteinBindingDomain); - - rna = model.getElementByElementId("sa3"); - assertEquals(1, rna.getRegions().size()); - assertTrue(rna.getRegions().get(0) instanceof ModificationSite); - - rna = model.getElementByElementId("sa4"); - assertEquals(1, rna.getRegions().size()); - assertTrue(rna.getRegions().get(0) instanceof ModificationSite); - ModificationSite modificationSite = (ModificationSite) rna.getRegions().get(0); - assertEquals(ModificationState.PHOSPHORYLATED, modificationSite.getState()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Model model = getModelForFile("testFiles/modifications/antisense_rna_with_region.xml"); + AntisenseRna rna = model.getElementByElementId("sa1"); + assertEquals(1, rna.getRegions().size()); + assertTrue(rna.getRegions().get(0) instanceof CodingRegion); + + rna = model.getElementByElementId("sa2"); + assertEquals(1, rna.getRegions().size()); + assertTrue(rna.getRegions().get(0) instanceof ProteinBindingDomain); + + rna = model.getElementByElementId("sa3"); + assertEquals(1, rna.getRegions().size()); + assertTrue(rna.getRegions().get(0) instanceof ModificationSite); + + rna = model.getElementByElementId("sa4"); + assertEquals(1, rna.getRegions().size()); + assertTrue(rna.getRegions().get(0) instanceof ModificationSite); + ModificationSite modificationSite = (ModificationSite) rna.getRegions().get(0); + assertEquals(ModificationState.PHOSPHORYLATED, modificationSite.getState()); } @Test public void testPhosporylatedProteinToXml() throws Exception { - try { - Model model = getModelForFile("testFiles/problematic/phosphorylated_protein.xml"); - - testXmlSerialization(model); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Model model = getModelForFile("testFiles/problematic/phosphorylated_protein.xml"); + testXmlSerialization(model); } } diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/NestedComplexParsingTests.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/NestedComplexParsingTests.java index aeed1f1a96e57eac33af3b0cb00ee890edccebf5..77be63a3496b6dbe104b8f0e36f78c8fbc019a22 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/NestedComplexParsingTests.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/NestedComplexParsingTests.java @@ -1,17 +1,13 @@ package lcsb.mapviewer.converter.model.celldesigner; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.Assert.*; -import org.apache.logging.log4j.*; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.junit.*; import lcsb.mapviewer.model.map.model.Model; -import lcsb.mapviewer.model.map.species.Complex; -import lcsb.mapviewer.model.map.species.Element; -import lcsb.mapviewer.model.map.species.Species; +import lcsb.mapviewer.model.map.species.*; import lcsb.mapviewer.modelutils.map.ElementUtils; public class NestedComplexParsingTests extends CellDesignerTestFunctions { @@ -38,64 +34,57 @@ public class NestedComplexParsingTests extends CellDesignerTestFunctions { @Test public void testParseCompartmens() throws Exception { - Model model; - try { - model = getModelForFile("testFiles/xmlNodeTestExamples/nested_complex.xml"); - - Element s1 = model.getElementByElementId("csa1"); - Element s2 = model.getElementByElementId("csa2"); - Element s3 = model.getElementByElementId("csa3"); - Element s4 = model.getElementByElementId("csa4"); - Element s5 = model.getElementByElementId("csa5"); - Element s6 = model.getElementByElementId("csa6"); - Element s7 = model.getElementByElementId("sa1"); - Element s8 = model.getElementByElementId("sa2"); - Element s9 = model.getElementByElementId("sa3"); - Element s10 = model.getElementByElementId("sa4"); - Element s11 = model.getElementByElementId("sa5"); - Element s12 = model.getElementByElementId("sa6"); - assertTrue(s1 instanceof Complex); - assertTrue(s2 instanceof Complex); - assertTrue(s3 instanceof Complex); - assertTrue(s4 instanceof Complex); - assertTrue(s5 instanceof Complex); - assertTrue(s6 instanceof Complex); - Complex cs1 = (Complex) s1; - Complex cs2 = (Complex) s2; - Complex cs3 = (Complex) s3; - Complex cs4 = (Complex) s4; - Complex cs5 = (Complex) s5; - Complex cs6 = (Complex) s6; - assertEquals(2, cs1.getElements().size()); - assertEquals(2, cs2.getElements().size()); - assertEquals(0, cs3.getElements().size()); - assertEquals(0, cs4.getElements().size()); - assertEquals(2, cs5.getElements().size()); - assertEquals(3, cs6.getElements().size()); - - assertTrue(cs1.getElements().contains(s9)); - assertTrue(cs1.getElements().contains(s3)); - - assertTrue(cs2.getElements().contains(s7)); - assertTrue(cs2.getElements().contains(s8)); - - assertTrue(cs5.getElements().contains(s10)); - assertTrue(cs5.getElements().contains(s11)); - - assertTrue(cs6.getElements().contains(s4)); - assertTrue(cs6.getElements().contains(s5)); - assertTrue(cs6.getElements().contains(s12)); - - assertEquals(1, cs1.getAllSimpleChildren().size()); - assertEquals(2, cs2.getAllSimpleChildren().size()); - assertEquals(0, cs3.getAllSimpleChildren().size()); - assertEquals(0, cs4.getAllSimpleChildren().size()); - assertEquals(2, cs5.getAllSimpleChildren().size()); - assertEquals(3, cs6.getAllSimpleChildren().size()); + Model model = getModelForFile("testFiles/xmlNodeTestExamples/nested_complex.xml"); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Element s1 = model.getElementByElementId("csa1"); + Element s2 = model.getElementByElementId("csa2"); + Element s3 = model.getElementByElementId("csa3"); + Element s4 = model.getElementByElementId("csa4"); + Element s5 = model.getElementByElementId("csa5"); + Element s6 = model.getElementByElementId("csa6"); + Element s7 = model.getElementByElementId("sa1"); + Element s8 = model.getElementByElementId("sa2"); + Element s9 = model.getElementByElementId("sa3"); + Element s10 = model.getElementByElementId("sa4"); + Element s11 = model.getElementByElementId("sa5"); + Element s12 = model.getElementByElementId("sa6"); + assertTrue(s1 instanceof Complex); + assertTrue(s2 instanceof Complex); + assertTrue(s3 instanceof Complex); + assertTrue(s4 instanceof Complex); + assertTrue(s5 instanceof Complex); + assertTrue(s6 instanceof Complex); + Complex cs1 = (Complex) s1; + Complex cs2 = (Complex) s2; + Complex cs3 = (Complex) s3; + Complex cs4 = (Complex) s4; + Complex cs5 = (Complex) s5; + Complex cs6 = (Complex) s6; + assertEquals(2, cs1.getElements().size()); + assertEquals(2, cs2.getElements().size()); + assertEquals(0, cs3.getElements().size()); + assertEquals(0, cs4.getElements().size()); + assertEquals(2, cs5.getElements().size()); + assertEquals(3, cs6.getElements().size()); + + assertTrue(cs1.getElements().contains(s9)); + assertTrue(cs1.getElements().contains(s3)); + + assertTrue(cs2.getElements().contains(s7)); + assertTrue(cs2.getElements().contains(s8)); + + assertTrue(cs5.getElements().contains(s10)); + assertTrue(cs5.getElements().contains(s11)); + + assertTrue(cs6.getElements().contains(s4)); + assertTrue(cs6.getElements().contains(s5)); + assertTrue(cs6.getElements().contains(s12)); + + assertEquals(1, cs1.getAllSimpleChildren().size()); + assertEquals(2, cs2.getAllSimpleChildren().size()); + assertEquals(0, cs3.getAllSimpleChildren().size()); + assertEquals(0, cs4.getAllSimpleChildren().size()); + assertEquals(2, cs5.getAllSimpleChildren().size()); + assertEquals(3, cs6.getAllSimpleChildren().size()); } } diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/ReconDataInCellDesignerXmlParserTest.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/ReconDataInCellDesignerXmlParserTest.java index dfbe867583ce69eefdbe64333714bf860303ad94..ea1d779d02cdf0795c6610952b86cf34faeee5bb 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/ReconDataInCellDesignerXmlParserTest.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/ReconDataInCellDesignerXmlParserTest.java @@ -1,13 +1,10 @@ package lcsb.mapviewer.converter.model.celldesigner; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.Assert.*; -import org.apache.logging.log4j.*; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.junit.*; import lcsb.mapviewer.converter.ConverterParams; import lcsb.mapviewer.model.map.model.Model; @@ -15,62 +12,54 @@ import lcsb.mapviewer.model.map.reaction.Reaction; import lcsb.mapviewer.model.map.species.Species; public class ReconDataInCellDesignerXmlParserTest extends CellDesignerTestFunctions { - Logger logger = LogManager.getLogger(ReconDataInCellDesignerXmlParserTest.class); + Logger logger = LogManager.getLogger(ReconDataInCellDesignerXmlParserTest.class); - @Before - public void setUp() throws Exception { - } + @Before + public void setUp() throws Exception { + } - @After - public void tearDown() throws Exception { - } + @After + public void tearDown() throws Exception { + } - @Test - public void testParseElement() throws Exception { - try { - CellDesignerXmlParser parser = new CellDesignerXmlParser(); - Model model = parser.createModel(new ConverterParams().filename("testFiles/annotation/recon_annotation_example.xml")); - assertNotNull(model); - Species species = (Species)model.getElementByElementId("sa1"); - assertNotNull(species); - assertEquals("S1_SYMB",species.getSymbol()); - assertEquals("ABREVIATION",species.getAbbreviation()); - assertEquals("FORMULA",species.getFormula()); - assertEquals((Integer)324,species.getCharge()); - assertEquals(1, species.getSynonyms().size()); - assertTrue(species.getSynonyms().contains("syn44")); - assertEquals("DESCRIPTION",species.getNotes()); - - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } + @Test + public void testParseElement() throws Exception { + CellDesignerXmlParser parser = new CellDesignerXmlParser(); + Model model = parser + .createModel(new ConverterParams().filename("testFiles/annotation/recon_annotation_example.xml")); + assertNotNull(model); + Species species = (Species) model.getElementByElementId("sa1"); + assertNotNull(species); + assertEquals("S1_SYMB", species.getSymbol()); + assertEquals("ABREVIATION", species.getAbbreviation()); + assertEquals("FORMULA", species.getFormula()); + assertEquals((Integer) 324, species.getCharge()); + assertEquals(1, species.getSynonyms().size()); + assertTrue(species.getSynonyms().contains("syn44")); + assertEquals("DESCRIPTION", species.getNotes()); + } - @Test - public void testParseReaction() throws Exception { - try { - CellDesignerXmlParser parser = new CellDesignerXmlParser(); - Model model = parser.createModel(new ConverterParams().filename("testFiles/annotation/recon_annotation_example.xml")); - assertNotNull(model); - Reaction reaction = model.getReactionByReactionId("re1"); - assertNotNull(reaction); - assertEquals("SAW",reaction.getSymbol()); - assertEquals("ABREVIATION2",reaction.getAbbreviation()); - assertEquals("FORMULA2",reaction.getFormula()); - assertEquals((Integer)100,reaction.getMechanicalConfidenceScore()); - assertEquals((Double)200.201,reaction.getLowerBound()); - assertEquals((Double)300.301,reaction.getUpperBound()); - assertEquals("SUBSYSTEM2",reaction.getSubsystem()); - assertEquals("(urn:miriam:ccds:CCDS8639.1) or (urn:miriam:ccds:CCDS26.1) or (urn:miriam:ccds:CCDS314.2) or (urn:miriam:ccds:CCDS314.1)",reaction.getGeneProteinReaction()); - assertEquals(1, reaction.getSynonyms().size()); - assertTrue(reaction.getSynonyms().contains("SYN1")); - assertEquals("DESCRIPTION2",reaction.getNotes()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } + @Test + public void testParseReaction() throws Exception { + CellDesignerXmlParser parser = new CellDesignerXmlParser(); + Model model = parser + .createModel(new ConverterParams().filename("testFiles/annotation/recon_annotation_example.xml")); + assertNotNull(model); + Reaction reaction = model.getReactionByReactionId("re1"); + assertNotNull(reaction); + assertEquals("SAW", reaction.getSymbol()); + assertEquals("ABREVIATION2", reaction.getAbbreviation()); + assertEquals("FORMULA2", reaction.getFormula()); + assertEquals((Integer) 100, reaction.getMechanicalConfidenceScore()); + assertEquals((Double) 200.201, reaction.getLowerBound()); + assertEquals((Double) 300.301, reaction.getUpperBound()); + assertEquals("SUBSYSTEM2", reaction.getSubsystem()); + assertEquals( + "(urn:miriam:ccds:CCDS8639.1) or (urn:miriam:ccds:CCDS26.1) or (urn:miriam:ccds:CCDS314.2) or (urn:miriam:ccds:CCDS314.1)", + reaction.getGeneProteinReaction()); + assertEquals(1, reaction.getSynonyms().size()); + assertTrue(reaction.getSynonyms().contains("SYN1")); + assertEquals("DESCRIPTION2", reaction.getNotes()); + } } diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/alias/AliasCollectionXmlParserTest.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/alias/AliasCollectionXmlParserTest.java index 38e4acc9faed93f0b851818587910ed8460dcaa7..f42ae71b444c652a82861552dcd2e3b49cf1eb9a 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/alias/AliasCollectionXmlParserTest.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/alias/AliasCollectionXmlParserTest.java @@ -1,33 +1,25 @@ package lcsb.mapviewer.converter.model.celldesigner.alias; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import java.awt.geom.Point2D; import java.util.ArrayList; import java.util.List; -import org.apache.logging.log4j.*; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.junit.*; import org.w3c.dom.Node; import lcsb.mapviewer.common.exception.InvalidXmlSchemaException; import lcsb.mapviewer.converter.model.celldesigner.CellDesignerElementCollection; import lcsb.mapviewer.converter.model.celldesigner.CellDesignerTestFunctions; -import lcsb.mapviewer.converter.model.celldesigner.structure.CellDesignerCompartment; -import lcsb.mapviewer.converter.model.celldesigner.structure.CellDesignerComplexSpecies; -import lcsb.mapviewer.converter.model.celldesigner.structure.CellDesignerGenericProtein; +import lcsb.mapviewer.converter.model.celldesigner.structure.*; import lcsb.mapviewer.model.map.compartment.Compartment; import lcsb.mapviewer.model.map.compartment.SquareCompartment; import lcsb.mapviewer.model.map.model.Model; import lcsb.mapviewer.model.map.model.ModelFullIndexed; -import lcsb.mapviewer.model.map.species.Complex; -import lcsb.mapviewer.model.map.species.GenericProtein; -import lcsb.mapviewer.model.map.species.Species; +import lcsb.mapviewer.model.map.species.*; public class AliasCollectionXmlParserTest extends CellDesignerTestFunctions { @@ -52,118 +44,80 @@ public class AliasCollectionXmlParserTest extends CellDesignerTestFunctions { @Test public void testParseXmlSpeciesAliasCollection() throws Exception { - try { - elements.addElement(new CellDesignerGenericProtein("s2594")); - elements.addElement(new CellDesignerGenericProtein("s2595")); - elements.addElement(new CellDesignerGenericProtein("s2596")); - elements.addElement(new CellDesignerGenericProtein("s2506")); - String xmlString = readFile("testFiles/xmlNodeTestExamples/cd_species_alias_collection.xml"); - Node node = getNodeFromXmlString(xmlString); - List<Species> list = parser.parseXmlSpeciesAliasCollection(node); - assertEquals(0, getWarnings().size()); - assertNotNull(list); - assertEquals(4, list.size()); - Species aliasSa8 = null; - Species aliasSa9 = null; - Species aliasSa10 = null; - Species aliasSa11 = null; - for (Species alias : list) { - if (alias.getElementId().equals("sa8")) - aliasSa8 = alias; - if (alias.getElementId().equals("sa9")) - aliasSa9 = alias; - if (alias.getElementId().equals("sa10")) - aliasSa10 = alias; - if (alias.getElementId().equals("sa11")) - aliasSa11 = alias; - } - assertNotNull(aliasSa8); - assertNotNull(aliasSa9); - assertNotNull(aliasSa10); - assertNotNull(aliasSa11); - - } catch (Exception e) { - e.printStackTrace(); - throw e; + elements.addElement(new CellDesignerGenericProtein("s2594")); + elements.addElement(new CellDesignerGenericProtein("s2595")); + elements.addElement(new CellDesignerGenericProtein("s2596")); + elements.addElement(new CellDesignerGenericProtein("s2506")); + String xmlString = readFile("testFiles/xmlNodeTestExamples/cd_species_alias_collection.xml"); + Node node = getNodeFromXmlString(xmlString); + List<Species> list = parser.parseXmlSpeciesAliasCollection(node); + assertEquals(0, getWarnings().size()); + assertNotNull(list); + assertEquals(4, list.size()); + Species aliasSa8 = null; + Species aliasSa9 = null; + Species aliasSa10 = null; + Species aliasSa11 = null; + for (Species alias : list) { + if (alias.getElementId().equals("sa8")) + aliasSa8 = alias; + if (alias.getElementId().equals("sa9")) + aliasSa9 = alias; + if (alias.getElementId().equals("sa10")) + aliasSa10 = alias; + if (alias.getElementId().equals("sa11")) + aliasSa11 = alias; } + assertNotNull(aliasSa8); + assertNotNull(aliasSa9); + assertNotNull(aliasSa10); + assertNotNull(aliasSa11); } - @Test + @Test(expected = InvalidXmlSchemaException.class) public void testParseInvalidXmlSpeciesAliasCollection() throws Exception { - try { - String xmlString = readFile("testFiles/invalid/species_alias_collection.xml"); - Node node = getNodeFromXmlString(xmlString); - parser.parseXmlSpeciesAliasCollection(node); - fail("Exception expected"); - } catch (InvalidXmlSchemaException e) { - assertTrue(e.getMessage().contains("Unknown element of celldesigner:listOfSpeciesAliases")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String xmlString = readFile("testFiles/invalid/species_alias_collection.xml"); + Node node = getNodeFromXmlString(xmlString); + parser.parseXmlSpeciesAliasCollection(node); } - @Test + @Test(expected = InvalidXmlSchemaException.class) public void testParseInvalidXmlComplexAliasCollection() throws Exception { - try { - String xmlString = readFile("testFiles/invalid/complex_alias_collection.xml"); - Node node = getNodeFromXmlString(xmlString); - parser.parseXmlComplexAliasCollection(node); - fail("Exception expected"); - } catch (InvalidXmlSchemaException e) { - assertTrue("Invalid message: " + e.getMessage(), - e.getMessage().contains("Unknown element of celldesigner:listOfComplexSpeciesAliases")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String xmlString = readFile("testFiles/invalid/complex_alias_collection.xml"); + Node node = getNodeFromXmlString(xmlString); + parser.parseXmlComplexAliasCollection(node); } - @Test + @Test(expected = InvalidXmlSchemaException.class) public void testParseInvalidXmlCompartmentAliasCollection() throws Exception { - try { - String xmlString = readFile("testFiles/invalid/compartment_alias_collection.xml"); - Node node = getNodeFromXmlString(xmlString); - parser.parseXmlCompartmentAliasCollection(node); - fail("Exception expected"); - } catch (InvalidXmlSchemaException e) { - assertTrue("Invalid message: " + e.getMessage(), - e.getMessage().contains("Unknown element of celldesigner:listOfCompartmentAliases")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String xmlString = readFile("testFiles/invalid/compartment_alias_collection.xml"); + Node node = getNodeFromXmlString(xmlString); + parser.parseXmlCompartmentAliasCollection(node); } @Test public void testSpeciesAliasCollectionToXmlString() throws Exception { - try { - List<Species> originalLlist = createSpeciesList(); - String xmlString2 = parser.speciesAliasCollectionToXmlString(originalLlist); - assertNotNull(xmlString2); + List<Species> originalLlist = createSpeciesList(); + String xmlString2 = parser.speciesAliasCollectionToXmlString(originalLlist); + assertNotNull(xmlString2); - for (Species alias : originalLlist) { - elements.addElement(new CellDesignerGenericProtein(elements.getElementId(alias))); - } + for (Species alias : originalLlist) { + elements.addElement(new CellDesignerGenericProtein(elements.getElementId(alias))); + } - Node node = getNodeFromXmlString(xmlString2); - List<Species> list = parser.parseXmlSpeciesAliasCollection(node); - assertEquals(0, getWarnings().size()); - assertNotNull(list); - assertEquals(3, list.size()); - for (Species species : originalLlist) { - boolean found = false; - for (Species alias : list) { - if (alias.getElementId().equals(species.getElementId())) { - found = true; - } + Node node = getNodeFromXmlString(xmlString2); + List<Species> list = parser.parseXmlSpeciesAliasCollection(node); + assertEquals(0, getWarnings().size()); + assertNotNull(list); + assertEquals(3, list.size()); + for (Species species : originalLlist) { + boolean found = false; + for (Species alias : list) { + if (alias.getElementId().equals(species.getElementId())) { + found = true; } - assertTrue(found); } - - } catch (Exception e) { - e.printStackTrace(); - throw e; + assertTrue(found); } } @@ -191,70 +145,60 @@ public class AliasCollectionXmlParserTest extends CellDesignerTestFunctions { @Test public void testParseXmlComplexAliasCollection() throws Exception { - try { - elements.addElement(new CellDesignerComplexSpecies("s2597")); - elements.addElement(new CellDesignerComplexSpecies("s2598")); - elements.addElement(new CellDesignerComplexSpecies("s2599")); - String xmlString = readFile("testFiles/xmlNodeTestExamples/cd_complex_alias_collection.xml"); - Node node = getNodeFromXmlString(xmlString); - List<Complex> list = parser.parseXmlComplexAliasCollection(node); - assertEquals(0, getWarnings().size()); - assertNotNull(list); - assertEquals(3, list.size()); - Complex aliasSa1 = null; - Complex aliasSa2 = null; - Complex aliasSa3 = null; - for (Complex alias : list) { - if (alias.getElementId().equals("csa1")) - aliasSa1 = alias; - if (alias.getElementId().equals("csa2")) - aliasSa2 = alias; - if (alias.getElementId().equals("csa3")) - aliasSa3 = alias; - } - assertNotNull(aliasSa1); - assertNotNull(aliasSa2); - assertNotNull(aliasSa3); - - } catch (Exception e) { - throw e; + elements.addElement(new CellDesignerComplexSpecies("s2597")); + elements.addElement(new CellDesignerComplexSpecies("s2598")); + elements.addElement(new CellDesignerComplexSpecies("s2599")); + String xmlString = readFile("testFiles/xmlNodeTestExamples/cd_complex_alias_collection.xml"); + Node node = getNodeFromXmlString(xmlString); + List<Complex> list = parser.parseXmlComplexAliasCollection(node); + assertEquals(0, getWarnings().size()); + assertNotNull(list); + assertEquals(3, list.size()); + Complex aliasSa1 = null; + Complex aliasSa2 = null; + Complex aliasSa3 = null; + for (Complex alias : list) { + if (alias.getElementId().equals("csa1")) + aliasSa1 = alias; + if (alias.getElementId().equals("csa2")) + aliasSa2 = alias; + if (alias.getElementId().equals("csa3")) + aliasSa3 = alias; } + assertNotNull(aliasSa1); + assertNotNull(aliasSa2); + assertNotNull(aliasSa3); } @Test public void testComplexAliasCollectionToXmlString() throws Exception { - try { - List<Complex> list = createComplexAliasList(); - String xmlString2 = parser.complexAliasCollectionToXmlString(list); - assertNotNull(xmlString2); + List<Complex> list = createComplexAliasList(); + String xmlString2 = parser.complexAliasCollectionToXmlString(list); + assertNotNull(xmlString2); - for (Complex complexAlias : list) { - elements.addElement(new CellDesignerComplexSpecies(elements.getElementId(complexAlias))); - } + for (Complex complexAlias : list) { + elements.addElement(new CellDesignerComplexSpecies(elements.getElementId(complexAlias))); + } - Node node = getNodeFromXmlString(xmlString2); - list = parser.parseXmlComplexAliasCollection(node); - assertEquals(0, getWarnings().size()); - assertNotNull(list); - assertEquals(3, list.size()); - Complex aliasSa1 = null; - Complex aliasSa2 = null; - Complex aliasSa3 = null; - for (Complex alias : list) { - if (alias.getElementId().equals("csa1")) - aliasSa1 = alias; - if (alias.getElementId().equals("csa2")) - aliasSa2 = alias; - if (alias.getElementId().equals("csa3")) - aliasSa3 = alias; - } - assertNotNull(aliasSa1); - assertNotNull(aliasSa2); - assertNotNull(aliasSa3); - } catch (Exception e) { - e.printStackTrace(); - throw e; + Node node = getNodeFromXmlString(xmlString2); + list = parser.parseXmlComplexAliasCollection(node); + assertEquals(0, getWarnings().size()); + assertNotNull(list); + assertEquals(3, list.size()); + Complex aliasSa1 = null; + Complex aliasSa2 = null; + Complex aliasSa3 = null; + for (Complex alias : list) { + if (alias.getElementId().equals("csa1")) + aliasSa1 = alias; + if (alias.getElementId().equals("csa2")) + aliasSa2 = alias; + if (alias.getElementId().equals("csa3")) + aliasSa3 = alias; } + assertNotNull(aliasSa1); + assertNotNull(aliasSa2); + assertNotNull(aliasSa3); } private List<Complex> createComplexAliasList() { @@ -278,66 +222,55 @@ public class AliasCollectionXmlParserTest extends CellDesignerTestFunctions { @Test public void testParseXmlCompartmentAliasCollection() throws Exception { - try { - elements.addElement(new CellDesignerCompartment("c1")); - elements.addElement(new CellDesignerCompartment("c2")); - elements.addElement(new CellDesignerCompartment("c3")); - - String xmlString = readFile("testFiles/xmlNodeTestExamples/cd_compartment_alias_collection.xml"); - Node node = getNodeFromXmlString(xmlString); - List<Compartment> list = parser.parseXmlCompartmentAliasCollection(node); - assertEquals(0, getWarnings().size()); - assertNotNull(list); - assertEquals(3, list.size()); - Compartment aliasCa1 = null; - Compartment aliasCa2 = null; - Compartment aliasCa3 = null; - for (Compartment alias : list) { - if (alias.getElementId().equals("ca1")) - aliasCa1 = alias; - if (alias.getElementId().equals("ca2")) - aliasCa2 = alias; - if (alias.getElementId().equals("ca3")) - aliasCa3 = alias; - } - assertNotNull(aliasCa1); - assertNotNull(aliasCa2); - assertNotNull(aliasCa3); - - } catch (Exception e) { - throw e; + elements.addElement(new CellDesignerCompartment("c1")); + elements.addElement(new CellDesignerCompartment("c2")); + elements.addElement(new CellDesignerCompartment("c3")); + + String xmlString = readFile("testFiles/xmlNodeTestExamples/cd_compartment_alias_collection.xml"); + Node node = getNodeFromXmlString(xmlString); + List<Compartment> list = parser.parseXmlCompartmentAliasCollection(node); + assertEquals(0, getWarnings().size()); + assertNotNull(list); + assertEquals(3, list.size()); + Compartment aliasCa1 = null; + Compartment aliasCa2 = null; + Compartment aliasCa3 = null; + for (Compartment alias : list) { + if (alias.getElementId().equals("ca1")) + aliasCa1 = alias; + if (alias.getElementId().equals("ca2")) + aliasCa2 = alias; + if (alias.getElementId().equals("ca3")) + aliasCa3 = alias; } + assertNotNull(aliasCa1); + assertNotNull(aliasCa2); + assertNotNull(aliasCa3); } @Test public void testCompartmentAliasCollectionToXmlString() throws Exception { - try { - List<Compartment> originalLlist = createCompartmentList(); - for (Compartment alias : originalLlist) { - elements.addElement(new CellDesignerCompartment(elements.getElementId(alias))); - } + List<Compartment> originalLlist = createCompartmentList(); + for (Compartment alias : originalLlist) { + elements.addElement(new CellDesignerCompartment(elements.getElementId(alias))); + } - String xmlString2 = parser.compartmentAliasCollectionToXmlString(originalLlist); + String xmlString2 = parser.compartmentAliasCollectionToXmlString(originalLlist); - Node node = getNodeFromXmlString(xmlString2); - List<Compartment> list = parser.parseXmlCompartmentAliasCollection(node); - assertEquals(0, getWarnings().size()); + Node node = getNodeFromXmlString(xmlString2); + List<Compartment> list = parser.parseXmlCompartmentAliasCollection(node); + assertEquals(0, getWarnings().size()); - assertNotNull(list); - assertEquals(originalLlist.size(), list.size()); - for (Compartment species : originalLlist) { - boolean found = false; - for (Compartment alias : list) { - if (alias.getElementId().equals(species.getElementId())) { - found = true; - } + assertNotNull(list); + assertEquals(originalLlist.size(), list.size()); + for (Compartment species : originalLlist) { + boolean found = false; + for (Compartment alias : list) { + if (alias.getElementId().equals(species.getElementId())) { + found = true; } - assertTrue(found); } - - } catch (Exception e) { - e.printStackTrace(); - throw e; + assertTrue(found); } } diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/alias/CompartmentAliasXmlParserTest.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/alias/CompartmentAliasXmlParserTest.java index 5364039301a8f6d94b201d1d16b4536c04369b22..1d7fd45b3a2230cefe813835d29d75adcc02a24b 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/alias/CompartmentAliasXmlParserTest.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/alias/CompartmentAliasXmlParserTest.java @@ -1,17 +1,12 @@ package lcsb.mapviewer.converter.model.celldesigner.alias; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import java.awt.geom.Point2D; -import org.apache.logging.log4j.*; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.junit.*; import org.mockito.Mockito; import lcsb.mapviewer.common.exception.InvalidXmlSchemaException; @@ -19,12 +14,7 @@ import lcsb.mapviewer.common.exception.NotImplementedException; import lcsb.mapviewer.converter.model.celldesigner.CellDesignerElementCollection; import lcsb.mapviewer.converter.model.celldesigner.CellDesignerTestFunctions; import lcsb.mapviewer.converter.model.celldesigner.structure.CellDesignerCompartment; -import lcsb.mapviewer.model.map.compartment.BottomSquareCompartment; -import lcsb.mapviewer.model.map.compartment.Compartment; -import lcsb.mapviewer.model.map.compartment.LeftSquareCompartment; -import lcsb.mapviewer.model.map.compartment.RightSquareCompartment; -import lcsb.mapviewer.model.map.compartment.SquareCompartment; -import lcsb.mapviewer.model.map.compartment.TopSquareCompartment; +import lcsb.mapviewer.model.map.compartment.*; import lcsb.mapviewer.model.map.model.Model; import lcsb.mapviewer.model.map.model.ModelFullIndexed; @@ -48,29 +38,24 @@ public class CompartmentAliasXmlParserTest extends CellDesignerTestFunctions { @Test public void testToXml() throws Exception { - try { - Compartment compartment = createCompartment(); - String xmlString = parser.toXml(compartment); - assertNotNull(xmlString); - - elements.addElement(new CellDesignerCompartment(elements.getElementId(compartment))); - - Compartment alias2 = parser.parseXmlAlias(xmlString); - assertEquals(0, getWarnings().size()); - - assertEquals(compartment.getElementId(), alias2.getElementId()); - assertNotNull(compartment.getName()); - assertEquals(compartment.getFontSize(), alias2.getFontSize(), 1e-6); - assertEquals(compartment.getHeight(), alias2.getHeight(), 1e-6); - assertEquals(compartment.getWidth(), alias2.getWidth(), 1e-6); - assertEquals(compartment.getX(), alias2.getX(), 1e-6); - assertEquals(compartment.getY(), alias2.getY(), 1e-6); - assertEquals(compartment.getNamePoint().getX(), alias2.getNamePoint().getX(), 1e-6); - assertEquals(compartment.getNamePoint().getY(), alias2.getNamePoint().getY(), 1e-6); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Compartment compartment = createCompartment(); + String xmlString = parser.toXml(compartment); + assertNotNull(xmlString); + + elements.addElement(new CellDesignerCompartment(elements.getElementId(compartment))); + + Compartment alias2 = parser.parseXmlAlias(xmlString); + assertEquals(0, getWarnings().size()); + + assertEquals(compartment.getElementId(), alias2.getElementId()); + assertNotNull(compartment.getName()); + assertEquals(compartment.getFontSize(), alias2.getFontSize(), 1e-6); + assertEquals(compartment.getHeight(), alias2.getHeight(), 1e-6); + assertEquals(compartment.getWidth(), alias2.getWidth(), 1e-6); + assertEquals(compartment.getX(), alias2.getX(), 1e-6); + assertEquals(compartment.getY(), alias2.getY(), 1e-6); + assertEquals(compartment.getNamePoint().getX(), alias2.getNamePoint().getX(), 1e-6); + assertEquals(compartment.getNamePoint().getY(), alias2.getNamePoint().getY(), 1e-6); } private Compartment createCompartment() { @@ -85,182 +70,106 @@ public class CompartmentAliasXmlParserTest extends CellDesignerTestFunctions { return compartment; } - @Test + @Test(expected = InvalidXmlSchemaException.class) public void parseInvalidAlias() throws Exception { - try { - Model model = new ModelFullIndexed(null); - parser = new CompartmentAliasXmlParser(elements, model); - String xmlString = readFile("testFiles/xmlNodeTestExamples/cd_compartment_alias.xml"); - parser.parseXmlAlias(xmlString); - fail("Exception expceted"); - } catch (InvalidXmlSchemaException e) { - assertTrue(e.getMessage().contains("Compartment does not exist in a model")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Model model = new ModelFullIndexed(null); + parser = new CompartmentAliasXmlParser(elements, model); + String xmlString = readFile("testFiles/xmlNodeTestExamples/cd_compartment_alias.xml"); + parser.parseXmlAlias(xmlString); } - @Test + @Test(expected = InvalidXmlSchemaException.class) public void parseInvalidAlias2() throws Exception { - try { - Model model = new ModelFullIndexed(null); - CellDesignerCompartment comp = new CellDesignerCompartment(); - comp.setElementId("c1"); - elements.addElement(comp); - parser = new CompartmentAliasXmlParser(elements, model); - String xmlString = readFile("testFiles/invalid/compartment_alias.xml"); - parser.parseXmlAlias(xmlString); - fail("Exception expceted"); - } catch (InvalidXmlSchemaException e) { - assertTrue(e.getMessage().contains("Unknown compartment type")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Model model = new ModelFullIndexed(null); + CellDesignerCompartment comp = new CellDesignerCompartment(); + comp.setElementId("c1"); + elements.addElement(comp); + parser = new CompartmentAliasXmlParser(elements, model); + String xmlString = readFile("testFiles/invalid/compartment_alias.xml"); + parser.parseXmlAlias(xmlString); } - @Test + @Test(expected = InvalidXmlSchemaException.class) public void parseInvalidAlias3() throws Exception { - try { - Model model = new ModelFullIndexed(null); - CellDesignerCompartment comp = new CellDesignerCompartment(); - comp.setElementId("c1"); - elements.addElement(comp); - parser = new CompartmentAliasXmlParser(elements, model); - String xmlString = readFile("testFiles/invalid/compartment_alias2.xml"); - parser.parseXmlAlias(xmlString); - fail("Exception expceted"); - } catch (InvalidXmlSchemaException e) { - assertTrue(e.getMessage().contains("Don't know what to do with celldesigner:point for class")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Model model = new ModelFullIndexed(null); + CellDesignerCompartment comp = new CellDesignerCompartment(); + comp.setElementId("c1"); + elements.addElement(comp); + parser = new CompartmentAliasXmlParser(elements, model); + String xmlString = readFile("testFiles/invalid/compartment_alias2.xml"); + parser.parseXmlAlias(xmlString); } - @Test + @Test(expected = InvalidXmlSchemaException.class) public void parseInvalidAlias4() throws Exception { - try { - Model model = new ModelFullIndexed(null); - CellDesignerCompartment comp = new CellDesignerCompartment(); - comp.setElementId("c1"); - elements.addElement(comp); - parser = new CompartmentAliasXmlParser(elements, model); - String xmlString = readFile("testFiles/invalid/compartment_alias3.xml"); - parser.parseXmlAlias(xmlString); - fail("Exception expceted"); - } catch (InvalidXmlSchemaException e) { - assertTrue(e.getMessage().contains("Unknown element of celldesigner:compartmentAlias")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Model model = new ModelFullIndexed(null); + CellDesignerCompartment comp = new CellDesignerCompartment(); + comp.setElementId("c1"); + elements.addElement(comp); + parser = new CompartmentAliasXmlParser(elements, model); + String xmlString = readFile("testFiles/invalid/compartment_alias3.xml"); + parser.parseXmlAlias(xmlString); } @Test public void testParseXmlAliasNode() throws Exception { - try { - elements.addElement(new CellDesignerCompartment("c1")); - - String xmlString = readFile("testFiles/xmlNodeTestExamples/cd_compartment_alias.xml"); - Compartment alias = (Compartment) parser.parseXmlAlias(xmlString); - assertEquals(0, getWarnings().size()); - assertNotNull(alias); - assertEquals("ca1", alias.getElementId()); - assertNotNull(alias.getName()); - assertTrue(alias instanceof SquareCompartment); - assertEquals(139.0, alias.getX(), 1e-6); - assertEquals(55.0, alias.getY(), 1e-6); - assertEquals(522.0, alias.getWidth(), 1e-6); - assertEquals(392.5, alias.getNamePoint().getX(), 1e-6); - assertEquals(196.5, alias.getNamePoint().getY(), 1e-6); - assertEquals(0xffcccc00, alias.getColor().getRGB()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + elements.addElement(new CellDesignerCompartment("c1")); + + String xmlString = readFile("testFiles/xmlNodeTestExamples/cd_compartment_alias.xml"); + Compartment alias = (Compartment) parser.parseXmlAlias(xmlString); + assertEquals(0, getWarnings().size()); + assertNotNull(alias); + assertEquals("ca1", alias.getElementId()); + assertNotNull(alias.getName()); + assertTrue(alias instanceof SquareCompartment); + assertEquals(139.0, alias.getX(), 1e-6); + assertEquals(55.0, alias.getY(), 1e-6); + assertEquals(522.0, alias.getWidth(), 1e-6); + assertEquals(392.5, alias.getNamePoint().getX(), 1e-6); + assertEquals(196.5, alias.getNamePoint().getY(), 1e-6); + assertEquals(0xffcccc00, alias.getColor().getRGB()); } @Test public void testGetters() { - try { - parser.setCommonParser(null); + parser.setCommonParser(null); - assertNull(parser.getCommonParser()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertNull(parser.getCommonParser()); } @Test public void testLeftToXml() throws Exception { - try { - Compartment alias = new LeftSquareCompartment("id"); - String xml = parser.toXml(alias); - assertNotNull(xml); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - + Compartment alias = new LeftSquareCompartment("id"); + String xml = parser.toXml(alias); + assertNotNull(xml); } @Test public void testRightToXml() throws Exception { - try { - Compartment alias = new RightSquareCompartment("id"); - String xml = parser.toXml(alias); - assertNotNull(xml); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - + Compartment alias = new RightSquareCompartment("id"); + String xml = parser.toXml(alias); + assertNotNull(xml); } @Test public void testTopToXml() throws Exception { - try { - Compartment alias = new TopSquareCompartment("id"); - String xml = parser.toXml(alias); - assertNotNull(xml); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - + Compartment alias = new TopSquareCompartment("id"); + String xml = parser.toXml(alias); + assertNotNull(xml); } @Test public void testBotttomToXml() throws Exception { - try { - Compartment alias = new BottomSquareCompartment("id"); - String xml = parser.toXml(alias); - assertNotNull(xml); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - + Compartment alias = new BottomSquareCompartment("id"); + String xml = parser.toXml(alias); + assertNotNull(xml); } - @Test + @Test(expected = NotImplementedException.class) public void testUnknownToXml() throws Exception { - try { - Compartment alias = Mockito.mock(BottomSquareCompartment.class); - Mockito.when(alias.getElementId()).thenReturn("some id"); - parser.toXml(alias); - fail("Exception expected"); - } catch (NotImplementedException e) { - assertTrue(e.getMessage().contains("Unknown compartment class")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - + Compartment alias = Mockito.mock(BottomSquareCompartment.class); + Mockito.when(alias.getElementId()).thenReturn("some id"); + parser.toXml(alias); } } diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/alias/ComplexAliasXmlParserTest.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/alias/ComplexAliasXmlParserTest.java index 1ac3189debc1c46e4f16e44602b6f7b8be64718c..3d233cffe153d8bc2a94922293c7e874af1d094e 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/alias/ComplexAliasXmlParserTest.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/alias/ComplexAliasXmlParserTest.java @@ -1,11 +1,8 @@ package lcsb.mapviewer.converter.model.celldesigner.alias; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.*; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import lcsb.mapviewer.common.Configuration; import lcsb.mapviewer.converter.model.celldesigner.CellDesignerElementCollection; @@ -33,26 +30,21 @@ public class ComplexAliasXmlParserTest extends CellDesignerTestFunctions { @Test public void testToXml() throws Exception { - try { - Complex complex = createComplex(); - String xmlString = parser.toXml(complex); - assertNotNull(xmlString); + Complex complex = createComplex(); + String xmlString = parser.toXml(complex); + assertNotNull(xmlString); - elements.addElement(new CellDesignerComplexSpecies(elements.getElementId(complex))); - Complex complexFromXml = parser.parseXmlAlias(xmlString); - assertEquals(0, getWarnings().size()); + elements.addElement(new CellDesignerComplexSpecies(elements.getElementId(complex))); + Complex complexFromXml = parser.parseXmlAlias(xmlString); + assertEquals(0, getWarnings().size()); - assertEquals(complex.getElementId(), complexFromXml.getElementId()); - assertNotNull(complex.getName()); - assertEquals(complex.getFontSize(), complexFromXml.getFontSize(), Configuration.EPSILON); - assertEquals(complex.getHeight(), complexFromXml.getHeight(), Configuration.EPSILON); - assertEquals(complex.getWidth(), complexFromXml.getWidth(), Configuration.EPSILON); - assertEquals(complex.getX(), complexFromXml.getX(), Configuration.EPSILON); - assertEquals(complex.getY(), complexFromXml.getY(), Configuration.EPSILON); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(complex.getElementId(), complexFromXml.getElementId()); + assertNotNull(complex.getName()); + assertEquals(complex.getFontSize(), complexFromXml.getFontSize(), Configuration.EPSILON); + assertEquals(complex.getHeight(), complexFromXml.getHeight(), Configuration.EPSILON); + assertEquals(complex.getWidth(), complexFromXml.getWidth(), Configuration.EPSILON); + assertEquals(complex.getX(), complexFromXml.getX(), Configuration.EPSILON); + assertEquals(complex.getY(), complexFromXml.getY(), Configuration.EPSILON); } private Complex createComplex() { @@ -68,22 +60,17 @@ public class ComplexAliasXmlParserTest extends CellDesignerTestFunctions { @Test public void testParseXmlAliasNode() throws Exception { - try { - elements.addElement(new CellDesignerComplexSpecies("s2597")); + elements.addElement(new CellDesignerComplexSpecies("s2597")); - String xmlString = readFile("testFiles/xmlNodeTestExamples/cd_complex_alias.xml"); - Complex alias = (Complex) parser.parseXmlAlias(xmlString); - assertEquals(0, getWarnings().size()); - assertEquals(false, alias.getActivity()); - assertEquals("csa1", alias.getElementId()); - assertEquals(12.0, alias.getFontSize(), Configuration.EPSILON); - assertEquals(120.0, alias.getHeight(), Configuration.EPSILON); - assertEquals(100.0, alias.getWidth(), Configuration.EPSILON); - assertEquals(744.0, alias.getX(), Configuration.EPSILON); - assertEquals(0.0, alias.getY(), Configuration.EPSILON); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String xmlString = readFile("testFiles/xmlNodeTestExamples/cd_complex_alias.xml"); + Complex alias = (Complex) parser.parseXmlAlias(xmlString); + assertEquals(0, getWarnings().size()); + assertEquals(false, alias.getActivity()); + assertEquals("csa1", alias.getElementId()); + assertEquals(12.0, alias.getFontSize(), Configuration.EPSILON); + assertEquals(120.0, alias.getHeight(), Configuration.EPSILON); + assertEquals(100.0, alias.getWidth(), Configuration.EPSILON); + assertEquals(744.0, alias.getX(), Configuration.EPSILON); + assertEquals(0.0, alias.getY(), Configuration.EPSILON); } } diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/alias/SpeciesAliasXmlParserTest.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/alias/SpeciesAliasXmlParserTest.java index dc9211475cbcd050b666b9c883529098c9604a38..3e983e66b9c3396bd26feba12609a3db92728e06 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/alias/SpeciesAliasXmlParserTest.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/alias/SpeciesAliasXmlParserTest.java @@ -1,19 +1,14 @@ package lcsb.mapviewer.converter.model.celldesigner.alias; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; -import static org.mockito.Mockito.when; +import static org.junit.Assert.*; +import static org.mockito.Mockito.*; import java.util.ArrayList; import java.util.List; -import org.apache.logging.log4j.*; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.junit.*; import org.mockito.Mockito; import lcsb.mapviewer.common.exception.InvalidXmlSchemaException; @@ -22,12 +17,8 @@ import lcsb.mapviewer.converter.model.celldesigner.CellDesignerTestFunctions; import lcsb.mapviewer.converter.model.celldesigner.structure.CellDesignerComplexSpecies; import lcsb.mapviewer.converter.model.celldesigner.structure.CellDesignerGenericProtein; import lcsb.mapviewer.model.map.compartment.Compartment; -import lcsb.mapviewer.model.map.model.Model; -import lcsb.mapviewer.model.map.model.ModelData; -import lcsb.mapviewer.model.map.model.ModelFullIndexed; -import lcsb.mapviewer.model.map.species.Complex; -import lcsb.mapviewer.model.map.species.GenericProtein; -import lcsb.mapviewer.model.map.species.Species; +import lcsb.mapviewer.model.map.model.*; +import lcsb.mapviewer.model.map.species.*; public class SpeciesAliasXmlParserTest extends CellDesignerTestFunctions { static Logger logger = LogManager.getLogger(SpeciesAliasXmlParser.class); @@ -66,63 +57,48 @@ public class SpeciesAliasXmlParserTest extends CellDesignerTestFunctions { @Test public void testParseXmlAliasNode() throws Exception { - try { - String xmlString = readFile("testFiles/xmlNodeTestExamples/species_alias.xml"); - Species alias = parser.parseXmlAlias(xmlString); - assertEquals(0, getWarnings().size()); - assertEquals(false, alias.getActivity()); - assertEquals("sa36", alias.getElementId()); - assertEquals(16.0, alias.getFontSize(), 1e-6); - assertEquals(25.0, alias.getHeight(), 1e-6); - assertEquals(80, alias.getWidth(), 1e-6); - assertEquals(11813.0, alias.getX(), 1e-6); - assertEquals(2840.5, alias.getY(), 1e-6); - assertEquals("ca1", alias.getCompartment().getElementId()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String xmlString = readFile("testFiles/xmlNodeTestExamples/species_alias.xml"); + Species alias = parser.parseXmlAlias(xmlString); + assertEquals(0, getWarnings().size()); + assertEquals(false, alias.getActivity()); + assertEquals("sa36", alias.getElementId()); + assertEquals(16.0, alias.getFontSize(), 1e-6); + assertEquals(25.0, alias.getHeight(), 1e-6); + assertEquals(80, alias.getWidth(), 1e-6); + assertEquals(11813.0, alias.getX(), 1e-6); + assertEquals(2840.5, alias.getY(), 1e-6); + assertEquals("ca1", alias.getCompartment().getElementId()); } @Test public void testParseXmlAliasFont() throws Exception { - try { - String xmlString = readFile("testFiles/xmlNodeTestExamples/species_alias_with_font.xml"); - Species alias = parser.parseXmlAlias(xmlString); - assertEquals(30.0, alias.getFontSize(), 1e-6); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String xmlString = readFile("testFiles/xmlNodeTestExamples/species_alias_with_font.xml"); + Species alias = parser.parseXmlAlias(xmlString); + assertEquals(30.0, alias.getFontSize(), 1e-6); } @Test public void testToXml() throws Exception { - try { - Model model2 = createStubModel(); - Species protein = createProtein(); - protein.setCompartment(model2.getCompartments().iterator().next()); - elements.addElement(new CellDesignerGenericProtein(elements.getElementId(protein))); - String xmlString = parser.toXml(protein); - - parser = new SpeciesAliasXmlParser(elements, model2); - Species alias2 = parser.parseXmlAlias(xmlString); - assertEquals(0, getWarnings().size()); - - assertEquals(protein.getActivity(), alias2.getActivity()); - assertEquals(protein.getElementId(), alias2.getElementId()); - assertEquals(protein.getFontSize(), alias2.getFontSize(), 1e-6); - assertEquals(protein.getHeight(), alias2.getHeight(), 1e-6); - assertEquals(protein.getWidth(), alias2.getWidth(), 1e-6); - assertEquals(protein.getX(), alias2.getX(), 1e-6); - assertEquals(protein.getY(), alias2.getY(), 1e-6); - assertEquals(protein.getCompartment().getElementId(), alias2.getCompartment().getElementId()); - assertEquals("Alias state label different", protein.getStateLabel(), alias2.getStateLabel()); - assertEquals("Alias state prefix different", protein.getStatePrefix(), alias2.getStatePrefix()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Model model2 = createStubModel(); + Species protein = createProtein(); + protein.setCompartment(model2.getCompartments().iterator().next()); + elements.addElement(new CellDesignerGenericProtein(elements.getElementId(protein))); + String xmlString = parser.toXml(protein); + + parser = new SpeciesAliasXmlParser(elements, model2); + Species alias2 = parser.parseXmlAlias(xmlString); + assertEquals(0, getWarnings().size()); + + assertEquals(protein.getActivity(), alias2.getActivity()); + assertEquals(protein.getElementId(), alias2.getElementId()); + assertEquals(protein.getFontSize(), alias2.getFontSize(), 1e-6); + assertEquals(protein.getHeight(), alias2.getHeight(), 1e-6); + assertEquals(protein.getWidth(), alias2.getWidth(), 1e-6); + assertEquals(protein.getX(), alias2.getX(), 1e-6); + assertEquals(protein.getY(), alias2.getY(), 1e-6); + assertEquals(protein.getCompartment().getElementId(), alias2.getCompartment().getElementId()); + assertEquals("Alias state label different", protein.getStateLabel(), alias2.getStateLabel()); + assertEquals("Alias state prefix different", protein.getStatePrefix(), alias2.getStatePrefix()); } private Species createProtein() { @@ -140,197 +116,127 @@ public class SpeciesAliasXmlParserTest extends CellDesignerTestFunctions { @Test public void testToXmlAliasWithStateNode() throws Exception { - try { - Model model = createStubModel(); - Species protein = createProtein(); - protein.setState("sssstate"); - protein.setCompartment(model.getCompartments().iterator().next()); - elements.addElement(new CellDesignerGenericProtein(elements.getElementId(protein))); - String xmlString = parser.toXml(protein); - - Species alias2 = parser.parseXmlAlias(xmlString); - assertEquals(0, getWarnings().size()); - - assertEquals("Alias state label different", protein.getStateLabel(), alias2.getStateLabel()); - assertEquals("Alias state prefix different", protein.getStatePrefix(), alias2.getStatePrefix()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Model model = createStubModel(); + Species protein = createProtein(); + protein.setState("sssstate"); + protein.setCompartment(model.getCompartments().iterator().next()); + elements.addElement(new CellDesignerGenericProtein(elements.getElementId(protein))); + String xmlString = parser.toXml(protein); + + Species alias2 = parser.parseXmlAlias(xmlString); + assertEquals(0, getWarnings().size()); + + assertEquals("Alias state label different", protein.getStateLabel(), alias2.getStateLabel()); + assertEquals("Alias state prefix different", protein.getStatePrefix(), alias2.getStatePrefix()); } @Test public void testParseXmlAliasWithStateNode() throws Exception { - try { - String xmlString = readFile("testFiles/xmlNodeTestExamples/species_alias_with_state.xml"); - Species alias = parser.parseXmlAlias(xmlString); - assertEquals(0, getWarnings().size()); - assertNotNull(alias); - assertEquals("test", alias.getStateLabel()); - assertEquals("free input", alias.getStatePrefix()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String xmlString = readFile("testFiles/xmlNodeTestExamples/species_alias_with_state.xml"); + Species alias = parser.parseXmlAlias(xmlString); + assertEquals(0, getWarnings().size()); + assertNotNull(alias); + assertEquals("test", alias.getStateLabel()); + assertEquals("free input", alias.getStatePrefix()); } @Test public void testParseXmlAliasWithoutStateNode() throws Exception { - try { - String xmlString = readFile("testFiles/xmlNodeTestExamples/species_alias_without_state.xml"); - Species alias = parser.parseXmlAlias(xmlString); - assertEquals(0, getWarnings().size()); - assertNotNull(alias); - assertNull(alias.getStateLabel()); - assertNull(alias.getStatePrefix()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String xmlString = readFile("testFiles/xmlNodeTestExamples/species_alias_without_state.xml"); + Species alias = parser.parseXmlAlias(xmlString); + assertEquals(0, getWarnings().size()); + assertNotNull(alias); + assertNull(alias.getStateLabel()); + assertNull(alias.getStatePrefix()); } - @Test + @Test(expected = InvalidXmlSchemaException.class) public void testParseInvalidXmlAliasNode() throws Exception { - try { - String xmlString = readFile("testFiles/invalid/species_alias.xml"); - parser.parseXmlAlias(xmlString); - fail("Exception expected"); - } catch (InvalidXmlSchemaException e) { - assertTrue(e.getMessage().contains("Unknown species for alias")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String xmlString = readFile("testFiles/invalid/species_alias.xml"); + parser.parseXmlAlias(xmlString); } - @Test + @Test(expected = InvalidXmlSchemaException.class) public void testParseInvalidXmlAliasNode2() throws Exception { - try { - String xmlString = readFile("testFiles/invalid/species_alias2.xml"); - parser.parseXmlAlias(xmlString); - fail("Exception expected"); - } catch (InvalidXmlSchemaException e) { - assertTrue(e.getMessage().contains("Unknown element of celldesigner:speciesAlias")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String xmlString = readFile("testFiles/invalid/species_alias2.xml"); + parser.parseXmlAlias(xmlString); } - @Test + @Test(expected = InvalidXmlSchemaException.class) public void testParseInvalidXmlAliasNode3() throws Exception { - try { - String xmlString = readFile("testFiles/invalid/species_alias3.xml"); - parser.parseXmlAlias(xmlString); - fail("Exception expected"); - } catch (InvalidXmlSchemaException e) { - assertTrue(e.getMessage().contains("No view in Alias")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String xmlString = readFile("testFiles/invalid/species_alias3.xml"); + parser.parseXmlAlias(xmlString); } - @Test + @Test(expected = InvalidXmlSchemaException.class) public void testParseInvalidXmlAliasNode4() throws Exception { - try { - parser = new SpeciesAliasXmlParser(elements, model); - - String xmlString = readFile("testFiles/invalid/species_alias4.xml"); - parser.parseXmlAlias(xmlString); - fail("Exception expected"); - } catch (InvalidXmlSchemaException e) { - assertTrue(e.getMessage().contains("CompartmentAlias does not exist")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + parser = new SpeciesAliasXmlParser(elements, model); + + String xmlString = readFile("testFiles/invalid/species_alias4.xml"); + parser.parseXmlAlias(xmlString); } - @Test + @Test(expected = InvalidXmlSchemaException.class) public void testParseInvalidXmlAliasNode5() throws Exception { - try { - parser = new SpeciesAliasXmlParser(elements, model); - - String xmlString = readFile("testFiles/invalid/species_alias5.xml"); - parser.parseXmlAlias(xmlString); - fail("Exception expected"); - } catch (InvalidXmlSchemaException e) { - assertTrue(e.getMessage().contains("ComplexAlias does not exist")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + parser = new SpeciesAliasXmlParser(elements, model); + + String xmlString = readFile("testFiles/invalid/species_alias5.xml"); + parser.parseXmlAlias(xmlString); } - @Test + @Test(expected = InvalidXmlSchemaException.class) public void testParseInvalidXmlAliasNode6() throws Exception { - try { - parser = new SpeciesAliasXmlParser(elements, model); - - String xmlString = readFile("testFiles/invalid/species_alias6.xml"); - parser.parseXmlAlias(xmlString); - fail("Exception expected"); - } catch (InvalidXmlSchemaException e) { - logger.debug(e.getMessage()); - assertTrue(e.getMessage().contains("Problem with creating species")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + parser = new SpeciesAliasXmlParser(elements, model); + + String xmlString = readFile("testFiles/invalid/species_alias6.xml"); + parser.parseXmlAlias(xmlString); } @Test public void testToXmlWithUnknownCompartment() throws Exception { - try { - Model model = Mockito.mock(ModelFullIndexed.class); - ModelData md = new ModelData(); - md.setModel(model); - - Compartment ca2 = new Compartment(testCompartmentAliasId2); - ca2.setElementId(testCompartmentAliasId2); - ca2.setX(6); - ca2.setY(6); - ca2.setWidth(190); - ca2.setHeight(190); - - Compartment ca = new Compartment(testCompartmentAliasId); - ca.setElementId(testCompartmentAliasId); - ca.setX(5); - ca.setY(5); - ca.setWidth(200); - ca.setHeight(200); - - List<Compartment> list = new ArrayList<>(); - list.add(ca); - list.add(ca2); - - // ensure that we return list (firts bigger compartment, then smaller) - when(model.getCompartments()).thenReturn(list); - when(model.getModelData()).thenReturn(md); - - Species alias = new Complex(testAliasId); - alias.setX(10); - alias.setY(10); - alias.setWidth(100); - alias.setHeight(100); - alias.setModel(model); - alias.setActivity(true); - - elements.addElement(new CellDesignerComplexSpecies(testSpeciesId)); - model.addElement(alias); - SpeciesAliasXmlParser parser = new SpeciesAliasXmlParser(elements, model); - - String xml = parser.toXml(alias); - - assertTrue(xml.contains(testAliasId)); - assertTrue(xml.contains(testCompartmentAliasId2)); - assertTrue(xml.contains("<celldesigner:activity>active</celldesigner:activity>")); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Model model = Mockito.mock(ModelFullIndexed.class); + ModelData md = new ModelData(); + md.setModel(model); + + Compartment ca2 = new Compartment(testCompartmentAliasId2); + ca2.setElementId(testCompartmentAliasId2); + ca2.setX(6); + ca2.setY(6); + ca2.setWidth(190); + ca2.setHeight(190); + + Compartment ca = new Compartment(testCompartmentAliasId); + ca.setElementId(testCompartmentAliasId); + ca.setX(5); + ca.setY(5); + ca.setWidth(200); + ca.setHeight(200); + + List<Compartment> list = new ArrayList<>(); + list.add(ca); + list.add(ca2); + + // ensure that we return list (firts bigger compartment, then smaller) + when(model.getCompartments()).thenReturn(list); + when(model.getModelData()).thenReturn(md); + + Species alias = new Complex(testAliasId); + alias.setX(10); + alias.setY(10); + alias.setWidth(100); + alias.setHeight(100); + alias.setModel(model); + alias.setActivity(true); + + elements.addElement(new CellDesignerComplexSpecies(testSpeciesId)); + model.addElement(alias); + SpeciesAliasXmlParser parser = new SpeciesAliasXmlParser(elements, model); + + String xml = parser.toXml(alias); + + assertTrue(xml.contains(testAliasId)); + assertTrue(xml.contains(testCompartmentAliasId2)); + assertTrue(xml.contains("<celldesigner:activity>active</celldesigner:activity>")); } } diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/annotation/RestAnnotationParserTest.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/annotation/RestAnnotationParserTest.java index f894db095527a5f0cad86dbfd635c15733f4d055..ed55df20099e0737ebf46479a98d7f669e8e6b1a 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/annotation/RestAnnotationParserTest.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/annotation/RestAnnotationParserTest.java @@ -1,20 +1,15 @@ package lcsb.mapviewer.converter.model.celldesigner.annotation; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import java.lang.reflect.Field; import java.util.List; import java.util.Set; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.apache.xerces.dom.DocumentImpl; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.mockito.Mockito; import org.w3c.dom.Document; import org.w3c.dom.Node; @@ -23,15 +18,10 @@ import lcsb.mapviewer.common.exception.InvalidArgumentException; import lcsb.mapviewer.common.exception.NotImplementedException; import lcsb.mapviewer.converter.model.celldesigner.CellDesignerTestFunctions; import lcsb.mapviewer.converter.model.celldesigner.structure.CellDesignerElement; -import lcsb.mapviewer.model.map.BioEntity; -import lcsb.mapviewer.model.map.MiriamData; -import lcsb.mapviewer.model.map.MiriamRelationType; -import lcsb.mapviewer.model.map.MiriamType; +import lcsb.mapviewer.model.map.*; import lcsb.mapviewer.model.map.model.Model; import lcsb.mapviewer.model.map.reaction.Reaction; -import lcsb.mapviewer.model.map.species.Element; -import lcsb.mapviewer.model.map.species.GenericProtein; -import lcsb.mapviewer.model.map.species.Species; +import lcsb.mapviewer.model.map.species.*; public class RestAnnotationParserTest extends CellDesignerTestFunctions { Logger logger = LogManager.getLogger(RestAnnotationParserTest.class); @@ -46,411 +36,293 @@ public class RestAnnotationParserTest extends CellDesignerTestFunctions { @Test public void test() throws Exception { + RestAnnotationParser rap = new RestAnnotationParser(); - try { - RestAnnotationParser rap = new RestAnnotationParser(); + String response = readFile("testFiles/annotation/sampleDescription.txt"); - String response = readFile("testFiles/annotation/sampleDescription.txt"); + List<String> synonyms = rap.getSynonyms(response); + assertEquals(3, synonyms.size()); + assertTrue(synonyms.contains("CAMK")); + assertTrue(synonyms.contains("CAMKIV")); - List<String> synonyms = rap.getSynonyms(response); - assertEquals(3, synonyms.size()); - assertTrue(synonyms.contains("CAMK")); - assertTrue(synonyms.contains("CAMKIV")); - - List<String> formerSymbols = rap.getFormerSymbols(response); - assertEquals(0, formerSymbols.size()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + List<String> formerSymbols = rap.getFormerSymbols(response); + assertEquals(0, formerSymbols.size()); } @Test public void testParseNotes() throws Exception { - try { - RestAnnotationParser parser = new RestAnnotationParser(); - Document node = getXmlDocumentFromFile("testFiles/xmlNodeTestExamples/notes.xml"); - Species proteinAlias = new GenericProtein("id"); - parser.processNotes(node.getFirstChild(), proteinAlias); - String notes = proteinAlias.getNotes(); - assertNotNull(notes); - assertFalse(notes.contains("body")); - assertTrue(notes.contains("some")); - // after redoing it should be the same - parser.processNotes(node.getFirstChild(), proteinAlias); - notes = proteinAlias.getNotes(); - assertNotNull(notes); - assertFalse(notes.contains("body")); - assertTrue(notes.contains("some")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + RestAnnotationParser parser = new RestAnnotationParser(); + Document node = getXmlDocumentFromFile("testFiles/xmlNodeTestExamples/notes.xml"); + Species proteinAlias = new GenericProtein("id"); + parser.processNotes(node.getFirstChild(), proteinAlias); + String notes = proteinAlias.getNotes(); + assertNotNull(notes); + assertFalse(notes.contains("body")); + assertTrue(notes.contains("some")); + // after redoing it should be the same + parser.processNotes(node.getFirstChild(), proteinAlias); + notes = proteinAlias.getNotes(); + assertNotNull(notes); + assertFalse(notes.contains("body")); + assertTrue(notes.contains("some")); } @Test public void testParseNotes2() throws Exception { - try { - RestAnnotationParser parser = new RestAnnotationParser(); - Document node = getXmlDocumentFromFile("testFiles/xmlNodeTestExamples/notes3.xml"); - Species proteinAlias = new GenericProtein("id"); - parser.processNotes(node.getFirstChild(), proteinAlias); - String notes = proteinAlias.getNotes(); - assertNotNull(notes); - assertFalse(notes.contains("body")); - assertTrue(notes.contains("some")); - // after redoing it should be the same - parser.processNotes(node.getFirstChild(), proteinAlias); - notes = proteinAlias.getNotes(); - assertNotNull(notes); - assertFalse(notes.contains("body")); - assertTrue(notes.contains("some")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + RestAnnotationParser parser = new RestAnnotationParser(); + Document node = getXmlDocumentFromFile("testFiles/xmlNodeTestExamples/notes3.xml"); + Species proteinAlias = new GenericProtein("id"); + parser.processNotes(node.getFirstChild(), proteinAlias); + String notes = proteinAlias.getNotes(); + assertNotNull(notes); + assertFalse(notes.contains("body")); + assertTrue(notes.contains("some")); + // after redoing it should be the same + parser.processNotes(node.getFirstChild(), proteinAlias); + notes = proteinAlias.getNotes(); + assertNotNull(notes); + assertFalse(notes.contains("body")); + assertTrue(notes.contains("some")); } @Test public void testParseNotes3() throws Exception { - try { - RestAnnotationParser parser = new RestAnnotationParser(); - Document node = getXmlDocumentFromFile("testFiles/xmlNodeTestExamples/notes4.xml"); - Species proteinAlias = new GenericProtein("id"); - proteinAlias.setNotes("text"); - parser.processNotes(node.getFirstChild(), proteinAlias); - String notes = proteinAlias.getNotes(); - assertNotNull(notes); - assertFalse(notes.contains("body")); - assertTrue(notes.contains("some")); - // after redoing it should be the same - parser.processNotes(node.getFirstChild(), proteinAlias); - notes = proteinAlias.getNotes(); - assertNotNull(notes); - assertFalse(notes.contains("body")); - assertTrue(notes.contains("some")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + RestAnnotationParser parser = new RestAnnotationParser(); + Document node = getXmlDocumentFromFile("testFiles/xmlNodeTestExamples/notes4.xml"); + Species proteinAlias = new GenericProtein("id"); + proteinAlias.setNotes("text"); + parser.processNotes(node.getFirstChild(), proteinAlias); + String notes = proteinAlias.getNotes(); + assertNotNull(notes); + assertFalse(notes.contains("body")); + assertTrue(notes.contains("some")); + // after redoing it should be the same + parser.processNotes(node.getFirstChild(), proteinAlias); + notes = proteinAlias.getNotes(); + assertNotNull(notes); + assertFalse(notes.contains("body")); + assertTrue(notes.contains("some")); } @Test public void testParseCollisionNotes() throws Exception { - try { - RestAnnotationParser parser = new RestAnnotationParser(); - Document node = getXmlDocumentFromFile("testFiles/xmlNodeTestExamples/notes2.xml"); - - GenericProtein protein = new GenericProtein("pr_id1"); - protein.addSynonym("a1"); - protein.addFormerSymbol("a1"); - protein.setFullName("yyy"); - protein.setAbbreviation("aaaa"); - protein.setCharge(9); - protein.setSymbol("D"); - parser.processNotes(node.getFirstChild(), protein); - assertEquals(1, protein.getSynonyms().size()); - assertEquals(1, protein.getFormerSymbols().size()); - - assertEquals(6, getWarnings().size()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + RestAnnotationParser parser = new RestAnnotationParser(); + Document node = getXmlDocumentFromFile("testFiles/xmlNodeTestExamples/notes2.xml"); + + GenericProtein protein = new GenericProtein("pr_id1"); + protein.addSynonym("a1"); + protein.addFormerSymbol("a1"); + protein.setFullName("yyy"); + protein.setAbbreviation("aaaa"); + protein.setCharge(9); + protein.setSymbol("D"); + parser.processNotes(node.getFirstChild(), protein); + assertEquals(1, protein.getSynonyms().size()); + assertEquals(1, protein.getFormerSymbols().size()); + + assertEquals(6, getWarnings().size()); } @Test public void testParseInvalidNotes1() throws Exception { - try { - RestAnnotationParser parser = new RestAnnotationParser(); - Document node = getXmlDocumentFromFile("testFiles/xmlNodeTestExamples/notes_invalid_charge.xml"); - - Species proteinAlias = new GenericProtein("id"); - parser.processNotes(node.getFirstChild(), proteinAlias); + RestAnnotationParser parser = new RestAnnotationParser(); + Document node = getXmlDocumentFromFile("testFiles/xmlNodeTestExamples/notes_invalid_charge.xml"); - assertEquals(1, getWarnings().size()); + Species proteinAlias = new GenericProtein("id"); + parser.processNotes(node.getFirstChild(), proteinAlias); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(1, getWarnings().size()); } @Test public void testParseCollisionNotes2() throws Exception { - try { - RestAnnotationParser parser = new RestAnnotationParser(); - Document node = getXmlDocumentFromFile("testFiles/xmlNodeTestExamples/notes2.xml"); - Reaction reaction = new Reaction(); - reaction.addSynonym("a1"); - reaction.setAbbreviation("aaaa"); - reaction.setSubsystem("sss"); - reaction.setGeneProteinReaction("str"); - reaction.setFormula("xxx"); - reaction.setMechanicalConfidenceScore(-45); - reaction.setUpperBound(4.5); - reaction.setLowerBound(4.5); - - parser.processNotes(node.getFirstChild(), reaction); - - assertEquals(8, getWarnings().size()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + RestAnnotationParser parser = new RestAnnotationParser(); + Document node = getXmlDocumentFromFile("testFiles/xmlNodeTestExamples/notes2.xml"); + Reaction reaction = new Reaction(); + reaction.addSynonym("a1"); + reaction.setAbbreviation("aaaa"); + reaction.setSubsystem("sss"); + reaction.setGeneProteinReaction("str"); + reaction.setFormula("xxx"); + reaction.setMechanicalConfidenceScore(-45); + reaction.setUpperBound(4.5); + reaction.setLowerBound(4.5); + + parser.processNotes(node.getFirstChild(), reaction); + + assertEquals(8, getWarnings().size()); } @Test public void testMoveAnnotationsFromNotes() throws Exception { - try { - Model model = getModelForFile("testFiles/copyingAnnotationModel.xml"); - - Set<Element> elements = model.getElements(); - for (Element element : elements) { - if (element.getName().equals("blabla")) { - assertEquals(2, element.getMiriamData().size()); - element.getMiriamData() - .add(new MiriamData(MiriamRelationType.BQ_BIOL_IS_DESCRIBED_BY, MiriamType.PUBMED, "12345")); - element.getMiriamData() - .add(new MiriamData(MiriamRelationType.BQ_BIOL_IS_DESCRIBED_BY, MiriamType.PUBMED, "333666")); - assertEquals(2, element.getMiriamData().size()); - } - assertFalse(element.getNotes().contains("rdf:RDF")); + Model model = getModelForFile("testFiles/copyingAnnotationModel.xml"); + + Set<Element> elements = model.getElements(); + for (Element element : elements) { + if (element.getName().equals("blabla")) { + assertEquals(2, element.getMiriamData().size()); + element.getMiriamData() + .add(new MiriamData(MiriamRelationType.BQ_BIOL_IS_DESCRIBED_BY, MiriamType.PUBMED, "12345")); + element.getMiriamData() + .add(new MiriamData(MiriamRelationType.BQ_BIOL_IS_DESCRIBED_BY, MiriamType.PUBMED, "333666")); + assertEquals(2, element.getMiriamData().size()); } - - } catch (Exception e) { - e.printStackTrace(); - throw e; + assertFalse(element.getNotes().contains("rdf:RDF")); } } @Test public void testProcessRdfDescription() throws Exception { - try { - RestAnnotationParser rap = new RestAnnotationParser(); - Species speciesAlias = new GenericProtein("id"); - speciesAlias.setNotes("begining\n" + "<rdf:RDF>" + "<rdf:Description rdf:about=\"#s2157\">\n" + "<bqmodel:is>\n" - + "<rdf:Bag>\n" + "<rdf:li rdf:resource=\"urn:miriam:obo.chebi:CHEBI%3A17515\"/>\n" + "</rdf:Bag>\n" - + "</bqmodel:is>\n" + "</rdf:Description>\n" + "</rdf:RDF>" + "\nend ending"); - rap.processRdfDescription(speciesAlias); - assertEquals("begining\n\nend ending", speciesAlias.getNotes()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + RestAnnotationParser rap = new RestAnnotationParser(); + Species speciesAlias = new GenericProtein("id"); + speciesAlias.setNotes("begining\n" + "<rdf:RDF>" + "<rdf:Description rdf:about=\"#s2157\">\n" + "<bqmodel:is>\n" + + "<rdf:Bag>\n" + "<rdf:li rdf:resource=\"urn:miriam:obo.chebi:CHEBI%3A17515\"/>\n" + "</rdf:Bag>\n" + + "</bqmodel:is>\n" + "</rdf:Description>\n" + "</rdf:RDF>" + "\nend ending"); + rap.processRdfDescription(speciesAlias); + assertEquals("begining\n\nend ending", speciesAlias.getNotes()); } @Test public void testGetMiriamDataFromAnnotation() throws Exception { - try { - RestAnnotationParser rap = new RestAnnotationParser(); - String response = readFile("testFiles/annotation/sampleDescription.txt"); - - Set<MiriamData> set = rap.getMiriamData(response); - for (MiriamData miriamData : set) { - if (miriamData.getDataType().equals(MiriamType.KEGG_GENES)) { - assertTrue(miriamData.getResource().contains("hsa")); - } - } + RestAnnotationParser rap = new RestAnnotationParser(); + String response = readFile("testFiles/annotation/sampleDescription.txt"); - } catch (Exception e) { - e.printStackTrace(); - throw e; + Set<MiriamData> set = rap.getMiriamData(response); + for (MiriamData miriamData : set) { + if (miriamData.getDataType().equals(MiriamType.KEGG_GENES)) { + assertTrue(miriamData.getResource().contains("hsa")); + } } - } @Test public void testGetMiriamDataFromEmpty() throws Exception { - try { - RestAnnotationParser rap = new RestAnnotationParser(); - - Set<MiriamData> set = rap.getMiriamData(null); - assertEquals(0, set.size()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + RestAnnotationParser rap = new RestAnnotationParser(); + Set<MiriamData> set = rap.getMiriamData(null); + assertEquals(0, set.size()); } @Test public void testCreateAnnotationString() throws Exception { - try { - RestAnnotationParser rap = new RestAnnotationParser(); - - String former1 = "form1"; - String former2 = "form2"; - GenericProtein element = new GenericProtein("id"); - element.addFormerSymbol(former1); - element.addFormerSymbol(former2); - element.setCharge(1); - String str = rap.createAnnotationString(element, true); - assertTrue(str.contains(former1)); - assertTrue(str.contains(former2)); - - for (NoteField field : NoteField.values()) { - boolean deprecated = false; - boolean importOnly = false; - try { - Field f = NoteField.class.getField(field.name()); - if (f.isAnnotationPresent(Deprecated.class)) - deprecated = true; - if (f.isAnnotationPresent(ImportOnly.class)) - importOnly = true; - - } catch (NoSuchFieldException | SecurityException e) { - } + RestAnnotationParser rap = new RestAnnotationParser(); + + String former1 = "form1"; + String former2 = "form2"; + GenericProtein element = new GenericProtein("id"); + element.addFormerSymbol(former1); + element.addFormerSymbol(former2); + element.setCharge(1); + String str = rap.createAnnotationString(element, true); + assertTrue(str.contains(former1)); + assertTrue(str.contains(former2)); + + for (NoteField field : NoteField.values()) { + boolean deprecated = false; + boolean importOnly = false; + try { + Field f = NoteField.class.getField(field.name()); + if (f.isAnnotationPresent(Deprecated.class)) + deprecated = true; + if (f.isAnnotationPresent(ImportOnly.class)) + importOnly = true; + + } catch (NoSuchFieldException | SecurityException e) { + } - if (!deprecated && !importOnly) { - if (field.getClazz().isAssignableFrom(element.getClass()) - || CellDesignerElement.class.isAssignableFrom(field.getClazz())) { - assertTrue("Export string doesn't contain info about: " + field.getCommonName(), - str.indexOf(field.getCommonName()) >= 0); - } + if (!deprecated && !importOnly) { + if (field.getClazz().isAssignableFrom(element.getClass()) + || CellDesignerElement.class.isAssignableFrom(field.getClazz())) { + assertTrue("Export string doesn't contain info about: " + field.getCommonName(), + str.indexOf(field.getCommonName()) >= 0); } - } - } catch (Exception e) { - e.printStackTrace(); - throw e; } - } @Test public void testCreateEmptyAnnotationString() throws Exception { - try { - RestAnnotationParser rap = new RestAnnotationParser(); - GenericProtein element = new GenericProtein("id"); - String str = rap.createAnnotationString(element, false); - - for (NoteField field : NoteField.values()) { - if (field.getClazz().isAssignableFrom(element.getClass()) - || CellDesignerElement.class.isAssignableFrom(field.getClazz())) { - assertFalse("Export string contain info about: " + field.getCommonName() + ". But shouldn't", - str.indexOf(field.getCommonName()) >= 0); - } - + RestAnnotationParser rap = new RestAnnotationParser(); + GenericProtein element = new GenericProtein("id"); + String str = rap.createAnnotationString(element, false); + + for (NoteField field : NoteField.values()) { + if (field.getClazz().isAssignableFrom(element.getClass()) + || CellDesignerElement.class.isAssignableFrom(field.getClazz())) { + assertFalse("Export string contain info about: " + field.getCommonName() + ". But shouldn't", + str.indexOf(field.getCommonName()) >= 0); } - } catch (Exception e) { - e.printStackTrace(); - throw e; } - } @Test public void testGetFormerSymbolsFromInvalidStr() throws Exception { - try { - RestAnnotationParser rap = new RestAnnotationParser(); - - assertEquals(0, rap.getFormerSymbols(null).size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + RestAnnotationParser rap = new RestAnnotationParser(); + assertEquals(0, rap.getFormerSymbols(null).size()); } - @Test + @Test(expected = InvalidArgumentException.class) public void testGetNotesInvalid() throws Exception { - try { - RestAnnotationParser rap = new RestAnnotationParser(); - - Document xmlDoc = new DocumentImpl(); - Node node = xmlDoc.createElement("bla"); - - rap.getNotes(node); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + RestAnnotationParser rap = new RestAnnotationParser(); + Document xmlDoc = new DocumentImpl(); + Node node = xmlDoc.createElement("bla"); + + rap.getNotes(node); } @Test public void testGetNotesWithLinkInside() throws Exception { - try { - RestAnnotationParser rap = new RestAnnotationParser(); - - Node node = super.getNodeFromXmlString("<notes>\n" + - "Name: L-cystine\n" + - "Synonyms: (R,R)-3,3'-dithiobis(2-aminopropanoic acid), (R-(R*,R*))-3,3'-Dithiobis(2-aminopropanoic acid), 3,3'-Dithiobis-L-alanine, beta,beta'-diamino-beta,beta'-dicarboxydiethyl disulfide, beta,beta'-dithiodialanine, bis(beta-amino-beta-carboxyethyl) disulfide, E921, L-alpha-Diamino-beta-dithiolactic acid, L-Cystine, L-Dicysteine, oxidized L-cysteine, Recon metabolite: mma\n" - + - "Description: VMH database: <a xmlns=\"http://www.w3.org/1999/xhtml\" href=\"http://vmh.uni.lu/#metabolite/mma\">mma</a>\n" - + - "SemanticZoomLevelVisibility: 5\n" + - "Charge: 0\n" + - "</notes>\n" + - ""); - String notes = rap.getNotes(node); - assertFalse(notes.contains("http://www.w3.org/1999/xhtml")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - + RestAnnotationParser rap = new RestAnnotationParser(); + + Node node = super.getNodeFromXmlString("<notes>\n" + + "Name: L-cystine\n" + + "Synonyms: (R,R)-3,3'-dithiobis(2-aminopropanoic acid), (R-(R*,R*))-3,3'-Dithiobis(2-aminopropanoic acid), 3,3'-Dithiobis-L-alanine, beta,beta'-diamino-beta,beta'-dicarboxydiethyl disulfide, beta,beta'-dithiodialanine, bis(beta-amino-beta-carboxyethyl) disulfide, E921, L-alpha-Diamino-beta-dithiolactic acid, L-Cystine, L-Dicysteine, oxidized L-cysteine, Recon metabolite: mma\n" + + + "Description: VMH database: <a xmlns=\"http://www.w3.org/1999/xhtml\" href=\"http://vmh.uni.lu/#metabolite/mma\">mma</a>\n" + + + "SemanticZoomLevelVisibility: 5\n" + + "Charge: 0\n" + + "</notes>\n" + + ""); + String notes = rap.getNotes(node); + assertFalse(notes.contains("http://www.w3.org/1999/xhtml")); } - @Test + @Test(expected = NotImplementedException.class) public void testProcessNotesForInvalidElement() throws Exception { - try { - RestAnnotationParser parser = new RestAnnotationParser(); - Document node = getXmlDocumentFromFile("testFiles/xmlNodeTestExamples/notes4.xml"); - BioEntity bioEntity = Mockito.mock(BioEntity.class); - Mockito.when(bioEntity.getNotes()).thenReturn(""); - parser.processNotes(node.getFirstChild(), bioEntity); - fail("Exception expected"); - } catch (NotImplementedException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + RestAnnotationParser parser = new RestAnnotationParser(); + Document node = getXmlDocumentFromFile("testFiles/xmlNodeTestExamples/notes4.xml"); + BioEntity bioEntity = Mockito.mock(BioEntity.class); + Mockito.when(bioEntity.getNotes()).thenReturn(""); + parser.processNotes(node.getFirstChild(), bioEntity); } @Test public void testProcessInvalidNotes() throws Exception { - try { - RestAnnotationParser parser = new RestAnnotationParser(); - String str = super.readFile("testFiles/xmlNodeTestExamples/notes5.xml"); - - parser.processNotes(str, new GenericProtein("id")); + RestAnnotationParser parser = new RestAnnotationParser(); + String str = super.readFile("testFiles/xmlNodeTestExamples/notes5.xml"); - assertEquals(1, getWarnings().size()); + parser.processNotes(str, new GenericProtein("id")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(1, getWarnings().size()); } @Test public void testProcessNotes() throws Exception { - try { - String newNotes = "new notes"; - String oldNotes = "old notes"; - RestAnnotationParser parser = new RestAnnotationParser(); - String str = "Description: " + newNotes + "\n" + oldNotes; - GenericProtein protein = new GenericProtein("id"); - parser.processNotes(str, protein); - - assertTrue(protein.getNotes().contains(newNotes)); - assertTrue(protein.getNotes().contains(oldNotes)); - assertFalse(protein.getNotes().contains("Description")); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String newNotes = "new notes"; + String oldNotes = "old notes"; + RestAnnotationParser parser = new RestAnnotationParser(); + String str = "Description: " + newNotes + "\n" + oldNotes; + GenericProtein protein = new GenericProtein("id"); + parser.processNotes(str, protein); + + assertTrue(protein.getNotes().contains(newNotes)); + assertTrue(protein.getNotes().contains(oldNotes)); + assertFalse(protein.getNotes().contains("Description")); } } diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/compartment/CompartmentCollectionXmlParserTest.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/compartment/CompartmentCollectionXmlParserTest.java index 9e851e9a7a7ec9b941ec8e99bf05abb815261775..ed2af3a9f26ef35ae80dde46c5a2e52dd77f455e 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/compartment/CompartmentCollectionXmlParserTest.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/compartment/CompartmentCollectionXmlParserTest.java @@ -1,17 +1,13 @@ package lcsb.mapviewer.converter.model.celldesigner.compartment; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import java.util.ArrayList; import java.util.List; -import org.apache.logging.log4j.*; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.junit.*; import org.w3c.dom.Node; import lcsb.mapviewer.common.exception.InvalidXmlSchemaException; @@ -21,88 +17,66 @@ import lcsb.mapviewer.converter.model.celldesigner.structure.CellDesignerCompart import lcsb.mapviewer.model.map.compartment.Compartment; public class CompartmentCollectionXmlParserTest extends CellDesignerTestFunctions { - static Logger logger = LogManager.getLogger(CompartmentCollectionXmlParserTest.class); - - int aliasIdCounter = 0; - - CompartmentCollectionXmlParser parser; - CellDesignerElementCollection elements; - - @Before - public void setUp() throws Exception { - elements = new CellDesignerElementCollection(); - parser = new CompartmentCollectionXmlParser(elements); - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testParseXmlReactionCollection() throws Exception { - try { - - String xmlString = readFile("testFiles/compartment/listOfCompartments.xml"); - Node node = getNodeFromXmlString(xmlString); - List<CellDesignerCompartment> compartments = parser.parseXmlCompartmentCollection(node); - - assertEquals(4, compartments.size()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testParseInvalidXmlReactionCollection() throws Exception { - try { - String xmlString = readFile("testFiles/invalid/listOfCompartments.xml"); - Node node = getNodeFromXmlString(xmlString); - parser.parseXmlCompartmentCollection(node); - fail("Exception expected"); - } catch (InvalidXmlSchemaException e) { - assertTrue(e.getMessage().contains("Unknown element of model/listOfCompartments:")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testCompartmentCollectionToXmlString() throws Exception { - try { - - String xmlString = readFile("testFiles/compartment/listOfCompartments.xml"); - Node node = getNodeFromXmlString(xmlString); - List<CellDesignerCompartment> cellDesignerCompartments = parser.parseXmlCompartmentCollection(node); - - List<Compartment> compartments = new ArrayList<>(); - for (CellDesignerCompartment cellDesignerCompartment : cellDesignerCompartments) { - Compartment comp =cellDesignerCompartment.createModelElement("ca" + aliasIdCounter); - compartments.add(comp); - aliasIdCounter++; - } - - String xmlString2 = parser.toXml(compartments); - assertNotNull(xmlString2); - - node = getNodeFromXmlString(xmlString2); - - elements = new CellDesignerElementCollection(); - parser = new CompartmentCollectionXmlParser(elements); - - List<CellDesignerCompartment> compartments2 = parser.parseXmlCompartmentCollection(node); - for (int i = 0; i < cellDesignerCompartments.size(); i++) { - CellDesignerCompartment compartmentA = cellDesignerCompartments.get(i); - CellDesignerCompartment compartmentB = compartments2.get(i); - assertEquals(compartmentA.getName(), compartmentB.getName()); - } - - } catch (Exception e) { - logger.error(e.getMessage(), e); - throw e; - } - } + static Logger logger = LogManager.getLogger(CompartmentCollectionXmlParserTest.class); + + int aliasIdCounter = 0; + + CompartmentCollectionXmlParser parser; + CellDesignerElementCollection elements; + + @Before + public void setUp() throws Exception { + elements = new CellDesignerElementCollection(); + parser = new CompartmentCollectionXmlParser(elements); + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testParseXmlReactionCollection() throws Exception { + String xmlString = readFile("testFiles/compartment/listOfCompartments.xml"); + Node node = getNodeFromXmlString(xmlString); + List<CellDesignerCompartment> compartments = parser.parseXmlCompartmentCollection(node); + + assertEquals(4, compartments.size()); + } + + @Test(expected = InvalidXmlSchemaException.class) + public void testParseInvalidXmlReactionCollection() throws Exception { + String xmlString = readFile("testFiles/invalid/listOfCompartments.xml"); + Node node = getNodeFromXmlString(xmlString); + parser.parseXmlCompartmentCollection(node); + } + + @Test + public void testCompartmentCollectionToXmlString() throws Exception { + String xmlString = readFile("testFiles/compartment/listOfCompartments.xml"); + Node node = getNodeFromXmlString(xmlString); + List<CellDesignerCompartment> cellDesignerCompartments = parser.parseXmlCompartmentCollection(node); + + List<Compartment> compartments = new ArrayList<>(); + for (CellDesignerCompartment cellDesignerCompartment : cellDesignerCompartments) { + Compartment comp = cellDesignerCompartment.createModelElement("ca" + aliasIdCounter); + compartments.add(comp); + aliasIdCounter++; + } + + String xmlString2 = parser.toXml(compartments); + assertNotNull(xmlString2); + + node = getNodeFromXmlString(xmlString2); + + elements = new CellDesignerElementCollection(); + parser = new CompartmentCollectionXmlParser(elements); + + List<CellDesignerCompartment> compartments2 = parser.parseXmlCompartmentCollection(node); + for (int i = 0; i < cellDesignerCompartments.size(); i++) { + CellDesignerCompartment compartmentA = cellDesignerCompartments.get(i); + CellDesignerCompartment compartmentB = compartments2.get(i); + assertEquals(compartmentA.getName(), compartmentB.getName()); + } + } } diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/compartment/CompartmentParserTests.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/compartment/CompartmentParserTests.java index fa8566b724de60000b67cf287449da2dc5c53756..c251c2c564045429fe223aebf71d16fa5054a532 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/compartment/CompartmentParserTests.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/compartment/CompartmentParserTests.java @@ -1,81 +1,51 @@ package lcsb.mapviewer.converter.model.celldesigner.compartment; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; -import org.apache.logging.log4j.*; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.junit.*; import lcsb.mapviewer.converter.model.celldesigner.CellDesignerTestFunctions; import lcsb.mapviewer.model.map.model.Model; public class CompartmentParserTests extends CellDesignerTestFunctions { - Logger logger = LogManager.getLogger(CompartmentParserTests.class); + Logger logger = LogManager.getLogger(CompartmentParserTests.class); - @Before - public void setUp() throws Exception { - } + @Before + public void setUp() throws Exception { + } - @After - public void tearDown() throws Exception { - } + @After + public void tearDown() throws Exception { + } - @Test - public void testParseCompartmensBottom() { - Model model; - try { - model = getModelForFile("testFiles/compartment/bottom_compartment.xml"); + @Test + public void testParseCompartmensBottom() throws Exception { + Model model = getModelForFile("testFiles/compartment/bottom_compartment.xml"); - assertEquals(1, model.getElements().size()); + assertEquals(1, model.getElements().size()); + } - } catch (Exception e) { - e.printStackTrace(); - fail("Unexpected exception"); - } - } + @Test + public void testParseCompartmensTop() throws Exception { + Model model = getModelForFile("testFiles/compartment/top_compartment.xml"); - @Test - public void testParseCompartmensTop() { - Model model; - try { - model = getModelForFile("testFiles/compartment/top_compartment.xml"); + assertEquals(1, model.getElements().size()); + } - assertEquals(1, model.getElements().size()); + @Test + public void testParseCompartmensRight() throws Exception { + Model model = getModelForFile("testFiles/compartment/right_compartment.xml"); - } catch (Exception e) { - e.printStackTrace(); - fail("Unexpected exception"); - } - } + assertEquals(1, model.getElements().size()); + } - @Test - public void testParseCompartmensRight() { - Model model; - try { - model = getModelForFile("testFiles/compartment/right_compartment.xml"); + @Test + public void testParseCompartmensLeft() throws Exception { + Model model = getModelForFile("testFiles/compartment/left_compartment.xml"); - assertEquals(1, model.getElements().size()); - - } catch (Exception e) { - e.printStackTrace(); - fail("Unexpected exception"); - } - } - - @Test - public void testParseCompartmensLeft() { - Model model; - try { - model = getModelForFile("testFiles/compartment/left_compartment.xml"); - - assertEquals(1, model.getElements().size()); - - } catch (Exception e) { - e.printStackTrace(); - fail("Unexpected exception"); - } - } + assertEquals(1, model.getElements().size()); + } } diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/compartment/CompartmentXmlParserTest.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/compartment/CompartmentXmlParserTest.java index 08340b92ebff8bebd1590c667db5eeee74cc0528..3c487452c2d0fa0fdecbae0ad6b13af32f6ddd77 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/compartment/CompartmentXmlParserTest.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/compartment/CompartmentXmlParserTest.java @@ -1,19 +1,15 @@ package lcsb.mapviewer.converter.model.celldesigner.compartment; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import java.io.StringReader; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; -import org.apache.logging.log4j.*; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.junit.*; import org.w3c.dom.Document; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; @@ -43,105 +39,62 @@ public class CompartmentXmlParserTest extends CellDesignerTestFunctions { } @Test - public void testParseXmlCompartment() { - try { - String xmlString = readFile(testProteinFile); - - Pair<String, CellDesignerCompartment> result = compartmentParser.parseXmlElement(xmlString); - CellDesignerCompartment compartment = result.getRight(); - assertNotNull(compartment); - assertEquals("c1", compartment.getElementId()); - assertEquals(1, compartment.getMiriamData().size()); - assertEquals("c1", compartment.getName()); - - } catch (Exception e) { - e.printStackTrace(); - fail("Unexpected exception occured"); - } + public void testParseXmlCompartment() throws Exception { + String xmlString = readFile(testProteinFile); + + Pair<String, CellDesignerCompartment> result = compartmentParser.parseXmlElement(xmlString); + CellDesignerCompartment compartment = result.getRight(); + assertNotNull(compartment); + assertEquals("c1", compartment.getElementId()); + assertEquals(1, compartment.getMiriamData().size()); + assertEquals("c1", compartment.getName()); } @Test public void testToXml() throws Exception { - try { - String xmlString = readFile(testProteinFile); - - Pair<String, CellDesignerCompartment> result = compartmentParser.parseXmlElement(xmlString); - CellDesignerCompartment compartment = result.getRight(); - Compartment alias = compartment.createModelElement("id"); - String transformedXml = compartmentParser.toXml(alias); - assertNotNull(transformedXml); - DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); - DocumentBuilder builder = factory.newDocumentBuilder(); - InputSource is = new InputSource(new StringReader(transformedXml)); - Document doc = builder.parse(is); - NodeList root = doc.getChildNodes(); - assertEquals("compartment", root.item(0).getNodeName()); - - Pair<String, CellDesignerCompartment> result2 = compartmentParser.parseXmlElement(compartmentParser.toXml(alias)); - CellDesignerCompartment compartment2 = result2.getRight(); - assertEquals(alias.getMiriamData().size(), compartment2.getMiriamData().size()); - assertEquals(alias.getName(), compartment2.getName()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String xmlString = readFile(testProteinFile); + + Pair<String, CellDesignerCompartment> result = compartmentParser.parseXmlElement(xmlString); + CellDesignerCompartment compartment = result.getRight(); + Compartment alias = compartment.createModelElement("id"); + String transformedXml = compartmentParser.toXml(alias); + assertNotNull(transformedXml); + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + DocumentBuilder builder = factory.newDocumentBuilder(); + InputSource is = new InputSource(new StringReader(transformedXml)); + Document doc = builder.parse(is); + NodeList root = doc.getChildNodes(); + assertEquals("compartment", root.item(0).getNodeName()); + + Pair<String, CellDesignerCompartment> result2 = compartmentParser.parseXmlElement(compartmentParser.toXml(alias)); + CellDesignerCompartment compartment2 = result2.getRight(); + assertEquals(alias.getMiriamData().size(), compartment2.getMiriamData().size()); + assertEquals(alias.getName(), compartment2.getName()); } - @Test + @Test(expected = CompartmentParserException.class) public void testParseInvalidCompartment() throws Exception { - try { - compartmentParser.parseXmlElement(readFile("testFiles/invalid/compartment.xml")); - fail("Exception expected"); - - } catch (CompartmentParserException e) { - assertTrue(e.getMessage().contains("Unknown element of Compartment")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + compartmentParser.parseXmlElement(readFile("testFiles/invalid/compartment.xml")); } - @Test + @Test(expected = CompartmentParserException.class) public void testParseInvalidCompartment2() throws Exception { - try { - compartmentParser.parseXmlElement(readFile("testFiles/invalid/compartment2.xml")); - fail("Exception expected"); - - } catch (CompartmentParserException e) { - assertTrue(e.getMessage().contains("Unknown xml tag of compartment")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + compartmentParser.parseXmlElement(readFile("testFiles/invalid/compartment2.xml")); } - @Test + @Test(expected = CompartmentParserException.class) public void testParseInvalidCompartment3() throws Exception { - try { - compartmentParser.parseXmlElement(readFile("testFiles/invalid/compartment3.xml")); - fail("Exception expected"); - - } catch (CompartmentParserException e) { - assertTrue(e.getMessage().contains("Unknown element of Compartment/annotation/extension")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + compartmentParser.parseXmlElement(readFile("testFiles/invalid/compartment3.xml")); } @Test public void testToXmlWithParent() throws Exception { - try { - Compartment child = new Compartment("c_1"); - Compartment parent = new Compartment("p_1"); - child.setCompartment(parent); - - String xml = compartmentParser.toXml(child); - assertTrue(xml.contains(parent.getElementId())); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Compartment child = new Compartment("c_1"); + Compartment parent = new Compartment("p_1"); + child.setCompartment(parent); + + String xml = compartmentParser.toXml(child); + assertTrue(xml.contains(parent.getElementId())); } } diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/geometry/CellDesignerAliasConverterTest.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/geometry/CellDesignerAliasConverterTest.java index 98003ed53917840511bacce046642efe2a1b498a..a846617fdc2023a0a831bcecacfaa6466a8342b8 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/geometry/CellDesignerAliasConverterTest.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/geometry/CellDesignerAliasConverterTest.java @@ -1,51 +1,36 @@ package lcsb.mapviewer.converter.model.celldesigner.geometry; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.mockito.Mockito; import lcsb.mapviewer.common.exception.InvalidArgumentException; import lcsb.mapviewer.common.exception.NotImplementedException; +import lcsb.mapviewer.converter.model.celldesigner.CellDesignerTestFunctions; import lcsb.mapviewer.model.map.species.Species; -public class CellDesignerAliasConverterTest { - - @AfterClass - public static void tearDownAfterClass() throws Exception { - } - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testConstructorWithInvalidArg() { - try { - new CellDesignerAliasConverter(null, false); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - assertTrue(e.getMessage().contains("element cannot be null")); - } - } - - @Test - public void testConstructorWithInvalidArg2() { - try { - Species alias = Mockito.mock(Species.class); - new CellDesignerAliasConverter(alias, false); - fail("Exception expected"); - } catch (NotImplementedException e) { - assertTrue(e.getMessage().contains("Unknown converter for class")); - } - } +public class CellDesignerAliasConverterTest extends CellDesignerTestFunctions { + + @AfterClass + public static void tearDownAfterClass() throws Exception { + } + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test(expected = InvalidArgumentException.class) + public void testConstructorWithInvalidArg() { + new CellDesignerAliasConverter(null, false); + } + + @Test(expected = NotImplementedException.class) + public void testConstructorWithInvalidArg2() { + Species alias = Mockito.mock(Species.class); + new CellDesignerAliasConverter(alias, false); + } } diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/geometry/ComplexConverterTest.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/geometry/ComplexConverterTest.java index 8640d60688e95b43fa731b91a6dd0a5a6a5ef18e..5cadff00130de6fdc5d74bd7b271225ddb9a1a45 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/geometry/ComplexConverterTest.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/geometry/ComplexConverterTest.java @@ -1,13 +1,12 @@ package lcsb.mapviewer.converter.model.celldesigner.geometry; -import static org.junit.Assert.assertEquals; +import static org.junit.Assert.*; import java.awt.geom.Point2D; -import org.apache.logging.log4j.*; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.junit.*; import lcsb.mapviewer.common.Configuration; import lcsb.mapviewer.converter.model.celldesigner.CellDesignerTestFunctions; @@ -27,24 +26,18 @@ public class ComplexConverterTest extends CellDesignerTestFunctions { @Test public void testGetAnchorForAlias() throws Exception { - try { - - Complex alias = new Complex("id"); - alias.setWidth(200); - alias.setHeight(300); - alias.setX(100.0); - alias.setY(50.0); - - CellDesignerAliasConverter converter = new CellDesignerAliasConverter(alias, false); - - for (CellDesignerAnchor anchor : CellDesignerAnchor.values()) { - Point2D point = converter.getPointCoordinates(alias, anchor); - CellDesignerAnchor newAnchor = converter.getAnchorForCoordinates(alias, point); - assertEquals(anchor, newAnchor); - } - } catch (Exception e) { - e.printStackTrace(); - throw e; + Complex alias = new Complex("id"); + alias.setWidth(200); + alias.setHeight(300); + alias.setX(100.0); + alias.setY(50.0); + + CellDesignerAliasConverter converter = new CellDesignerAliasConverter(alias, false); + + for (CellDesignerAnchor anchor : CellDesignerAnchor.values()) { + Point2D point = converter.getPointCoordinates(alias, anchor); + CellDesignerAnchor newAnchor = converter.getAnchorForCoordinates(alias, point); + assertEquals(anchor, newAnchor); } } diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/geometry/ProteinCellDesignerAliasConverterTest.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/geometry/ProteinCellDesignerAliasConverterTest.java index 372e6f5812018eb347de3d264f3e6e8014b17050..c50ba1f30893bf1a4f72850c10ef6ee08722d32a 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/geometry/ProteinCellDesignerAliasConverterTest.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/geometry/ProteinCellDesignerAliasConverterTest.java @@ -1,48 +1,38 @@ package lcsb.mapviewer.converter.model.celldesigner.geometry; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import java.awt.geom.Point2D; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.junit.Test; import org.mockito.Mockito; import lcsb.mapviewer.common.Configuration; import lcsb.mapviewer.common.exception.NotImplementedException; +import lcsb.mapviewer.converter.model.celldesigner.CellDesignerTestFunctions; import lcsb.mapviewer.converter.model.celldesigner.geometry.helper.CellDesignerAnchor; import lcsb.mapviewer.model.map.species.GenericProtein; import lcsb.mapviewer.model.map.species.Protein; -public class ProteinCellDesignerAliasConverterTest { +public class ProteinCellDesignerAliasConverterTest extends CellDesignerTestFunctions { Logger logger = LogManager.getLogger(ProteinCellDesignerAliasConverterTest.class); ProteinCellDesignerAliasConverter converter = new ProteinCellDesignerAliasConverter(false); - @Test + @Test(expected = NotImplementedException.class) public void testNotImplementedMethod() { - try { - Protein alias = Mockito.mock(Protein.class); - converter.getBoundPathIterator(alias); - fail("Exception expected"); - } catch (NotImplementedException e) { - assertTrue(e.getMessage().contains("Not implemented protein converter for type")); - } + Protein alias = Mockito.mock(Protein.class); + converter.getBoundPathIterator(alias); } - @Test + @Test(expected = NotImplementedException.class) public void testGetPointCoordinates() { - try { - Protein alias = Mockito.spy(Protein.class); - alias.setWidth(10); - alias.setHeight(10); - converter.getPointCoordinates(alias, CellDesignerAnchor.E); - fail("Exception expected"); - } catch (NotImplementedException e) { - assertTrue(e.getMessage().contains("Unknown type")); - } + Protein alias = Mockito.spy(Protein.class); + alias.setWidth(10); + alias.setHeight(10); + converter.getPointCoordinates(alias, CellDesignerAnchor.E); } @Test @@ -60,5 +50,4 @@ public class ProteinCellDesignerAliasConverterTest { } } - } diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/geometry/ProteinConverterTest.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/geometry/ProteinConverterTest.java index d0b5bd31465e272d9b2c5d0ac6135a4823c22e76..fc6f42a0346e252df1d0f37e48caef1ab38b040a 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/geometry/ProteinConverterTest.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/geometry/ProteinConverterTest.java @@ -1,13 +1,12 @@ package lcsb.mapviewer.converter.model.celldesigner.geometry; -import static org.junit.Assert.assertEquals; +import static org.junit.Assert.*; import java.awt.geom.Point2D; -import org.apache.logging.log4j.*; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.junit.*; import lcsb.mapviewer.common.Configuration; import lcsb.mapviewer.converter.model.celldesigner.CellDesignerTestFunctions; @@ -28,24 +27,18 @@ public class ProteinConverterTest extends CellDesignerTestFunctions { @Test public void testGetAnchorForAlias() throws Exception { - try { - - GenericProtein alias = new GenericProtein("id"); - alias.setWidth(200); - alias.setHeight(300); - alias.setX(100.0); - alias.setY(50.0); - - CellDesignerAliasConverter converter = new CellDesignerAliasConverter(alias, false); - - for (CellDesignerAnchor anchor : CellDesignerAnchor.values()) { - Point2D point = converter.getPointCoordinates(alias, anchor); - CellDesignerAnchor newAnchor = converter.getAnchorForCoordinates(alias, point); - assertEquals(anchor, newAnchor); - } - } catch (Exception e) { - e.printStackTrace(); - throw e; + GenericProtein alias = new GenericProtein("id"); + alias.setWidth(200); + alias.setHeight(300); + alias.setX(100.0); + alias.setY(50.0); + + CellDesignerAliasConverter converter = new CellDesignerAliasConverter(alias, false); + + for (CellDesignerAnchor anchor : CellDesignerAnchor.values()) { + Point2D point = converter.getPointCoordinates(alias, anchor); + CellDesignerAnchor newAnchor = converter.getAnchorForCoordinates(alias, point); + assertEquals(anchor, newAnchor); } } @@ -68,29 +61,23 @@ public class ProteinConverterTest extends CellDesignerTestFunctions { @Test public void testGetResidueCoords() throws Exception { - try { - GenericProtein protein = new GenericProtein("id"); - protein.setX(135); - protein.setY(194.0); - protein.setWidth(130); - protein.setHeight(67); - - CellDesignerAliasConverter conv = new CellDesignerAliasConverter(protein, false); - assertEquals(135.0, conv.getResidueCoordinates(protein, 3.141592653589793).getX(), 2); - assertEquals(265., conv.getResidueCoordinates(protein, 0.0).getX(), 2); - assertEquals(135.0, conv.getResidueCoordinates(protein, 2.41).getX(), 2); - assertEquals(194.0, conv.getResidueCoordinates(protein, 1.98).getY(), 2); - assertEquals(194.0, conv.getResidueCoordinates(protein, 1.59).getY(), 2); - assertEquals(265.0, conv.getResidueCoordinates(protein, 6.28).getX(), 2); - assertEquals(261.0, conv.getResidueCoordinates(protein, 4.13).getY(), 2); - assertEquals(261.0, conv.getResidueCoordinates(protein, 4.86).getY(), 2); - assertEquals(265.0, conv.getResidueCoordinates(protein, 5.69).getX(), 2); - assertEquals(194.0, conv.getResidueCoordinates(protein, 0.99).getY(), 2); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + GenericProtein protein = new GenericProtein("id"); + protein.setX(135); + protein.setY(194.0); + protein.setWidth(130); + protein.setHeight(67); + + CellDesignerAliasConverter conv = new CellDesignerAliasConverter(protein, false); + assertEquals(135.0, conv.getResidueCoordinates(protein, 3.141592653589793).getX(), 2); + assertEquals(265., conv.getResidueCoordinates(protein, 0.0).getX(), 2); + assertEquals(135.0, conv.getResidueCoordinates(protein, 2.41).getX(), 2); + assertEquals(194.0, conv.getResidueCoordinates(protein, 1.98).getY(), 2); + assertEquals(194.0, conv.getResidueCoordinates(protein, 1.59).getY(), 2); + assertEquals(265.0, conv.getResidueCoordinates(protein, 6.28).getX(), 2); + assertEquals(261.0, conv.getResidueCoordinates(protein, 4.13).getY(), 2); + assertEquals(261.0, conv.getResidueCoordinates(protein, 4.86).getY(), 2); + assertEquals(265.0, conv.getResidueCoordinates(protein, 5.69).getX(), 2); + assertEquals(194.0, conv.getResidueCoordinates(protein, 0.99).getY(), 2); } } diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/geometry/SimpleMoleculeCellDesignerAliasConverterTest.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/geometry/SimpleMoleculeCellDesignerAliasConverterTest.java index 25479733a03204fbd77d8c713a8a4f742d4a02d5..7fb94dd1f68cb514c8944e053e66b324b10eff9d 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/geometry/SimpleMoleculeCellDesignerAliasConverterTest.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/geometry/SimpleMoleculeCellDesignerAliasConverterTest.java @@ -1,24 +1,20 @@ package lcsb.mapviewer.converter.model.celldesigner.geometry; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import java.awt.geom.Point2D; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import lcsb.mapviewer.common.Configuration; import lcsb.mapviewer.common.exception.NotImplementedException; +import lcsb.mapviewer.converter.model.celldesigner.CellDesignerTestFunctions; import lcsb.mapviewer.converter.model.celldesigner.geometry.helper.CellDesignerAnchor; import lcsb.mapviewer.model.map.model.Model; import lcsb.mapviewer.model.map.model.ModelFullIndexed; import lcsb.mapviewer.model.map.species.SimpleMolecule; -public class SimpleMoleculeCellDesignerAliasConverterTest { +public class SimpleMoleculeCellDesignerAliasConverterTest extends CellDesignerTestFunctions { SimpleMoleculeCellDesignerAliasConverter converter = new SimpleMoleculeCellDesignerAliasConverter(false); @@ -34,14 +30,9 @@ public class SimpleMoleculeCellDesignerAliasConverterTest { public void tearDown() throws Exception { } - @Test + @Test(expected = NotImplementedException.class) public void testPathIterator() { - try { - converter.getBoundPathIterator(null); - fail("Exception expected"); - } catch (NotImplementedException e) { - - } + converter.getBoundPathIterator(null); } @Test diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/geometry/helper/CellDesignerLineTransformationTest.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/geometry/helper/CellDesignerLineTransformationTest.java index 68da743761c602d8058fb830c1d45e768e80226b..44e0f1629df81dfdd26afa8b51449068b3467b47 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/geometry/helper/CellDesignerLineTransformationTest.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/geometry/helper/CellDesignerLineTransformationTest.java @@ -1,10 +1,6 @@ package lcsb.mapviewer.converter.model.celldesigner.geometry.helper; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import java.awt.geom.Point2D; import java.util.ArrayList; @@ -12,15 +8,14 @@ import java.util.List; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import lcsb.mapviewer.common.exception.InvalidArgumentException; import lcsb.mapviewer.common.geometry.PointTransformation; +import lcsb.mapviewer.converter.model.celldesigner.CellDesignerTestFunctions; import lcsb.mapviewer.model.graphics.PolylineData; -public class CellDesignerLineTransformationTest { +public class CellDesignerLineTransformationTest extends CellDesignerTestFunctions { Logger logger = LogManager.getLogger(CellDesignerLineTransformationTest.class); CellDesignerLineTransformation lineTransformation = new CellDesignerLineTransformation(); @@ -36,244 +31,166 @@ public class CellDesignerLineTransformationTest { @Test public void testGetPointsFromLine() { - try { - Point2D startPoint = new Point2D.Double(1, 7); - Point2D endPoint = new Point2D.Double(3, 5); + Point2D startPoint = new Point2D.Double(1, 7); + Point2D endPoint = new Point2D.Double(3, 5); - List<Point2D> points = new ArrayList<Point2D>(); - points.add(new Point2D.Double(1.5, 2.5)); - points.add(new Point2D.Double(12, 13)); - points.add(new Point2D.Double(30, 40)); + List<Point2D> points = new ArrayList<Point2D>(); + points.add(new Point2D.Double(1.5, 2.5)); + points.add(new Point2D.Double(12, 13)); + points.add(new Point2D.Double(30, 40)); - PolylineData line = new PolylineData(lineTransformation.getLinePointsFromPoints(startPoint, endPoint, points)); + PolylineData line = new PolylineData(lineTransformation.getLinePointsFromPoints(startPoint, endPoint, points)); - List<Point2D> newPoints = lineTransformation.getPointsFromLine(line); - assertNotNull(newPoints); + List<Point2D> newPoints = lineTransformation.getPointsFromLine(line); + assertNotNull(newPoints); - assertEquals(points.size(), newPoints.size()); + assertEquals(points.size(), newPoints.size()); - for (int i = 0; i < points.size(); i++) { - double dist = points.get(i).distance(newPoints.get(i)); - assertTrue("Distance to big: " + dist + " for points " + points.get(i) + " and " + newPoints.get(i), - dist < 1e-6); - assertTrue(pointTransformation.isValidPoint(newPoints.get(i))); - } - } catch (Exception e) { - e.printStackTrace(); - throw e; + for (int i = 0; i < points.size(); i++) { + double dist = points.get(i).distance(newPoints.get(i)); + assertTrue("Distance to big: " + dist + " for points " + points.get(i) + " and " + newPoints.get(i), + dist < 1e-6); + assertTrue(pointTransformation.isValidPoint(newPoints.get(i))); } } @Test public void testGetPointsFromLineShouldCreateDefensiveCopy() { - try { - Point2D startPoint = new Point2D.Double(1, 7); - Point2D endPoint = new Point2D.Double(3, 5); - - List<Point2D> points = new ArrayList<>(); - points.add(new Point2D.Double(1.5, 2.5)); - points.add(new Point2D.Double(12, 13)); - points.add(new Point2D.Double(30, 40)); - - PolylineData line = new PolylineData(lineTransformation.getLinePointsFromPoints(startPoint, endPoint, points)); - - List<Point2D> newPoints = lineTransformation.getPointsFromLine(line); - List<Point2D> newPoints2 = lineTransformation.getPointsFromLine(line); - for (Point2D point : newPoints2) { - for (Point2D point2 : newPoints) { - assertFalse(point == point2); - } + Point2D startPoint = new Point2D.Double(1, 7); + Point2D endPoint = new Point2D.Double(3, 5); + + List<Point2D> points = new ArrayList<>(); + points.add(new Point2D.Double(1.5, 2.5)); + points.add(new Point2D.Double(12, 13)); + points.add(new Point2D.Double(30, 40)); + + PolylineData line = new PolylineData(lineTransformation.getLinePointsFromPoints(startPoint, endPoint, points)); + + List<Point2D> newPoints = lineTransformation.getPointsFromLine(line); + List<Point2D> newPoints2 = lineTransformation.getPointsFromLine(line); + for (Point2D point : newPoints2) { + for (Point2D point2 : newPoints) { + assertFalse(point == point2); } - } catch (Exception e) { - e.printStackTrace(); - throw e; } } @Test public void testGetLinePointsFromPointsShouldCreateDefensiveCopy() { - try { - Point2D startPoint = new Point2D.Double(1, 7); - Point2D endPoint = new Point2D.Double(3, 5); - - List<Point2D> points = new ArrayList<>(); - points.add(new Point2D.Double(1.5, 2.5)); - points.add(new Point2D.Double(12, 13)); - points.add(new Point2D.Double(30, 40)); - - List<Point2D> newPoints = lineTransformation.getLinePointsFromPoints(startPoint, endPoint, points); - List<Point2D> newPoints2 = lineTransformation.getLinePointsFromPoints(startPoint, endPoint, points); - - for (Point2D point : newPoints2) { - for (Point2D point2 : newPoints) { - assertFalse(point == point2); - } + Point2D startPoint = new Point2D.Double(1, 7); + Point2D endPoint = new Point2D.Double(3, 5); + + List<Point2D> points = new ArrayList<>(); + points.add(new Point2D.Double(1.5, 2.5)); + points.add(new Point2D.Double(12, 13)); + points.add(new Point2D.Double(30, 40)); + + List<Point2D> newPoints = lineTransformation.getLinePointsFromPoints(startPoint, endPoint, points); + List<Point2D> newPoints2 = lineTransformation.getLinePointsFromPoints(startPoint, endPoint, points); + + for (Point2D point : newPoints2) { + for (Point2D point2 : newPoints) { + assertFalse(point == point2); } - } catch (Exception e) { - e.printStackTrace(); - throw e; } } @Test public void testGetProblematicPointsFromLine() { - try { - Point2D startPoint = new Point2D.Double(1, 7); - Point2D endPoint = new Point2D.Double(1, 5); + Point2D startPoint = new Point2D.Double(1, 7); + Point2D endPoint = new Point2D.Double(1, 5); - List<Point2D> points = new ArrayList<Point2D>(); - points.add(new Point2D.Double(1.5, 2.5)); - points.add(new Point2D.Double(12, 13)); - points.add(new Point2D.Double(30, 40)); + List<Point2D> points = new ArrayList<Point2D>(); + points.add(new Point2D.Double(1.5, 2.5)); + points.add(new Point2D.Double(12, 13)); + points.add(new Point2D.Double(30, 40)); - PolylineData line = new PolylineData(lineTransformation.getLinePointsFromPoints(startPoint, endPoint, points)); + PolylineData line = new PolylineData(lineTransformation.getLinePointsFromPoints(startPoint, endPoint, points)); - List<Point2D> newPoints = lineTransformation.getPointsFromLine(line); - assertNotNull(newPoints); + List<Point2D> newPoints = lineTransformation.getPointsFromLine(line); + assertNotNull(newPoints); - assertEquals(points.size(), newPoints.size()); + assertEquals(points.size(), newPoints.size()); - for (int i = 0; i < points.size(); i++) { - assertTrue("Invalid point after transformation: " + newPoints.get(i), - pointTransformation.isValidPoint(newPoints.get(i))); - double dist = points.get(i).distance(newPoints.get(i)); - assertTrue("Distance to big: " + dist + " for points " + points.get(i) + " and " + newPoints.get(i), - dist < 1e-6); - assertTrue(pointTransformation.isValidPoint(newPoints.get(i))); - } - } catch (Exception e) { - e.printStackTrace(); - throw e; + for (int i = 0; i < points.size(); i++) { + assertTrue("Invalid point after transformation: " + newPoints.get(i), + pointTransformation.isValidPoint(newPoints.get(i))); + double dist = points.get(i).distance(newPoints.get(i)); + assertTrue("Distance to big: " + dist + " for points " + points.get(i) + " and " + newPoints.get(i), + dist < 1e-6); + assertTrue(pointTransformation.isValidPoint(newPoints.get(i))); } } @Test public void testGetProblematicPointsFromLine2() { - try { - Point2D startPoint = new Point2D.Double(5, 1); - Point2D endPoint = new Point2D.Double(70, 1); - - List<Point2D> points = new ArrayList<Point2D>(); - points.add(new Point2D.Double(1.5, 2.5)); - points.add(new Point2D.Double(12, 13)); - points.add(new Point2D.Double(-12, -13)); - points.add(new Point2D.Double(30, 40)); - - PolylineData line = new PolylineData(lineTransformation.getLinePointsFromPoints(startPoint, endPoint, points)); - - List<Point2D> newPoints = lineTransformation.getPointsFromLine(line); - assertNotNull(newPoints); - - assertEquals(points.size(), newPoints.size()); - - for (int i = 0; i < points.size(); i++) { - assertTrue("Invalid point after transformation: " + newPoints.get(i), - pointTransformation.isValidPoint(newPoints.get(i))); - double dist = points.get(i).distance(newPoints.get(i)); - assertTrue("Distance to big: " + dist + " for points " + points.get(i) + " and " + newPoints.get(i), - dist < 1e-6); - assertTrue(pointTransformation.isValidPoint(newPoints.get(i))); - } - } catch (Exception e) { - e.printStackTrace(); - throw e; + Point2D startPoint = new Point2D.Double(5, 1); + Point2D endPoint = new Point2D.Double(70, 1); + + List<Point2D> points = new ArrayList<Point2D>(); + points.add(new Point2D.Double(1.5, 2.5)); + points.add(new Point2D.Double(12, 13)); + points.add(new Point2D.Double(-12, -13)); + points.add(new Point2D.Double(30, 40)); + + PolylineData line = new PolylineData(lineTransformation.getLinePointsFromPoints(startPoint, endPoint, points)); + + List<Point2D> newPoints = lineTransformation.getPointsFromLine(line); + assertNotNull(newPoints); + + assertEquals(points.size(), newPoints.size()); + + for (int i = 0; i < points.size(); i++) { + assertTrue("Invalid point after transformation: " + newPoints.get(i), + pointTransformation.isValidPoint(newPoints.get(i))); + double dist = points.get(i).distance(newPoints.get(i)); + assertTrue("Distance to big: " + dist + " for points " + points.get(i) + " and " + newPoints.get(i), + dist < 1e-6); + assertTrue(pointTransformation.isValidPoint(newPoints.get(i))); } } - @Test + @Test(expected = InvalidArgumentException.class) public void testGetLinePointsFromInvalidPoints() { - try { - Point2D startPoint = new Point2D.Double(Double.POSITIVE_INFINITY, 1); - Point2D endPoint = new Point2D.Double(70, 1); - - lineTransformation.getLinePointsFromPoints(startPoint, endPoint, new ArrayList<>()); - fail("Excepiton expceted"); - - } catch (InvalidArgumentException e) { - assertTrue(e.getMessage().contains("Invalid start point")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Point2D startPoint = new Point2D.Double(Double.POSITIVE_INFINITY, 1); + Point2D endPoint = new Point2D.Double(70, 1); + + lineTransformation.getLinePointsFromPoints(startPoint, endPoint, new ArrayList<>()); } - @Test + @Test(expected = InvalidArgumentException.class) public void testGetLinePointsFromInvalidPoints2() { - try { - Point2D endPoint = new Point2D.Double(Double.POSITIVE_INFINITY, 1); - Point2D startPoint = new Point2D.Double(70, 1); - - lineTransformation.getLinePointsFromPoints(startPoint, endPoint, new ArrayList<>()); - fail("Excepiton expceted"); - - } catch (InvalidArgumentException e) { - assertTrue(e.getMessage().contains("Invalid end point")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Point2D endPoint = new Point2D.Double(Double.POSITIVE_INFINITY, 1); + Point2D startPoint = new Point2D.Double(70, 1); + + lineTransformation.getLinePointsFromPoints(startPoint, endPoint, new ArrayList<>()); } - @Test + @Test(expected = InvalidArgumentException.class) public void testGetLinePointsFromInvalidPoints3() { - try { - Point2D endPoint = new Point2D.Double(70, 2); - Point2D startPoint = new Point2D.Double(70, 1); - List<Point2D> list = new ArrayList<>(); - list.add(new Point2D.Double(Double.POSITIVE_INFINITY, 1)); - - lineTransformation.getLinePointsFromPoints(startPoint, endPoint, list); - fail("Excepiton expceted"); - - } catch (InvalidArgumentException e) { - assertTrue(e.getMessage().contains("Invalid point")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Point2D endPoint = new Point2D.Double(70, 2); + Point2D startPoint = new Point2D.Double(70, 1); + List<Point2D> list = new ArrayList<>(); + list.add(new Point2D.Double(Double.POSITIVE_INFINITY, 1)); + + lineTransformation.getLinePointsFromPoints(startPoint, endPoint, list); } - @Test + @Test(expected = InvalidArgumentException.class) public void testGetPointsFromInvalidLine() { - try { - - lineTransformation.getPointsFromLine(null); - fail("Excepiton expceted"); - - } catch (InvalidArgumentException e) { - assertTrue(e.getMessage().contains("Line cannot be null")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + lineTransformation.getPointsFromLine(null); } - @Test + @Test(expected = InvalidArgumentException.class) public void testGetPointsFromInvalidLine2() { - try { - lineTransformation.getPointsFromLine(new PolylineData()); - fail("Excepiton expceted"); - } catch (InvalidArgumentException e) { - assertTrue(e.getMessage().contains("Invalid line passed as an argument")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + lineTransformation.getPointsFromLine(new PolylineData()); } - @Test + @Test(expected = InvalidArgumentException.class) public void testGetPointsFromInvalidLine3() { - try { - PolylineData line = new PolylineData(); - line.getPoints().add(new Point2D.Double()); - line.getPoints().add(new Point2D.Double()); - lineTransformation.getPointsFromLine(line); - fail("Excepiton expceted"); - } catch (InvalidArgumentException e) { - assertTrue(e.getMessage().contains("First and last point in the line must differ but found")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + PolylineData line = new PolylineData(); + line.getPoints().add(new Point2D.Double()); + line.getPoints().add(new Point2D.Double()); + lineTransformation.getPointsFromLine(line); } } diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/geometry/helper/CellDesignerPointTransformationTest.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/geometry/helper/CellDesignerPointTransformationTest.java index c7980de1da623565a8169d4ea6ae83889b0b9374..c8a1c21eacea1ec705046b438a57a901bed078d2 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/geometry/helper/CellDesignerPointTransformationTest.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/geometry/helper/CellDesignerPointTransformationTest.java @@ -1,66 +1,56 @@ package lcsb.mapviewer.converter.model.celldesigner.geometry.helper; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.Assert.*; import java.awt.geom.Point2D; -import org.apache.logging.log4j.*; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -public class CellDesignerPointTransformationTest { - Logger logger = LogManager.getLogger(CellDesignerPointTransformationTest .class); - - CellDesignerPointTransformation pt = new CellDesignerPointTransformation(); - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - /** - * Check if coordinetas are transformed in both ways correctly for this - * strange transformation with new base constsed of 3 points - */ - @Test - public void testConversionOfPointBases() { - try { - Point2D pointA = new Point2D.Double(1, 2); - Point2D pointB = new Point2D.Double(10, 12); - Point2D pointC = new Point2D.Double(4, 3); - Point2D pointP = new Point2D.Double(0.1, 2); - - Point2D pointO = pt.getCoordinatesInNormalBase(pointA, pointB, pointC, pointP); - Point2D pointQ = pt.getCoordinatesInCellDesignerBase(pointA, pointB, pointC, pointO); - assertEquals(0, pointQ.distance(pointP), 1e-6); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testNanTransformation() { - try { - Point2D pointA = new Point2D.Double(11429.886363636364, 11966.818181818182); - Point2D pointB = new Point2D.Double(11300.886363636364, 12056.363636363636); - Point2D pointC = new Point2D.Double(11429.886363636364, 12170.272727272728); - Point2D pointP = new Point2D.Double(11430.886363636364, 12052.045875614034); - - Point2D pointO = pt.getCoordinatesInNormalBase(pointA, pointB, pointC, pointP); - Point2D pointQ = pt.getCoordinatesInCellDesignerBase(pointA, pointB, pointC, pointO); - assertTrue(Double.isFinite(pointQ.getX())); - assertTrue(Double.isFinite(pointQ.getY())); - assertEquals(0, pointQ.distance(pointP), 1e-6); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.junit.*; + +import lcsb.mapviewer.converter.model.celldesigner.CellDesignerTestFunctions; + +public class CellDesignerPointTransformationTest extends CellDesignerTestFunctions { + Logger logger = LogManager.getLogger(CellDesignerPointTransformationTest.class); + + CellDesignerPointTransformation pt = new CellDesignerPointTransformation(); + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + /** + * Check if coordinates are transformed in both ways correctly for this strange + * transformation with new base consisted of 3 points + */ + @Test + public void testConversionOfPointBases() { + Point2D pointA = new Point2D.Double(1, 2); + Point2D pointB = new Point2D.Double(10, 12); + Point2D pointC = new Point2D.Double(4, 3); + Point2D pointP = new Point2D.Double(0.1, 2); + + Point2D pointO = pt.getCoordinatesInNormalBase(pointA, pointB, pointC, pointP); + Point2D pointQ = pt.getCoordinatesInCellDesignerBase(pointA, pointB, pointC, pointO); + assertEquals(0, pointQ.distance(pointP), 1e-6); + } + + @Test + public void testNanTransformation() { + Point2D pointA = new Point2D.Double(11429.886363636364, 11966.818181818182); + Point2D pointB = new Point2D.Double(11300.886363636364, 12056.363636363636); + Point2D pointC = new Point2D.Double(11429.886363636364, 12170.272727272728); + Point2D pointP = new Point2D.Double(11430.886363636364, 12052.045875614034); + + Point2D pointO = pt.getCoordinatesInNormalBase(pointA, pointB, pointC, pointP); + Point2D pointQ = pt.getCoordinatesInCellDesignerBase(pointA, pointB, pointC, pointO); + assertTrue(Double.isFinite(pointQ.getX())); + assertTrue(Double.isFinite(pointQ.getY())); + assertEquals(0, pointQ.distance(pointP), 1e-6); + } } diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/geometry/helper/CellDesignerPolygonTransformationTest.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/geometry/helper/CellDesignerPolygonTransformationTest.java index 1b1a46ccdb403cf04d1e97dad18a3ab82571951b..056731ff04c6a021deec794c51e7b992f6e41e80 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/geometry/helper/CellDesignerPolygonTransformationTest.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/geometry/helper/CellDesignerPolygonTransformationTest.java @@ -1,71 +1,51 @@ package lcsb.mapviewer.converter.model.celldesigner.geometry.helper; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - import java.awt.geom.Point2D; import java.util.ArrayList; import java.util.List; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import lcsb.mapviewer.common.exception.InvalidArgumentException; - -public class CellDesignerPolygonTransformationTest { - CellDesignerPolygonTransformation tranformation = new CellDesignerPolygonTransformation(); - - @AfterClass - public static void tearDownAfterClass() throws Exception { - } - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testGetPointOnInvalidPolygonByAnchor() { - try { - tranformation.getPointOnPolygonByAnchor(new ArrayList<>(), null); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - assertTrue(e.getMessage().contains("Invalid number of points")); - } - } - - @Test - public void testGetPointOnPolygonByInvalidAnchor() { - try { - List<Point2D> list = new ArrayList<>(); - for (int i = 0; i < CellDesignerAnchor.DIFFERENT_ANCHORS / 2; i++) { - list.add(new Point2D.Double()); - } - tranformation.getPointOnPolygonByAnchor(list, null); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - assertTrue(e.getMessage().contains("Invalid anchor")); - } - } - - @Test - public void testGetPointOnPolygonByInvalidAnchor2() { - try { - List<Point2D> list = new ArrayList<>(); - for (int i = 0; i < CellDesignerAnchor.DIFFERENT_ANCHORS; i++) { - list.add(new Point2D.Double()); - } - tranformation.getPointOnPolygonByAnchor(list, null); - tranformation.getPointOnPolygonByAnchor(new ArrayList<>(), null); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - assertTrue(e.getMessage().contains("Invalid anchor")); - } - } +import lcsb.mapviewer.converter.model.celldesigner.CellDesignerTestFunctions; + +public class CellDesignerPolygonTransformationTest extends CellDesignerTestFunctions { + CellDesignerPolygonTransformation tranformation = new CellDesignerPolygonTransformation(); + + @AfterClass + public static void tearDownAfterClass() throws Exception { + } + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test(expected = InvalidArgumentException.class) + public void testGetPointOnInvalidPolygonByAnchor() { + tranformation.getPointOnPolygonByAnchor(new ArrayList<>(), null); + } + + @Test(expected = InvalidArgumentException.class) + public void testGetPointOnPolygonByInvalidAnchor() { + List<Point2D> list = new ArrayList<>(); + for (int i = 0; i < CellDesignerAnchor.DIFFERENT_ANCHORS / 2; i++) { + list.add(new Point2D.Double()); + } + tranformation.getPointOnPolygonByAnchor(list, null); + } + + @Test(expected = InvalidArgumentException.class) + public void testGetPointOnPolygonByInvalidAnchor2() { + List<Point2D> list = new ArrayList<>(); + for (int i = 0; i < CellDesignerAnchor.DIFFERENT_ANCHORS; i++) { + list.add(new Point2D.Double()); + } + tranformation.getPointOnPolygonByAnchor(list, null); + tranformation.getPointOnPolygonByAnchor(new ArrayList<>(), null); + } } diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/reaction/KineticsXmlParserTest.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/reaction/KineticsXmlParserTest.java index 29c5bc2ccd941c64968d9cc6fdbf185a804035b1..4a4c0c5eba99255510813f5627a9a91d0fdd4130 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/reaction/KineticsXmlParserTest.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/reaction/KineticsXmlParserTest.java @@ -110,7 +110,6 @@ public class KineticsXmlParserTest extends CellDesignerTestFunctions { @Test public void testToXmlDefinition() throws Exception { - try { Model model = super.getModelForFile("testFiles/reactions/kinetics.xml"); CellDesignerElementCollection elements = new CellDesignerElementCollection(); for (Element element : model.getElements()) { @@ -123,10 +122,6 @@ public class KineticsXmlParserTest extends CellDesignerTestFunctions { assertNotNull(xml); assertTrue(xml.indexOf(elements.getElementId(kinetics.getElements().iterator().next())) >= 0); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } } @Test diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/reaction/ModificationReactionTest.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/reaction/ModificationReactionTest.java index a16a83d1801c622edee8b85d202bd7e09a00b7ad..01869c993a98048d97dbcf5e2f87b3a09b3bac5e 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/reaction/ModificationReactionTest.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/reaction/ModificationReactionTest.java @@ -1,25 +1,18 @@ package lcsb.mapviewer.converter.model.celldesigner.reaction; -import static org.junit.Assert.assertEquals; +import static org.junit.Assert.*; import java.io.FileInputStream; -import org.apache.logging.log4j.*; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.junit.*; import lcsb.mapviewer.converter.ConverterParams; import lcsb.mapviewer.converter.model.celldesigner.CellDesignerTestFunctions; import lcsb.mapviewer.converter.model.celldesigner.CellDesignerXmlParser; import lcsb.mapviewer.model.map.model.Model; -import lcsb.mapviewer.model.map.reaction.type.CatalysisReaction; -import lcsb.mapviewer.model.map.reaction.type.InhibitionReaction; -import lcsb.mapviewer.model.map.reaction.type.ModulationReaction; -import lcsb.mapviewer.model.map.reaction.type.PhysicalStimulationReaction; -import lcsb.mapviewer.model.map.reaction.type.TriggerReaction; -import lcsb.mapviewer.model.map.reaction.type.UnknownCatalysisReaction; -import lcsb.mapviewer.model.map.reaction.type.UnknownInhibitionReaction; +import lcsb.mapviewer.model.map.reaction.type.*; public class ModificationReactionTest extends CellDesignerTestFunctions { Logger logger = LogManager.getLogger(ModificationReactionTest.class); @@ -34,93 +27,57 @@ public class ModificationReactionTest extends CellDesignerTestFunctions { @Test public void testCatalysisReaction() throws Exception { - try { - CellDesignerXmlParser parser = new CellDesignerXmlParser(); - FileInputStream fis = new FileInputStream("testFiles/reactions/modification_reaction/catalysis.xml"); - Model model = parser.createModel(new ConverterParams().inputStream(fis)); - assertEquals(CatalysisReaction.class, model.getReactionByReactionId("re1").getClass()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + CellDesignerXmlParser parser = new CellDesignerXmlParser(); + FileInputStream fis = new FileInputStream("testFiles/reactions/modification_reaction/catalysis.xml"); + Model model = parser.createModel(new ConverterParams().inputStream(fis)); + assertEquals(CatalysisReaction.class, model.getReactionByReactionId("re1").getClass()); } @Test public void testInhibitionReaction() throws Exception { - try { - CellDesignerXmlParser parser = new CellDesignerXmlParser(); - FileInputStream fis = new FileInputStream("testFiles/reactions/modification_reaction/inhibition.xml"); - Model model = parser.createModel(new ConverterParams().inputStream(fis)); - assertEquals(InhibitionReaction.class, model.getReactionByReactionId("re2").getClass()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + CellDesignerXmlParser parser = new CellDesignerXmlParser(); + FileInputStream fis = new FileInputStream("testFiles/reactions/modification_reaction/inhibition.xml"); + Model model = parser.createModel(new ConverterParams().inputStream(fis)); + assertEquals(InhibitionReaction.class, model.getReactionByReactionId("re2").getClass()); } @Test public void testModulationReaction() throws Exception { - try { - CellDesignerXmlParser parser = new CellDesignerXmlParser(); - FileInputStream fis = new FileInputStream("testFiles/reactions/modification_reaction/modulation.xml"); - Model model = parser.createModel(new ConverterParams().inputStream(fis)); - assertEquals(ModulationReaction.class, model.getReactionByReactionId("re1").getClass()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + CellDesignerXmlParser parser = new CellDesignerXmlParser(); + FileInputStream fis = new FileInputStream("testFiles/reactions/modification_reaction/modulation.xml"); + Model model = parser.createModel(new ConverterParams().inputStream(fis)); + assertEquals(ModulationReaction.class, model.getReactionByReactionId("re1").getClass()); } @Test public void testPhysicalStimulationReaction() throws Exception { - try { - CellDesignerXmlParser parser = new CellDesignerXmlParser(); - FileInputStream fis = new FileInputStream("testFiles/reactions/modification_reaction/physical_stimulation.xml"); - Model model = parser.createModel(new ConverterParams().inputStream(fis)); - assertEquals(PhysicalStimulationReaction.class, model.getReactionByReactionId("re1").getClass()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + CellDesignerXmlParser parser = new CellDesignerXmlParser(); + FileInputStream fis = new FileInputStream("testFiles/reactions/modification_reaction/physical_stimulation.xml"); + Model model = parser.createModel(new ConverterParams().inputStream(fis)); + assertEquals(PhysicalStimulationReaction.class, model.getReactionByReactionId("re1").getClass()); } @Test public void testTriggerReaction() throws Exception { - try { - CellDesignerXmlParser parser = new CellDesignerXmlParser(); - FileInputStream fis = new FileInputStream("testFiles/reactions/modification_reaction/trigger.xml"); - Model model = parser.createModel(new ConverterParams().inputStream(fis)); - assertEquals(TriggerReaction.class, model.getReactionByReactionId("re1").getClass()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + CellDesignerXmlParser parser = new CellDesignerXmlParser(); + FileInputStream fis = new FileInputStream("testFiles/reactions/modification_reaction/trigger.xml"); + Model model = parser.createModel(new ConverterParams().inputStream(fis)); + assertEquals(TriggerReaction.class, model.getReactionByReactionId("re1").getClass()); } @Test public void testUnknownCatalysisReaction() throws Exception { - try { - CellDesignerXmlParser parser = new CellDesignerXmlParser(); - FileInputStream fis = new FileInputStream("testFiles/reactions/modification_reaction/unknown_catalysis.xml"); - Model model = parser.createModel(new ConverterParams().inputStream(fis)); - assertEquals(UnknownCatalysisReaction.class, model.getReactionByReactionId("re1").getClass()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + CellDesignerXmlParser parser = new CellDesignerXmlParser(); + FileInputStream fis = new FileInputStream("testFiles/reactions/modification_reaction/unknown_catalysis.xml"); + Model model = parser.createModel(new ConverterParams().inputStream(fis)); + assertEquals(UnknownCatalysisReaction.class, model.getReactionByReactionId("re1").getClass()); } @Test public void testUnknownInhibitionReaction() throws Exception { - try { - CellDesignerXmlParser parser = new CellDesignerXmlParser(); - FileInputStream fis = new FileInputStream("testFiles/reactions/modification_reaction/unknown_inhibition.xml"); - Model model = parser.createModel(new ConverterParams().inputStream(fis)); - assertEquals(UnknownInhibitionReaction.class, model.getReactionByReactionId("re1").getClass()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + CellDesignerXmlParser parser = new CellDesignerXmlParser(); + FileInputStream fis = new FileInputStream("testFiles/reactions/modification_reaction/unknown_inhibition.xml"); + Model model = parser.createModel(new ConverterParams().inputStream(fis)); + assertEquals(UnknownInhibitionReaction.class, model.getReactionByReactionId("re1").getClass()); } } diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/reaction/ReactionFromXmlTest.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/reaction/ReactionFromXmlTest.java index ad59c9fd21bb38c08bc3789c823ca4827a854c38..461ec80c528c2a8c7405b5369215825600f1bf64 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/reaction/ReactionFromXmlTest.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/reaction/ReactionFromXmlTest.java @@ -1,12 +1,6 @@ package lcsb.mapviewer.converter.model.celldesigner.reaction; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.mockito.Mockito; import lcsb.mapviewer.common.exception.InvalidArgumentException; @@ -15,9 +9,7 @@ import lcsb.mapviewer.converter.model.celldesigner.CellDesignerTestFunctions; import lcsb.mapviewer.converter.model.celldesigner.structure.CellDesignerGenericProtein; import lcsb.mapviewer.model.map.model.Model; import lcsb.mapviewer.model.map.model.ModelFullIndexed; -import lcsb.mapviewer.model.map.reaction.Product; -import lcsb.mapviewer.model.map.reaction.Reactant; -import lcsb.mapviewer.model.map.reaction.Reaction; +import lcsb.mapviewer.model.map.reaction.*; import lcsb.mapviewer.model.map.reaction.type.TwoProductReactionInterface; import lcsb.mapviewer.model.map.species.GenericProtein; import lcsb.mapviewer.model.map.species.Species; @@ -59,537 +51,241 @@ public class ReactionFromXmlTest extends CellDesignerTestFunctions { public void tearDown() throws Exception { } - @Test + @Test(expected = ReactionParserException.class) public void testInvalid() throws Exception { - try { - parser.getReaction(super.getNodeFromXmlString(readFile("testFiles/invalid/reaction.xml")), model); - fail("Exception expected"); - } catch (ReactionParserException e) { - assertTrue(e.getMessage().contains("kineticLaw node doesn't have math subnode")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test + parser.getReaction(super.getNodeFromXmlString(readFile("testFiles/invalid/reaction.xml")), model); + } + + @Test(expected = ReactionParserException.class) public void testInvalid3() throws Exception { - try { - parser.getReaction(super.getNodeFromXmlString(readFile("testFiles/invalid/reaction3.xml")), model); - fail("Exception expected"); - } catch (ReactionParserException e) { - assertTrue(e.getMessage().contains("Unknown element of reaction")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test + parser.getReaction(super.getNodeFromXmlString(readFile("testFiles/invalid/reaction3.xml")), model); + } + + @Test(expected = ReactionParserException.class) public void testInvalid4() throws Exception { - try { - parser.getReaction(super.getNodeFromXmlString(readFile("testFiles/invalid/reaction4.xml")), model); - fail("Exception expected"); - } catch (ReactionParserException e) { - assertTrue(e.getMessage().contains("No annotation node in reaction")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test + parser.getReaction(super.getNodeFromXmlString(readFile("testFiles/invalid/reaction4.xml")), model); + } + + @Test(expected = ReactionParserException.class) public void testInvalid5() throws Exception { - try { - parser.getReaction(super.getNodeFromXmlString(readFile("testFiles/invalid/reaction5.xml")), model); - fail("Exception expected"); - } catch (ReactionParserException e) { - assertTrue(e.getMessage().contains("Problem with parsing RDF")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test + parser.getReaction(super.getNodeFromXmlString(readFile("testFiles/invalid/reaction5.xml")), model); + } + + @Test(expected = ReactionParserException.class) public void testInvalid6() throws Exception { - try { - parser.getReaction(super.getNodeFromXmlString(readFile("testFiles/invalid/reaction6.xml")), model); - fail("Exception expected"); - } catch (ReactionParserException e) { - assertTrue(e.getMessage().contains("Unknown element of reaction/annotation")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test + parser.getReaction(super.getNodeFromXmlString(readFile("testFiles/invalid/reaction6.xml")), model); + } + + @Test(expected = ReactionParserException.class) public void testInvalid7() throws Exception { - try { - parser.getReaction(super.getNodeFromXmlString(readFile("testFiles/invalid/reaction7.xml")), model); - fail("Exception expected"); - } catch (ReactionParserException e) { - assertTrue(e.getMessage().contains("Unknown element of celldesigner:baseReactants")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test + parser.getReaction(super.getNodeFromXmlString(readFile("testFiles/invalid/reaction7.xml")), model); + } + + @Test(expected = ReactionParserException.class) public void testInvalid8() throws Exception { - try { - parser.getReaction(super.getNodeFromXmlString(readFile("testFiles/invalid/reaction8.xml")), model); - fail("Exception expected"); - } catch (ReactionParserException e) { - assertTrue(e.getMessage().contains("Unknown element of celldesigner:baseProducts")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test + parser.getReaction(super.getNodeFromXmlString(readFile("testFiles/invalid/reaction8.xml")), model); + } + + @Test(expected = ReactionParserException.class) public void testInvalid9() throws Exception { - try { - parser.getReaction(super.getNodeFromXmlString(readFile("testFiles/invalid/reaction9.xml")), model); - fail("Exception expected"); - } catch (ReactionParserException e) { - assertTrue("Invalid message: " + e.getMessage(), - e.getMessage().contains("Unknown element of celldesigner:connectScheme")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test + parser.getReaction(super.getNodeFromXmlString(readFile("testFiles/invalid/reaction9.xml")), model); + } + + @Test(expected = ReactionParserException.class) public void testInvalid10() throws Exception { - try { - parser.getReaction(super.getNodeFromXmlString(readFile("testFiles/invalid/reaction10.xml")), model); - fail("Exception expected"); - } catch (ReactionParserException e) { - assertTrue(e.getMessage().contains("Unknown element of reaction/celldesigner:extension")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test + parser.getReaction(super.getNodeFromXmlString(readFile("testFiles/invalid/reaction10.xml")), model); + } + + @Test(expected = ReactionParserException.class) public void testInvalid11() throws Exception { - try { - parser.getReaction(super.getNodeFromXmlString(readFile("testFiles/invalid/reaction11.xml")), model); - fail("Exception expected"); - } catch (ReactionParserException e) { - assertTrue(e.getMessage().contains("No connectScheme node")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test + parser.getReaction(super.getNodeFromXmlString(readFile("testFiles/invalid/reaction11.xml")), model); + } + + @Test(expected = ReactionParserException.class) public void testInvalid12() throws Exception { - try { - parser.getReaction(super.getNodeFromXmlString(readFile("testFiles/invalid/reaction12.xml")), model); - fail("Exception expected"); - } catch (ReactionParserException e) { - assertTrue(e.getMessage().contains("Unknown node type")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test + parser.getReaction(super.getNodeFromXmlString(readFile("testFiles/invalid/reaction12.xml")), model); + } + + @Test(expected = ReactionParserException.class) public void testInvalid14() throws Exception { - try { - parser.getReaction(super.getNodeFromXmlString(readFile("testFiles/invalid/reaction14.xml")), model); - fail("Exception expected"); - } catch (ReactionParserException e) { - assertTrue(e.getMessage().contains("Missing gate member connecting members")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test + parser.getReaction(super.getNodeFromXmlString(readFile("testFiles/invalid/reaction14.xml")), model); + } + + @Test(expected = ReactionParserException.class) public void testInvalid15() throws Exception { - try { - parser.getReaction(super.getNodeFromXmlString(readFile("testFiles/invalid/reaction15.xml")), model); - fail("Exception expected"); - } catch (ReactionParserException e) { - assertTrue(e.getMessage().contains("Couldn't find type of BOOLEAN_LOGIC_GATE")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test + parser.getReaction(super.getNodeFromXmlString(readFile("testFiles/invalid/reaction15.xml")), model); + } + + @Test(expected = ReactionParserException.class) public void testInvalid16() throws Exception { - try { - parser.getReaction(super.getNodeFromXmlString(readFile("testFiles/invalid/reaction16.xml")), model); - fail("Exception expected"); - } catch (ReactionParserException e) { - assertTrue("Invalid message: " + e.getMessage(), - e.getMessage().contains("Unknown element of celldesigner:listOfReactantLinks")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test + parser.getReaction(super.getNodeFromXmlString(readFile("testFiles/invalid/reaction16.xml")), model); + } + + @Test(expected = ReactionParserException.class) public void testInvalid17() throws Exception { - try { - parser.getReaction(super.getNodeFromXmlString(readFile("testFiles/invalid/reaction17.xml")), model); - fail("Exception expected"); - } catch (ReactionParserException e) { - assertTrue("Invalid message: " + e.getMessage(), - e.getMessage().contains("Unknown element of celldesigner:reactantLink")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test + parser.getReaction(super.getNodeFromXmlString(readFile("testFiles/invalid/reaction17.xml")), model); + } + + @Test(expected = ReactionParserException.class) public void testInvalid19() throws Exception { - try { - parser.getReaction(super.getNodeFromXmlString(readFile("testFiles/invalid/reaction19.xml")), model); - fail("Exception expected"); - } catch (ReactionParserException e) { - assertTrue("Invalid message: " + e.getMessage(), e.getMessage().contains("Alias doesn't exist")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test + parser.getReaction(super.getNodeFromXmlString(readFile("testFiles/invalid/reaction19.xml")), model); + } + + @Test(expected = ReactionParserException.class) public void testInvalid20() throws Exception { - try { - parser.getReaction(super.getNodeFromXmlString(readFile("testFiles/invalid/reaction20.xml")), model); - fail("Exception expected"); - } catch (ReactionParserException e) { - assertTrue("Invalid message: " + e.getMessage(), - e.getMessage().contains("Unknown element of celldesigner:listOfProductLinks")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test + parser.getReaction(super.getNodeFromXmlString(readFile("testFiles/invalid/reaction20.xml")), model); + } + + @Test(expected = ReactionParserException.class) public void testInvalid21() throws Exception { - try { - parser.getReaction(super.getNodeFromXmlString(readFile("testFiles/invalid/reaction21.xml")), model); - fail("Exception expected"); - } catch (ReactionParserException e) { - assertTrue("Invalid message: " + e.getMessage(), - e.getMessage().contains("Unknown element of celldesigner:reactantLink")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test + parser.getReaction(super.getNodeFromXmlString(readFile("testFiles/invalid/reaction21.xml")), model); + } + + @Test(expected = ReactionParserException.class) public void testInvalid23() throws Exception { - try { - parser.getReaction(super.getNodeFromXmlString(readFile("testFiles/invalid/reaction23.xml")), model); - fail("Exception expected"); - } catch (ReactionParserException e) { - assertTrue("Invalid message: " + e.getMessage(), e.getMessage().contains("Alias doesn't exist")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test + parser.getReaction(super.getNodeFromXmlString(readFile("testFiles/invalid/reaction23.xml")), model); + } + + @Test(expected = ReactionParserException.class) public void testInvalid24() throws Exception { - try { - parser.getReaction(super.getNodeFromXmlString(readFile("testFiles/invalid/reaction24.xml")), model); - fail("Exception expected"); - } catch (ReactionParserException e) { - assertTrue("Invalid message: " + e.getMessage(), - e.getMessage().contains("Unknown element of celldesigner:listOfModification")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test + parser.getReaction(super.getNodeFromXmlString(readFile("testFiles/invalid/reaction24.xml")), model); + } + + @Test(expected = ReactionParserException.class) public void testInvalid26() throws Exception { - try { - parser.getReaction(super.getNodeFromXmlString(readFile("testFiles/invalid/reaction26.xml")), model); - fail("Exception expected"); - } catch (ReactionParserException e) { - assertTrue("Invalid message: " + e.getMessage(), e.getMessage().contains("Unknown alias")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test + parser.getReaction(super.getNodeFromXmlString(readFile("testFiles/invalid/reaction26.xml")), model); + } + + @Test(expected = ReactionParserException.class) public void testInvalid28() throws Exception { - try { - parser.getReaction(super.getNodeFromXmlString(readFile("testFiles/invalid/reaction28.xml")), model); - fail("Exception expected"); - } catch (ReactionParserException e) { - assertTrue("Invalid message: " + e.getMessage(), - e.getMessage().contains("Unknown element of celldesigner:connectScheme")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test + parser.getReaction(super.getNodeFromXmlString(readFile("testFiles/invalid/reaction28.xml")), model); + } + + @Test(expected = ReactionParserException.class) public void testInvalid29() throws Exception { - try { - parser.getReaction(super.getNodeFromXmlString(readFile("testFiles/invalid/reaction29.xml")), model); - fail("Exception expected"); - } catch (ReactionParserException e) { - assertTrue("Invalid message: " + e.getMessage(), - e.getMessage().contains("Unknown element of celldesigner:listOfModification")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test + parser.getReaction(super.getNodeFromXmlString(readFile("testFiles/invalid/reaction29.xml")), model); + } + + @Test(expected = ReactionParserException.class) public void testInvalid30() throws Exception { - try { - parser.getReaction(super.getNodeFromXmlString(readFile("testFiles/invalid/reaction30.xml")), model); - fail("Exception expected"); - } catch (ReactionParserException e) { - assertTrue("Invalid message: " + e.getMessage(), - e.getMessage().contains("Unknown element of reaction/celldesigner:baseReactant")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test + parser.getReaction(super.getNodeFromXmlString(readFile("testFiles/invalid/reaction30.xml")), model); + } + + @Test(expected = ReactionParserException.class) public void testInvalid31() throws Exception { - try { - parser.getReaction(super.getNodeFromXmlString(readFile("testFiles/invalid/reaction31.xml")), model); - fail("Exception expected"); - } catch (ReactionParserException e) { - assertTrue("Invalid message: " + e.getMessage(), e.getMessage().contains("Alias with id")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test + parser.getReaction(super.getNodeFromXmlString(readFile("testFiles/invalid/reaction31.xml")), model); + } + + @Test(expected = ReactionParserException.class) public void testInvalid33() throws Exception { - try { - parser.getReaction(super.getNodeFromXmlString(readFile("testFiles/invalid/reaction33.xml")), model); - fail("Exception expected"); - } catch (ReactionParserException e) { - assertTrue("Invalid message: " + e.getMessage(), - e.getMessage().contains("Unknown element of reaction/celldesigner:baseReactant")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test + parser.getReaction(super.getNodeFromXmlString(readFile("testFiles/invalid/reaction33.xml")), model); + } + + @Test(expected = ReactionParserException.class) public void testInvalid34() throws Exception { - try { - parser.getReaction(super.getNodeFromXmlString(readFile("testFiles/invalid/reaction34.xml")), model); - fail("Exception expected"); - } catch (ReactionParserException e) { - assertTrue("Invalid message: " + e.getMessage(), e.getMessage().contains("Alias with id")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test + parser.getReaction(super.getNodeFromXmlString(readFile("testFiles/invalid/reaction34.xml")), model); + } + + @Test(expected = ReactionParserException.class) public void testInvalid36() throws Exception { - try { - parser.getReaction(super.getNodeFromXmlString(readFile("testFiles/invalid/reaction36.xml")), model); - fail("Exception expected"); - } catch (ReactionParserException e) { - assertTrue("Invalid message: " + e.getMessage(), - e.getMessage().contains("Unknown element of reaction/celldesigner:baseProduct")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test + parser.getReaction(super.getNodeFromXmlString(readFile("testFiles/invalid/reaction36.xml")), model); + } + + @Test(expected = ReactionParserException.class) public void testInvalidReaction() throws Exception { - try { - // test situation when createProperTypeReaction returns reaction of - // unknown type - ReactionFromXml parser = new ReactionFromXml(null, false) { - Reaction createProperTypeReaction(String type, Reaction result) { - return result; - } - }; - parser.getReaction(super.getNodeFromXmlString(readFile("testFiles/xmlNodeTestExamples/reaction_transport.xml")), - model); - fail("Exception expected"); - - } catch (ReactionParserException e) { - assertTrue(e.getMessage().contains("Problem with parsing lines. Unknown reaction")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test + // test situation when createProperTypeReaction returns reaction of + // unknown type + ReactionFromXml parser = new ReactionFromXml(null, false) { + Reaction createProperTypeReaction(String type, Reaction result) { + return result; + } + }; + parser.getReaction(super.getNodeFromXmlString(readFile("testFiles/xmlNodeTestExamples/reaction_transport.xml")), + model); + } + + @Test(expected = ReactionParserException.class) public void testInvalidReaction2() throws Exception { - try { - // test situation when createProperTypeReaction returns reaction of - // unknown type that implements TwoProductReactionInterface - - ReactionFromXml parser = new ReactionFromXml(null, false) { - Reaction createProperTypeReaction(String type, Reaction reaction) { - Reaction result = Mockito.mock(Reaction.class, - Mockito.withSettings().extraInterfaces(TwoProductReactionInterface.class)); - Mockito.when(result.getReactants()).thenReturn(reaction.getReactants()); - Mockito.when(result.getProducts()).thenReturn(reaction.getProducts()); - return result; - } - }; - - parser.getReaction( - super.getNodeFromXmlString(readFile("testFiles/xmlNodeTestExamples/reaction_dissociation_with_addition.xml")), - model); - fail("Exception expected"); - - } catch (ReactionParserException e) { - assertTrue(e.getMessage().contains("Invalid reaction type")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test + // test situation when createProperTypeReaction returns reaction of + // unknown type that implements TwoProductReactionInterface + + ReactionFromXml parser = new ReactionFromXml(null, false) { + Reaction createProperTypeReaction(String type, Reaction reaction) { + Reaction result = Mockito.mock(Reaction.class, + Mockito.withSettings().extraInterfaces(TwoProductReactionInterface.class)); + Mockito.when(result.getReactants()).thenReturn(reaction.getReactants()); + Mockito.when(result.getProducts()).thenReturn(reaction.getProducts()); + return result; + } + }; + + parser.getReaction( + super.getNodeFromXmlString(readFile("testFiles/xmlNodeTestExamples/reaction_dissociation_with_addition.xml")), + model); + } + + @Test(expected = ReactionParserException.class) public void testInvalidReaction3() throws Exception { - try { - // test situation when createOperatorsForTwoProductReaction encounter - // reaction with two many base reactants - - ReactionFromXml parser = new ReactionFromXml(null, false) { - Reaction createProperTypeReaction(String type, Reaction result) throws ReactionParserException { - Reaction r = super.createProperTypeReaction(type, result); - r.addReactant(new Reactant()); - return r; - } - }; - parser.getReaction( - super.getNodeFromXmlString(readFile("testFiles/xmlNodeTestExamples/reaction_dissociation_with_addition.xml")), - model); - fail("Exception expected"); - - } catch (ReactionParserException e) { - assertTrue(e.getMessage().contains("Reaction has more than one reactant")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test + // test situation when createOperatorsForTwoProductReaction encounter + // reaction with two many base reactants + + ReactionFromXml parser = new ReactionFromXml(null, false) { + Reaction createProperTypeReaction(String type, Reaction result) throws ReactionParserException { + Reaction r = super.createProperTypeReaction(type, result); + r.addReactant(new Reactant()); + return r; + } + }; + parser.getReaction( + super.getNodeFromXmlString(readFile("testFiles/xmlNodeTestExamples/reaction_dissociation_with_addition.xml")), + model); + } + + @Test(expected = ReactionParserException.class) public void testInvalidReaction4() throws Exception { - try { - // test situation when createOperatorsForTwoProductReaction encounter - // reaction with two many base products - - ReactionFromXml parser = new ReactionFromXml(null, false) { - Reaction createProperTypeReaction(String type, Reaction result) throws ReactionParserException { - Reaction r = super.createProperTypeReaction(type, result); - r.addProduct(new Product()); - return r; - } - }; - parser.getReaction( - super.getNodeFromXmlString(readFile("testFiles/xmlNodeTestExamples/reaction_dissociation_with_addition.xml")), - model); - fail("Exception expected"); - - } catch (ReactionParserException e) { - assertTrue(e.getMessage().contains("Too many products")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test + // test situation when createOperatorsForTwoProductReaction encounter + // reaction with two many base products + + ReactionFromXml parser = new ReactionFromXml(null, false) { + Reaction createProperTypeReaction(String type, Reaction result) throws ReactionParserException { + Reaction r = super.createProperTypeReaction(type, result); + r.addProduct(new Product()); + return r; + } + }; + parser.getReaction( + super.getNodeFromXmlString(readFile("testFiles/xmlNodeTestExamples/reaction_dissociation_with_addition.xml")), + model); + } + + @Test(expected = ReactionParserException.class) public void testInvalidReaction7() throws Exception { - try { - // test situation when createOperatorsForTwoReactantReaction encounter - // reaction with two many base products - - ReactionFromXml parser = new ReactionFromXml(null, false) { - Reaction createProperTypeReaction(String type, Reaction result) throws ReactionParserException { - Reaction r = super.createProperTypeReaction(type, result); - r.addProduct(new Product()); - return r; - } - }; - parser.getReaction(super.getNodeFromXmlString(readFile("testFiles/xmlNodeTestExamples/reaction_heterodimer.xml")), - model); - fail("Exception expected"); - - } catch (ReactionParserException e) { - assertTrue(e.getMessage().contains("Reaction has more than one product")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test + // test situation when createOperatorsForTwoReactantReaction encounter + // reaction with two many base products + + ReactionFromXml parser = new ReactionFromXml(null, false) { + Reaction createProperTypeReaction(String type, Reaction result) throws ReactionParserException { + Reaction r = super.createProperTypeReaction(type, result); + r.addProduct(new Product()); + return r; + } + }; + parser.getReaction(super.getNodeFromXmlString(readFile("testFiles/xmlNodeTestExamples/reaction_heterodimer.xml")), + model); + } + + @Test(expected = InvalidArgumentException.class) public void testParseInvalidEditPointsString() throws Exception { - try { - ReactionFromXml parser = new ReactionFromXml(null, false); + ReactionFromXml parser = new ReactionFromXml(null, false); - parser.parseEditPointsString("1"); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - assertTrue(e.getMessage().contains("Invalid editPoint string")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + parser.parseEditPointsString("1"); } - @Test + @Test(expected = InvalidArgumentException.class) public void testParseInvalidEditPointsString2() throws Exception { - try { - ReactionFromXml parser = new ReactionFromXml(null, false); - - parser.parseEditPointsString("1,Infinity"); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - assertTrue(e.getMessage().contains("Invalid point parsed from input string")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + ReactionFromXml parser = new ReactionFromXml(null, false); + + parser.parseEditPointsString("1,Infinity"); } } diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/reaction/ReactionLineDataTest.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/reaction/ReactionLineDataTest.java index c30d2a3a08fe7252c4c5315d94e60e63018d5723..08b6429d490c2fd45a31233cb6ea8c3f36458a9b 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/reaction/ReactionLineDataTest.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/reaction/ReactionLineDataTest.java @@ -1,18 +1,14 @@ package lcsb.mapviewer.converter.model.celldesigner.reaction; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import static org.junit.Assert.*; + +import org.junit.*; import org.mockito.Mockito; +import lcsb.mapviewer.converter.model.celldesigner.CellDesignerTestFunctions; import lcsb.mapviewer.model.map.reaction.Reaction; -public class ReactionLineDataTest { +public class ReactionLineDataTest extends CellDesignerTestFunctions { @Before public void setUp() throws Exception { @@ -39,17 +35,9 @@ public class ReactionLineDataTest { } } - @Test + @Test(expected = ReactionParserException.class) public void testCreateInvalidReaction() throws Exception { - try { - ReactionLineData.TRANSPORT.createReaction(Mockito.mock(Reaction.class)); - fail("Exception expected"); - } catch (ReactionParserException e) { - assertTrue(e.getMessage().contains("Problem with creation the new instance of reaction")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + ReactionLineData.TRANSPORT.createReaction(Mockito.mock(Reaction.class)); } } diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/reaction/ReactionParserTests.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/reaction/ReactionParserTests.java index c957380b2c0d98359fad54a553f189662721255c..893fccc418bd91a6aa8a3e7c3953c8365e30a7ae 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/reaction/ReactionParserTests.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/reaction/ReactionParserTests.java @@ -1,67 +1,31 @@ package lcsb.mapviewer.converter.model.celldesigner.reaction; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.junit.Assert.*; import java.awt.Color; import java.awt.geom.Line2D; import java.awt.geom.Point2D; -import java.util.HashSet; -import java.util.List; -import java.util.Set; +import java.util.*; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.w3c.dom.Node; import lcsb.mapviewer.common.Configuration; import lcsb.mapviewer.converter.model.celldesigner.CellDesignerElementCollection; import lcsb.mapviewer.converter.model.celldesigner.CellDesignerTestFunctions; import lcsb.mapviewer.converter.model.celldesigner.structure.CellDesignerGenericProtein; -import lcsb.mapviewer.model.graphics.ArrowType; -import lcsb.mapviewer.model.graphics.LineType; -import lcsb.mapviewer.model.graphics.PolylineData; +import lcsb.mapviewer.model.graphics.*; import lcsb.mapviewer.model.map.model.Model; import lcsb.mapviewer.model.map.model.ModelFullIndexed; -import lcsb.mapviewer.model.map.reaction.AndOperator; -import lcsb.mapviewer.model.map.reaction.AssociationOperator; -import lcsb.mapviewer.model.map.reaction.DissociationOperator; -import lcsb.mapviewer.model.map.reaction.Modifier; -import lcsb.mapviewer.model.map.reaction.NandOperator; -import lcsb.mapviewer.model.map.reaction.NodeOperator; -import lcsb.mapviewer.model.map.reaction.OrOperator; -import lcsb.mapviewer.model.map.reaction.Product; -import lcsb.mapviewer.model.map.reaction.Reactant; -import lcsb.mapviewer.model.map.reaction.Reaction; -import lcsb.mapviewer.model.map.reaction.SplitOperator; -import lcsb.mapviewer.model.map.reaction.TruncationOperator; -import lcsb.mapviewer.model.map.reaction.UnknownOperator; -import lcsb.mapviewer.model.map.reaction.type.DissociationReaction; -import lcsb.mapviewer.model.map.reaction.type.HeterodimerAssociationReaction; -import lcsb.mapviewer.model.map.reaction.type.KnownTransitionOmittedReaction; -import lcsb.mapviewer.model.map.reaction.type.NegativeInfluenceReaction; -import lcsb.mapviewer.model.map.reaction.type.ReactionRect; -import lcsb.mapviewer.model.map.reaction.type.ReducedTriggerReaction; -import lcsb.mapviewer.model.map.reaction.type.StateTransitionReaction; -import lcsb.mapviewer.model.map.reaction.type.TranscriptionReaction; -import lcsb.mapviewer.model.map.reaction.type.TranslationReaction; -import lcsb.mapviewer.model.map.reaction.type.TransportReaction; -import lcsb.mapviewer.model.map.reaction.type.TruncationReaction; -import lcsb.mapviewer.model.map.reaction.type.UnknownReducedPhysicalStimulationReaction; -import lcsb.mapviewer.model.map.species.Element; -import lcsb.mapviewer.model.map.species.GenericProtein; -import lcsb.mapviewer.model.map.species.Protein; -import lcsb.mapviewer.model.map.species.Species; +import lcsb.mapviewer.model.map.reaction.*; +import lcsb.mapviewer.model.map.reaction.type.*; +import lcsb.mapviewer.model.map.species.*; public class ReactionParserTests extends CellDesignerTestFunctions { - private Logger logger = LogManager.getLogger(ReactionParserTests.class.getName());; + private Logger logger = LogManager.getLogger(ReactionParserTests.class.getName()); ReactionXmlParser parser; CellDesignerElementCollection elements; @@ -78,53 +42,39 @@ public class ReactionParserTests extends CellDesignerTestFunctions { @Test public void testColorReaction() throws Exception { - Model model; - try { - model = getModelForFile("testFiles/colorfull_reaction.xml"); - Reaction reaction = model.getReactionByReactionId("re1"); - PolylineData line = reaction.getReactants().get(0).getLine(); - assertFalse( - "000".equals(line.getColor().getRed() + "" + line.getColor().getGreen() + "" + line.getColor().getBlue())); - line = reaction.getProducts().get(0).getLine(); - assertFalse( - "000".equals(line.getColor().getRed() + "" + line.getColor().getGreen() + "" + line.getColor().getBlue())); - line = reaction.getModifiers().get(0).getLine(); - assertFalse( - "000".equals(line.getColor().getRed() + "" + line.getColor().getGreen() + "" + line.getColor().getBlue())); - line = reaction.getOperators().get(0).getLine(); - assertFalse( - "000".equals(line.getColor().getRed() + "" + line.getColor().getGreen() + "" + line.getColor().getBlue())); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Model model = getModelForFile("testFiles/colorfull_reaction.xml"); + Reaction reaction = model.getReactionByReactionId("re1"); + PolylineData line = reaction.getReactants().get(0).getLine(); + assertFalse( + "000".equals(line.getColor().getRed() + "" + line.getColor().getGreen() + "" + line.getColor().getBlue())); + line = reaction.getProducts().get(0).getLine(); + assertFalse( + "000".equals(line.getColor().getRed() + "" + line.getColor().getGreen() + "" + line.getColor().getBlue())); + line = reaction.getModifiers().get(0).getLine(); + assertFalse( + "000".equals(line.getColor().getRed() + "" + line.getColor().getGreen() + "" + line.getColor().getBlue())); + line = reaction.getOperators().get(0).getLine(); + assertFalse( + "000".equals(line.getColor().getRed() + "" + line.getColor().getGreen() + "" + line.getColor().getBlue())); } @Test public void testColorReactionWithModifierOperator() throws Exception { - Model model; - try { - model = getModelForFile("testFiles/colorfull_reaction_2.xml"); - Reaction reaction = model.getReactionByReactionId("re1"); - Modifier m1 = reaction.getModifiers().get(0); - Modifier m2 = reaction.getModifiers().get(1); - NodeOperator o = reaction.getOperators().get(0); - - Set<Color> colors = new HashSet<>(); - colors.add(m1.getLine().getColor()); - colors.add(m2.getLine().getColor()); - colors.add(o.getLine().getColor()); - assertEquals("Each part has different color", 3, colors.size()); - - assertFalse("000".equals(getStringColor(m1.getLine()))); - assertFalse("000".equals(getStringColor(m2.getLine()))); - assertFalse("Operator line not parsed properly", "000".equals(getStringColor(o.getLine()))); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Model model = getModelForFile("testFiles/colorfull_reaction_2.xml"); + Reaction reaction = model.getReactionByReactionId("re1"); + Modifier m1 = reaction.getModifiers().get(0); + Modifier m2 = reaction.getModifiers().get(1); + NodeOperator o = reaction.getOperators().get(0); + + Set<Color> colors = new HashSet<>(); + colors.add(m1.getLine().getColor()); + colors.add(m2.getLine().getColor()); + colors.add(o.getLine().getColor()); + assertEquals("Each part has different color", 3, colors.size()); + + assertFalse("000".equals(getStringColor(m1.getLine()))); + assertFalse("000".equals(getStringColor(m2.getLine()))); + assertFalse("Operator line not parsed properly", "000".equals(getStringColor(o.getLine()))); } private String getStringColor(PolylineData line) { @@ -133,1469 +83,1106 @@ public class ReactionParserTests extends CellDesignerTestFunctions { @Test public void testMissingLines() throws Exception { - Model model; - try { - model = getModelForFile("testFiles/problematic/pd_map_with_problematic_reaction_line.xml"); - assertTrue(model.getElementByElementId("sa5003") instanceof GenericProtein); - Set<Reaction> list = model.getReactions(); - for (Reaction reaction : list) { - // reaction re1607 in this model was problematic, but in fact the - // problem - // can be in any reaction line - // if (reaction.getId().equals("re1607")) { - List<Line2D> lines = reaction.getLines(); - for (Line2D line2d : lines) { - assertFalse(Double.isNaN(line2d.getX1())); - assertFalse(Double.isNaN(line2d.getX2())); - assertFalse(Double.isNaN(line2d.getY1())); - assertFalse(Double.isNaN(line2d.getY2())); - } - // } + Model model = getModelForFile("testFiles/problematic/pd_map_with_problematic_reaction_line.xml"); + assertTrue(model.getElementByElementId("sa5003") instanceof GenericProtein); + Set<Reaction> list = model.getReactions(); + for (Reaction reaction : list) { + // reaction re1607 in this model was problematic, but in fact the + // problem + // can be in any reaction line + // if (reaction.getId().equals("re1607")) { + List<Line2D> lines = reaction.getLines(); + for (Line2D line2d : lines) { + assertFalse(Double.isNaN(line2d.getX1())); + assertFalse(Double.isNaN(line2d.getX2())); + assertFalse(Double.isNaN(line2d.getY1())); + assertFalse(Double.isNaN(line2d.getY2())); } - } catch (Exception e) { - e.printStackTrace(); - throw e; + // } } } @Test public void testTransitionReaction() throws Exception { - Model model; - try { - model = getModelForFile("testFiles/reactions/transition.xml"); - assertEquals(1, model.getReactions().size()); - Reaction reaction = model.getReactions().iterator().next(); - assertTrue(reaction instanceof StateTransitionReaction); - assertEquals(1, reaction.getReactants().size()); - Reactant reactant = reaction.getReactants().get(0); - - assertTrue(reaction.isReversible()); - assertEquals(ArrowType.FULL, reactant.getLine().getBeginAtd().getArrowType()); - assertEquals(ArrowType.NONE, reactant.getLine().getEndAtd().getArrowType()); - assertEquals(3, reactant.getLine().getLines().size()); - - Product product = reaction.getProducts().get(0); - assertEquals(ArrowType.NONE, product.getLine().getBeginAtd().getArrowType()); - assertEquals(ArrowType.FULL, product.getLine().getEndAtd().getArrowType()); - assertEquals(2, product.getLine().getLines().size()); + Model model = getModelForFile("testFiles/reactions/transition.xml"); + assertEquals(1, model.getReactions().size()); + Reaction reaction = model.getReactions().iterator().next(); + assertTrue(reaction instanceof StateTransitionReaction); + assertEquals(1, reaction.getReactants().size()); + Reactant reactant = reaction.getReactants().get(0); - assertTrue(reactant.getLine().getEndPoint().distance(product.getLine().getPoints().get(0)) < 20); - assertNotNull(reaction.getReactionRect()); + assertTrue(reaction.isReversible()); + assertEquals(ArrowType.FULL, reactant.getLine().getBeginAtd().getArrowType()); + assertEquals(ArrowType.NONE, reactant.getLine().getEndAtd().getArrowType()); + assertEquals(3, reactant.getLine().getLines().size()); - // NormalImageGenerator generator = new NormalImageGenerator(1, 0, 0, - // 1024, 1024, model, true, false, 0,false); - // generator.saveToPNG("tmp.png"); - // Desktop.getDesktop().open(new File("tmp.png")); + Product product = reaction.getProducts().get(0); + assertEquals(ArrowType.NONE, product.getLine().getBeginAtd().getArrowType()); + assertEquals(ArrowType.FULL, product.getLine().getEndAtd().getArrowType()); + assertEquals(2, product.getLine().getLines().size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertTrue(reactant.getLine().getEndPoint().distance(product.getLine().getPoints().get(0)) < 20); + assertNotNull(reaction.getReactionRect()); } @Test public void testTransition2() throws Exception { - Model model; - try { - model = getModelForFile("testFiles/reactions/transitionWithAdditionalNodes.xml"); - Reaction reaction = model.getReactions().iterator().next(); - assertEquals(2, reaction.getOperators().size()); - for (Reactant reactant : reaction.getReactants()) { - assertEquals(ArrowType.NONE, reactant.getLine().getBeginAtd().getArrowType()); - assertEquals(ArrowType.NONE, reactant.getLine().getEndAtd().getArrowType()); - - assertTrue( - reactant.getLine().getEndPoint().distance(reaction.getReactants().get(0).getLine().getEndPoint()) < 1e-6); - } + Model model = getModelForFile("testFiles/reactions/transitionWithAdditionalNodes.xml"); + Reaction reaction = model.getReactions().iterator().next(); + assertEquals(2, reaction.getOperators().size()); + for (Reactant reactant : reaction.getReactants()) { + assertEquals(ArrowType.NONE, reactant.getLine().getBeginAtd().getArrowType()); + assertEquals(ArrowType.NONE, reactant.getLine().getEndAtd().getArrowType()); - for (Product product : reaction.getProducts()) { - assertEquals(ArrowType.NONE, product.getLine().getBeginAtd().getArrowType()); - assertEquals(ArrowType.FULL, product.getLine().getEndAtd().getArrowType()); + assertTrue( + reactant.getLine().getEndPoint().distance(reaction.getReactants().get(0).getLine().getEndPoint()) < 1e-6); + } - assertTrue( - product.getLine().getBeginPoint().distance(reaction.getProducts().get(0).getLine().getBeginPoint()) < 1e-6); - } - assertNotNull(reaction.getReactionRect()); - - // NormalImageGenerator generator = new NormalImageGenerator(1, 0, 0, - // 1024, 1024, model, true, false, 0,false); - // generator.saveToPNG("tmp.png"); - // Desktop.getDesktop().open(new File("tmp.png")); - } catch (Exception e) { - e.printStackTrace(); - throw e; + for (Product product : reaction.getProducts()) { + assertEquals(ArrowType.NONE, product.getLine().getBeginAtd().getArrowType()); + assertEquals(ArrowType.FULL, product.getLine().getEndAtd().getArrowType()); + + assertTrue( + product.getLine().getBeginPoint().distance(reaction.getProducts().get(0).getLine().getBeginPoint()) < 1e-6); } + assertNotNull(reaction.getReactionRect()); } @Test public void testTransiotionOmitted() throws Exception { - Model model; - try { - model = getModelForFile("testFiles/reactions/transition_omitted.xml"); - Reaction reaction = model.getReactions().iterator().next(); - assertEquals(0, reaction.getOperators().size()); - assertEquals(KnownTransitionOmittedReaction.class, reaction.getClass()); - assertNotNull(reaction.getReactionRect()); - - // NormalImageGenerator generator = new NormalImageGenerator(1, 0, 0, - // 1024, 1024, model, true, false, 0,false); - // generator.saveToPNG("tmp.png"); - // Desktop.getDesktop().open(new File("tmp.png")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Model model = getModelForFile("testFiles/reactions/transition_omitted.xml"); + Reaction reaction = model.getReactions().iterator().next(); + assertEquals(0, reaction.getOperators().size()); + assertEquals(KnownTransitionOmittedReaction.class, reaction.getClass()); + assertNotNull(reaction.getReactionRect()); } @Test public void testUnknownTransition() throws Exception { - Model model; - try { - model = getModelForFile("testFiles/reactions/unknown_transition.xml"); - Reaction reaction = model.getReactions().iterator().next(); - assertNotNull(reaction.getReactionRect()); - - // NormalImageGenerator generator = new NormalImageGenerator(1, 0, 0, - // 1024, 1024, model, true, false, 0,false); - // generator.saveToPNG("tmp.png"); - // Desktop.getDesktop().open(new File("tmp.png")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Model model = getModelForFile("testFiles/reactions/unknown_transition.xml"); + Reaction reaction = model.getReactions().iterator().next(); + assertNotNull(reaction.getReactionRect()); + } @Test public void testTranscription() throws Exception { - Model model; - try { - model = getModelForFile("testFiles/reactions/transcription.xml"); - assertEquals(1, model.getReactions().size()); - Reaction reaction = model.getReactions().iterator().next(); - assertTrue(reaction instanceof TranscriptionReaction); - assertEquals(1, reaction.getReactants().size()); - Reactant reactant = reaction.getReactants().get(0); - assertEquals(ArrowType.NONE, reactant.getLine().getBeginAtd().getArrowType()); - assertEquals(ArrowType.NONE, reactant.getLine().getEndAtd().getArrowType()); - assertEquals(LineType.DASH_DOT_DOT, reactant.getLine().getType()); - assertEquals(1, reactant.getLine().getLines().size()); - - Product product = reaction.getProducts().get(0); - assertEquals(ArrowType.NONE, product.getLine().getBeginAtd().getArrowType()); - assertEquals(ArrowType.FULL, product.getLine().getEndAtd().getArrowType()); - assertEquals(1, product.getLine().getLines().size()); - - assertTrue(reactant.getLine().getEndPoint().distance(product.getLine().getPoints().get(0)) < 20); - assertNotNull(reaction.getReactionRect()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Model model = getModelForFile("testFiles/reactions/transcription.xml"); + assertEquals(1, model.getReactions().size()); + Reaction reaction = model.getReactions().iterator().next(); + assertTrue(reaction instanceof TranscriptionReaction); + assertEquals(1, reaction.getReactants().size()); + Reactant reactant = reaction.getReactants().get(0); + assertEquals(ArrowType.NONE, reactant.getLine().getBeginAtd().getArrowType()); + assertEquals(ArrowType.NONE, reactant.getLine().getEndAtd().getArrowType()); + assertEquals(LineType.DASH_DOT_DOT, reactant.getLine().getType()); + assertEquals(1, reactant.getLine().getLines().size()); + + Product product = reaction.getProducts().get(0); + assertEquals(ArrowType.NONE, product.getLine().getBeginAtd().getArrowType()); + assertEquals(ArrowType.FULL, product.getLine().getEndAtd().getArrowType()); + assertEquals(1, product.getLine().getLines().size()); + + assertTrue(reactant.getLine().getEndPoint().distance(product.getLine().getPoints().get(0)) < 20); + assertNotNull(reaction.getReactionRect()); } @Test public void testTranscription2() throws Exception { - Model model; - try { - model = getModelForFile("testFiles/reactions/transcription_with_additions.xml"); - assertEquals(1, model.getReactions().size()); - Reaction reaction = model.getReactions().iterator().next(); - assertTrue(reaction instanceof TranscriptionReaction); - assertEquals(2, reaction.getReactants().size()); - Reactant reactant = reaction.getReactants().get(0); - assertEquals(ArrowType.NONE, reactant.getLine().getBeginAtd().getArrowType()); - assertEquals(ArrowType.NONE, reactant.getLine().getEndAtd().getArrowType()); - assertEquals(LineType.DASH_DOT_DOT, reactant.getLine().getType()); - assertEquals(1, reactant.getLine().getLines().size()); - NodeOperator operator = null; - for (NodeOperator operator2 : reaction.getOperators()) { - if (operator2 instanceof SplitOperator) - operator = operator2; - } - assertEquals(LineType.DASH_DOT_DOT, operator.getLine().getType()); - - Product product = reaction.getProducts().get(0); - assertEquals(ArrowType.NONE, product.getLine().getBeginAtd().getArrowType()); - assertEquals(ArrowType.FULL, product.getLine().getEndAtd().getArrowType()); - assertEquals(1, product.getLine().getLines().size()); - - assertNotNull(reaction.getReactionRect()); - - super.testXmlSerialization(model); - // NormalImageGenerator generator = new NormalImageGenerator(1, 0, 0, - // 1024, 1024, model, true, false, 0,false); - // generator.saveToPNG("tmp.png"); - // Desktop.getDesktop().open(new File("tmp.png")); - } catch (Exception e) { - e.printStackTrace(); - throw e; + Model model = getModelForFile("testFiles/reactions/transcription_with_additions.xml"); + assertEquals(1, model.getReactions().size()); + Reaction reaction = model.getReactions().iterator().next(); + assertTrue(reaction instanceof TranscriptionReaction); + assertEquals(2, reaction.getReactants().size()); + Reactant reactant = reaction.getReactants().get(0); + assertEquals(ArrowType.NONE, reactant.getLine().getBeginAtd().getArrowType()); + assertEquals(ArrowType.NONE, reactant.getLine().getEndAtd().getArrowType()); + assertEquals(LineType.DASH_DOT_DOT, reactant.getLine().getType()); + assertEquals(1, reactant.getLine().getLines().size()); + NodeOperator operator = null; + for (NodeOperator operator2 : reaction.getOperators()) { + if (operator2 instanceof SplitOperator) + operator = operator2; } + assertEquals(LineType.DASH_DOT_DOT, operator.getLine().getType()); + + Product product = reaction.getProducts().get(0); + assertEquals(ArrowType.NONE, product.getLine().getBeginAtd().getArrowType()); + assertEquals(ArrowType.FULL, product.getLine().getEndAtd().getArrowType()); + assertEquals(1, product.getLine().getLines().size()); + + assertNotNull(reaction.getReactionRect()); + + super.testXmlSerialization(model); } @Test public void testTranslation() throws Exception { - Model model; - try { - model = getModelForFile("testFiles/reactions/translation.xml"); - assertEquals(1, model.getReactions().size()); - Reaction reaction = model.getReactions().iterator().next(); - assertTrue(reaction instanceof TranslationReaction); - assertEquals(2, reaction.getReactants().size()); - Reactant reactant = reaction.getReactants().get(0); - assertEquals(ArrowType.NONE, reactant.getLine().getBeginAtd().getArrowType()); - assertEquals(ArrowType.NONE, reactant.getLine().getEndAtd().getArrowType()); - assertEquals(LineType.DASH_DOT, reactant.getLine().getType()); - assertEquals(1, reactant.getLine().getLines().size()); - NodeOperator operator = reaction.getOperators().iterator().next(); - assertEquals(LineType.DASH_DOT, operator.getLine().getType()); - - Product product = reaction.getProducts().get(0); - assertEquals(ArrowType.NONE, product.getLine().getBeginAtd().getArrowType()); - assertEquals(ArrowType.FULL, product.getLine().getEndAtd().getArrowType()); - assertEquals(1, product.getLine().getLines().size()); - - assertNotNull(reaction.getReactionRect()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Model model = getModelForFile("testFiles/reactions/translation.xml"); + assertEquals(1, model.getReactions().size()); + Reaction reaction = model.getReactions().iterator().next(); + assertTrue(reaction instanceof TranslationReaction); + assertEquals(2, reaction.getReactants().size()); + Reactant reactant = reaction.getReactants().get(0); + assertEquals(ArrowType.NONE, reactant.getLine().getBeginAtd().getArrowType()); + assertEquals(ArrowType.NONE, reactant.getLine().getEndAtd().getArrowType()); + assertEquals(LineType.DASH_DOT, reactant.getLine().getType()); + assertEquals(1, reactant.getLine().getLines().size()); + NodeOperator operator = reaction.getOperators().iterator().next(); + assertEquals(LineType.DASH_DOT, operator.getLine().getType()); + + Product product = reaction.getProducts().get(0); + assertEquals(ArrowType.NONE, product.getLine().getBeginAtd().getArrowType()); + assertEquals(ArrowType.FULL, product.getLine().getEndAtd().getArrowType()); + assertEquals(1, product.getLine().getLines().size()); + + assertNotNull(reaction.getReactionRect()); } @Test public void testTransport() throws Exception { - Model model; - try { - model = getModelForFile("testFiles/reactions/transport.xml"); - assertEquals(1, model.getReactions().size()); - Reaction reaction = model.getReactions().iterator().next(); - assertTrue(reaction instanceof TransportReaction); - assertEquals(1, reaction.getReactants().size()); - Reactant reactant = reaction.getReactants().get(0); - assertEquals(ArrowType.NONE, reactant.getLine().getBeginAtd().getArrowType()); - assertEquals(ArrowType.NONE, reactant.getLine().getEndAtd().getArrowType()); - assertEquals(1, reactant.getLine().getLines().size()); - - Product product = reaction.getProducts().get(0); - assertEquals(ArrowType.NONE, product.getLine().getBeginAtd().getArrowType()); - assertEquals(ArrowType.FULL_CROSSBAR, product.getLine().getEndAtd().getArrowType()); - assertEquals(1, product.getLine().getLines().size()); + Model model = getModelForFile("testFiles/reactions/transport.xml"); + assertEquals(1, model.getReactions().size()); + Reaction reaction = model.getReactions().iterator().next(); + assertTrue(reaction instanceof TransportReaction); + assertEquals(1, reaction.getReactants().size()); + Reactant reactant = reaction.getReactants().get(0); + assertEquals(ArrowType.NONE, reactant.getLine().getBeginAtd().getArrowType()); + assertEquals(ArrowType.NONE, reactant.getLine().getEndAtd().getArrowType()); + assertEquals(1, reactant.getLine().getLines().size()); - assertNotNull(reaction.getReactionRect()); + Product product = reaction.getProducts().get(0); + assertEquals(ArrowType.NONE, product.getLine().getBeginAtd().getArrowType()); + assertEquals(ArrowType.FULL_CROSSBAR, product.getLine().getEndAtd().getArrowType()); + assertEquals(1, product.getLine().getLines().size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertNotNull(reaction.getReactionRect()); } @Test public void testHeterodimer() throws Exception { - Model model; - try { - model = getModelForFile("testFiles/reactions/heterodimer.xml"); - assertEquals(1, model.getReactions().size()); - Reaction reaction = model.getReactions().iterator().next(); - assertTrue(reaction instanceof HeterodimerAssociationReaction); - assertEquals(2, reaction.getReactants().size()); - Reactant reactant = reaction.getReactants().get(0); - assertEquals(ArrowType.NONE, reactant.getLine().getBeginAtd().getArrowType()); - assertEquals(ArrowType.NONE, reactant.getLine().getEndAtd().getArrowType()); - assertEquals(2, reactant.getLine().getLines().size()); - reactant = reaction.getReactants().get(1); - assertEquals(ArrowType.NONE, reactant.getLine().getBeginAtd().getArrowType()); - assertEquals(ArrowType.NONE, reactant.getLine().getEndAtd().getArrowType()); - assertEquals(3, reactant.getLine().getLines().size()); - - Product product = reaction.getProducts().get(0); - assertEquals(ArrowType.NONE, product.getLine().getBeginAtd().getArrowType()); - assertEquals(ArrowType.FULL, product.getLine().getEndAtd().getArrowType()); - assertEquals(3, product.getLine().getLines().size()); - - NodeOperator operator = reaction.getOperators().iterator().next(); - assertEquals(LineType.SOLID, operator.getLine().getType()); - assertEquals(7, operator.getLine().getLines().size()); - - assertNotNull(reaction.getReactionRect()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Model model = getModelForFile("testFiles/reactions/heterodimer.xml"); + assertEquals(1, model.getReactions().size()); + Reaction reaction = model.getReactions().iterator().next(); + assertTrue(reaction instanceof HeterodimerAssociationReaction); + assertEquals(2, reaction.getReactants().size()); + Reactant reactant = reaction.getReactants().get(0); + assertEquals(ArrowType.NONE, reactant.getLine().getBeginAtd().getArrowType()); + assertEquals(ArrowType.NONE, reactant.getLine().getEndAtd().getArrowType()); + assertEquals(2, reactant.getLine().getLines().size()); + reactant = reaction.getReactants().get(1); + assertEquals(ArrowType.NONE, reactant.getLine().getBeginAtd().getArrowType()); + assertEquals(ArrowType.NONE, reactant.getLine().getEndAtd().getArrowType()); + assertEquals(3, reactant.getLine().getLines().size()); + + Product product = reaction.getProducts().get(0); + assertEquals(ArrowType.NONE, product.getLine().getBeginAtd().getArrowType()); + assertEquals(ArrowType.FULL, product.getLine().getEndAtd().getArrowType()); + assertEquals(3, product.getLine().getLines().size()); + + NodeOperator operator = reaction.getOperators().iterator().next(); + assertEquals(LineType.SOLID, operator.getLine().getType()); + assertEquals(7, operator.getLine().getLines().size()); + + assertNotNull(reaction.getReactionRect()); } @Test public void testHeterodimerWithAdditions() throws Exception { - Model model; - try { - model = getModelForFile("testFiles/reactions/heterodimerWithAdditions.xml"); - - assertEquals(1, model.getReactions().size()); - Reaction reaction = model.getReactions().iterator().next(); - assertTrue(reaction instanceof HeterodimerAssociationReaction); - assertEquals(3, reaction.getReactants().size()); - Reactant reactant = reaction.getReactants().get(0); - assertEquals(ArrowType.NONE, reactant.getLine().getBeginAtd().getArrowType()); - assertEquals(ArrowType.NONE, reactant.getLine().getEndAtd().getArrowType()); - assertEquals(2, reactant.getLine().getLines().size()); - reactant = reaction.getReactants().get(1); - assertEquals(ArrowType.NONE, reactant.getLine().getBeginAtd().getArrowType()); - assertEquals(ArrowType.NONE, reactant.getLine().getEndAtd().getArrowType()); - assertEquals(3, reactant.getLine().getLines().size()); - - for (Product product : reaction.getProducts()) { - assertEquals(ArrowType.NONE, product.getLine().getBeginAtd().getArrowType()); - assertEquals(ArrowType.FULL, product.getLine().getEndAtd().getArrowType()); - } - - assertEquals(3, reaction.getOperators().size()); - NodeOperator operator = reaction.getOperators().iterator().next(); - assertEquals(LineType.SOLID, operator.getLine().getType()); - assertEquals(7, operator.getLine().getLines().size()); + Model model = getModelForFile("testFiles/reactions/heterodimerWithAdditions.xml"); + + assertEquals(1, model.getReactions().size()); + Reaction reaction = model.getReactions().iterator().next(); + assertTrue(reaction instanceof HeterodimerAssociationReaction); + assertEquals(3, reaction.getReactants().size()); + Reactant reactant = reaction.getReactants().get(0); + assertEquals(ArrowType.NONE, reactant.getLine().getBeginAtd().getArrowType()); + assertEquals(ArrowType.NONE, reactant.getLine().getEndAtd().getArrowType()); + assertEquals(2, reactant.getLine().getLines().size()); + reactant = reaction.getReactants().get(1); + assertEquals(ArrowType.NONE, reactant.getLine().getBeginAtd().getArrowType()); + assertEquals(ArrowType.NONE, reactant.getLine().getEndAtd().getArrowType()); + assertEquals(3, reactant.getLine().getLines().size()); + + for (Product product : reaction.getProducts()) { + assertEquals(ArrowType.NONE, product.getLine().getBeginAtd().getArrowType()); + assertEquals(ArrowType.FULL, product.getLine().getEndAtd().getArrowType()); + } - assertNotNull(reaction.getReactionRect()); + assertEquals(3, reaction.getOperators().size()); + NodeOperator operator = reaction.getOperators().iterator().next(); + assertEquals(LineType.SOLID, operator.getLine().getType()); + assertEquals(7, operator.getLine().getLines().size()); - // NormalImageGenerator generator = new NormalImageGenerator(1, 0, 0, - // 1024, 1024, model, true, false, 0,false); - // generator.saveToPNG("tmp.png"); - // Desktop.getDesktop().open(new File("tmp.png")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertNotNull(reaction.getReactionRect()); } @Test public void testDissociation() throws Exception { - Model model; - try { - model = getModelForFile("testFiles/reactions/dissociation.xml"); - assertEquals(2, model.getReactions().size()); - Reaction reaction = null; - for (Reaction reaction2 : model.getReactions()) { - if (reaction2.getIdReaction().equals("re1")) - reaction = reaction2; - } - assertTrue(reaction instanceof DissociationReaction); - assertEquals(1, reaction.getReactants().size()); - Reactant reactant = reaction.getReactants().get(0); - assertEquals(ArrowType.NONE, reactant.getLine().getBeginAtd().getArrowType()); - assertEquals(ArrowType.NONE, reactant.getLine().getEndAtd().getArrowType()); - assertEquals(2, reactant.getLine().getLines().size()); - - assertEquals(2, reaction.getProducts().size()); - Product product = reaction.getProducts().get(0); - assertEquals(ArrowType.NONE, product.getLine().getBeginAtd().getArrowType()); - assertEquals(ArrowType.FULL, product.getLine().getEndAtd().getArrowType()); - assertEquals(5, product.getLine().getLines().size()); - product = reaction.getProducts().get(1); - assertEquals(ArrowType.NONE, product.getLine().getBeginAtd().getArrowType()); - assertEquals(ArrowType.FULL, product.getLine().getEndAtd().getArrowType()); - assertEquals(4, product.getLine().getLines().size()); - - assertEquals(1, reaction.getOperators().size()); - NodeOperator operator = reaction.getOperators().iterator().next(); - assertEquals(LineType.SOLID, operator.getLine().getType()); - assertEquals(5, operator.getLine().getLines().size()); - - assertNotNull(reaction.getReactionRect()); - - // NormalImageGenerator generator = new NormalImageGenerator(1, 0, 0, - // 1024, 1024, model, true, false, 0,false); - // generator.saveToPNG("tmp.png"); - // Desktop.getDesktop().open(new File("tmp.png")); - } catch (Exception e) { - e.printStackTrace(); - throw e; + Model model = getModelForFile("testFiles/reactions/dissociation.xml"); + assertEquals(2, model.getReactions().size()); + Reaction reaction = null; + for (Reaction reaction2 : model.getReactions()) { + if (reaction2.getIdReaction().equals("re1")) + reaction = reaction2; } + assertTrue(reaction instanceof DissociationReaction); + assertEquals(1, reaction.getReactants().size()); + Reactant reactant = reaction.getReactants().get(0); + assertEquals(ArrowType.NONE, reactant.getLine().getBeginAtd().getArrowType()); + assertEquals(ArrowType.NONE, reactant.getLine().getEndAtd().getArrowType()); + assertEquals(2, reactant.getLine().getLines().size()); + + assertEquals(2, reaction.getProducts().size()); + Product product = reaction.getProducts().get(0); + assertEquals(ArrowType.NONE, product.getLine().getBeginAtd().getArrowType()); + assertEquals(ArrowType.FULL, product.getLine().getEndAtd().getArrowType()); + assertEquals(5, product.getLine().getLines().size()); + product = reaction.getProducts().get(1); + assertEquals(ArrowType.NONE, product.getLine().getBeginAtd().getArrowType()); + assertEquals(ArrowType.FULL, product.getLine().getEndAtd().getArrowType()); + assertEquals(4, product.getLine().getLines().size()); + + assertEquals(1, reaction.getOperators().size()); + NodeOperator operator = reaction.getOperators().iterator().next(); + assertEquals(LineType.SOLID, operator.getLine().getType()); + assertEquals(5, operator.getLine().getLines().size()); + + assertNotNull(reaction.getReactionRect()); } @Test public void testDissociationWithAddition() throws Exception { - Model model; - try { - model = getModelForFile("testFiles/reactions/dissociationWithAddition.xml"); - assertEquals(2, model.getReactions().size()); - Reaction reaction = null; - for (Reaction reaction2 : model.getReactions()) { - if (reaction2.getIdReaction().equals("re1")) - reaction = reaction2; - } - assertTrue(reaction instanceof DissociationReaction); - assertEquals(2, reaction.getReactants().size()); - Reactant reactant = reaction.getReactants().get(0); - assertEquals(ArrowType.NONE, reactant.getLine().getBeginAtd().getArrowType()); - assertEquals(ArrowType.NONE, reactant.getLine().getEndAtd().getArrowType()); - assertEquals(2, reactant.getLine().getLines().size()); - - assertEquals(3, reaction.getProducts().size()); - Product product = reaction.getProducts().get(0); - assertEquals(ArrowType.NONE, product.getLine().getBeginAtd().getArrowType()); - assertEquals(ArrowType.FULL, product.getLine().getEndAtd().getArrowType()); - assertEquals(5, product.getLine().getLines().size()); - product = reaction.getProducts().get(1); - assertEquals(ArrowType.NONE, product.getLine().getBeginAtd().getArrowType()); - assertEquals(ArrowType.FULL, product.getLine().getEndAtd().getArrowType()); - assertEquals(4, product.getLine().getLines().size()); - - assertEquals(3, reaction.getOperators().size()); - NodeOperator operator = reaction.getOperators().iterator().next(); - assertEquals(LineType.SOLID, operator.getLine().getType()); - assertEquals(5, operator.getLine().getLines().size()); - assertEquals(DissociationOperator.class, operator.getClass()); - - assertNotNull(reaction.getReactionRect()); - - // NormalImageGenerator generator = new NormalImageGenerator(1, 0, 0, - // 1024, 1024, model, true, false, 0,false); - // generator.saveToPNG("tmp.png"); - // Desktop.getDesktop().open(new File("tmp.png")); - } catch (Exception e) { - e.printStackTrace(); - throw e; + Model model = getModelForFile("testFiles/reactions/dissociationWithAddition.xml"); + assertEquals(2, model.getReactions().size()); + Reaction reaction = null; + for (Reaction reaction2 : model.getReactions()) { + if (reaction2.getIdReaction().equals("re1")) + reaction = reaction2; } + assertTrue(reaction instanceof DissociationReaction); + assertEquals(2, reaction.getReactants().size()); + Reactant reactant = reaction.getReactants().get(0); + assertEquals(ArrowType.NONE, reactant.getLine().getBeginAtd().getArrowType()); + assertEquals(ArrowType.NONE, reactant.getLine().getEndAtd().getArrowType()); + assertEquals(2, reactant.getLine().getLines().size()); + + assertEquals(3, reaction.getProducts().size()); + Product product = reaction.getProducts().get(0); + assertEquals(ArrowType.NONE, product.getLine().getBeginAtd().getArrowType()); + assertEquals(ArrowType.FULL, product.getLine().getEndAtd().getArrowType()); + assertEquals(5, product.getLine().getLines().size()); + product = reaction.getProducts().get(1); + assertEquals(ArrowType.NONE, product.getLine().getBeginAtd().getArrowType()); + assertEquals(ArrowType.FULL, product.getLine().getEndAtd().getArrowType()); + assertEquals(4, product.getLine().getLines().size()); + + assertEquals(3, reaction.getOperators().size()); + NodeOperator operator = reaction.getOperators().iterator().next(); + assertEquals(LineType.SOLID, operator.getLine().getType()); + assertEquals(5, operator.getLine().getLines().size()); + assertEquals(DissociationOperator.class, operator.getClass()); + + assertNotNull(reaction.getReactionRect()); } @Test public void testTruncation() throws Exception { - Model model; - try { - model = getModelForFile("testFiles/reactions/truncation.xml"); - assertEquals(1, model.getReactions().size()); - Reaction reaction = model.getReactions().iterator().next(); - assertTrue(reaction instanceof TruncationReaction); - assertEquals(1, reaction.getReactants().size()); - Reactant reactant = reaction.getReactants().get(0); - assertEquals(ArrowType.NONE, reactant.getLine().getBeginAtd().getArrowType()); - assertEquals(ArrowType.NONE, reactant.getLine().getEndAtd().getArrowType()); - assertEquals(2, reactant.getLine().getLines().size()); - - assertEquals(2, reaction.getProducts().size()); - Product product = reaction.getProducts().get(0); - assertEquals(ArrowType.NONE, product.getLine().getBeginAtd().getArrowType()); - assertEquals(ArrowType.FULL, product.getLine().getEndAtd().getArrowType()); - assertEquals(3, product.getLine().getLines().size()); - product = reaction.getProducts().get(1); - assertEquals(ArrowType.NONE, product.getLine().getBeginAtd().getArrowType()); - assertEquals(ArrowType.FULL, product.getLine().getEndAtd().getArrowType()); - assertEquals(4, product.getLine().getLines().size()); - - assertEquals(1, reaction.getOperators().size()); - NodeOperator operator = reaction.getOperators().iterator().next(); - assertEquals(LineType.SOLID, operator.getLine().getType()); - assertEquals(1, operator.getLine().getLines().size()); - assertEquals(TruncationOperator.class, operator.getClass()); - assertEquals(reaction.getReactionRect(), ReactionRect.RECT_BOLT); - - assertNotNull(reaction.getReactionRect()); - // NormalImageGenerator generator = new NormalImageGenerator(1, 0, 0, - // 1024, 1024, model, true, false, 0,false); - // generator.saveToPNG("tmp.png"); - // Desktop.getDesktop().open(new File("tmp.png")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Model model = getModelForFile("testFiles/reactions/truncation.xml"); + assertEquals(1, model.getReactions().size()); + Reaction reaction = model.getReactions().iterator().next(); + assertTrue(reaction instanceof TruncationReaction); + assertEquals(1, reaction.getReactants().size()); + Reactant reactant = reaction.getReactants().get(0); + assertEquals(ArrowType.NONE, reactant.getLine().getBeginAtd().getArrowType()); + assertEquals(ArrowType.NONE, reactant.getLine().getEndAtd().getArrowType()); + assertEquals(2, reactant.getLine().getLines().size()); + + assertEquals(2, reaction.getProducts().size()); + Product product = reaction.getProducts().get(0); + assertEquals(ArrowType.NONE, product.getLine().getBeginAtd().getArrowType()); + assertEquals(ArrowType.FULL, product.getLine().getEndAtd().getArrowType()); + assertEquals(3, product.getLine().getLines().size()); + product = reaction.getProducts().get(1); + assertEquals(ArrowType.NONE, product.getLine().getBeginAtd().getArrowType()); + assertEquals(ArrowType.FULL, product.getLine().getEndAtd().getArrowType()); + assertEquals(4, product.getLine().getLines().size()); + + assertEquals(1, reaction.getOperators().size()); + NodeOperator operator = reaction.getOperators().iterator().next(); + assertEquals(LineType.SOLID, operator.getLine().getType()); + assertEquals(1, operator.getLine().getLines().size()); + assertEquals(TruncationOperator.class, operator.getClass()); + assertEquals(reaction.getReactionRect(), ReactionRect.RECT_BOLT); + + assertNotNull(reaction.getReactionRect()); } @Test public void testTruncationWithModifier() throws Exception { - Model model; - try { - model = getModelForFile("testFiles/reactions/truncationWithModifier.xml"); - Reaction reaction = model.getReactions().iterator().next(); - Modifier m = reaction.getModifiers().get(0); - assertEquals(ArrowType.CIRCLE, m.getLine().getEndAtd().getArrowType()); - - m = reaction.getModifiers().get(1); - assertEquals(ArrowType.CROSSBAR, m.getLine().getEndAtd().getArrowType()); - // NormalImageGenerator generator = new NormalImageGenerator(1, 0, 0, - // 1024, 1024, model, true, false, 0,false); - // generator.saveToPNG("tmp.png"); - // Desktop.getDesktop().open(new File("tmp.png")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Model model = getModelForFile("testFiles/reactions/truncationWithModifier.xml"); + Reaction reaction = model.getReactions().iterator().next(); + Modifier m = reaction.getModifiers().get(0); + assertEquals(ArrowType.CIRCLE, m.getLine().getEndAtd().getArrowType()); + + m = reaction.getModifiers().get(1); + assertEquals(ArrowType.CROSSBAR, m.getLine().getEndAtd().getArrowType()); } @Test public void testComplexModifier1() throws Exception { - Model model; - try { - model = getModelForFile("testFiles/reactions/complexModifier1.xml"); - - Reaction reaction = model.getReactions().iterator().next(); - assertEquals(1, reaction.getOperators().size()); - assertEquals(2, reaction.getModifiers().size()); - - NodeOperator operator = reaction.getOperators().iterator().next(); - assertTrue(operator.isModifierOperator()); - assertEquals(AndOperator.class, operator.getClass()); - - // NormalImageGenerator generator = new NormalImageGenerator(1, 0, 0, - // 1024, 1024, model, true, false, 0,false); - // generator.saveToPNG("tmp.png"); - // Desktop.getDesktop().open(new File("tmp.png")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Model model = getModelForFile("testFiles/reactions/complexModifier1.xml"); + + Reaction reaction = model.getReactions().iterator().next(); + assertEquals(1, reaction.getOperators().size()); + assertEquals(2, reaction.getModifiers().size()); + + NodeOperator operator = reaction.getOperators().iterator().next(); + assertTrue(operator.isModifierOperator()); + assertEquals(AndOperator.class, operator.getClass()); + } @Test public void testComplexModifier2() throws Exception { - Model model; - try { - model = getModelForFile("testFiles/reactions/complexModifier2.xml"); - Reaction reaction = model.getReactions().iterator().next(); - assertEquals(1, reaction.getOperators().size()); - assertEquals(2, reaction.getModifiers().size()); - - NodeOperator operator = reaction.getOperators().iterator().next(); - assertTrue(operator.isModifierOperator()); - assertEquals(OrOperator.class, operator.getClass()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Model model = getModelForFile("testFiles/reactions/complexModifier2.xml"); + Reaction reaction = model.getReactions().iterator().next(); + assertEquals(1, reaction.getOperators().size()); + assertEquals(2, reaction.getModifiers().size()); + + NodeOperator operator = reaction.getOperators().iterator().next(); + assertTrue(operator.isModifierOperator()); + assertEquals(OrOperator.class, operator.getClass()); } @Test public void testComplexModifier3() throws Exception { - Model model; - try { - model = getModelForFile("testFiles/reactions/complexModifier3.xml"); - Reaction reaction = model.getReactions().iterator().next(); - assertEquals(1, reaction.getOperators().size()); - assertEquals(2, reaction.getModifiers().size()); - - NodeOperator operator = reaction.getOperators().iterator().next(); - assertTrue(operator.isModifierOperator()); - assertEquals(NandOperator.class, operator.getClass()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Model model = getModelForFile("testFiles/reactions/complexModifier3.xml"); + Reaction reaction = model.getReactions().iterator().next(); + assertEquals(1, reaction.getOperators().size()); + assertEquals(2, reaction.getModifiers().size()); + + NodeOperator operator = reaction.getOperators().iterator().next(); + assertTrue(operator.isModifierOperator()); + assertEquals(NandOperator.class, operator.getClass()); } @Test public void testComplexModifier4() throws Exception { - Model model; - try { - model = getModelForFile("testFiles/reactions/complexModifier4.xml"); - Reaction reaction = model.getReactions().iterator().next(); - assertEquals(1, reaction.getOperators().size()); - assertEquals(2, reaction.getModifiers().size()); - - NodeOperator operator = reaction.getOperators().iterator().next(); - assertTrue(operator.isModifierOperator()); - assertEquals(UnknownOperator.class, operator.getClass()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Model model = getModelForFile("testFiles/reactions/complexModifier4.xml"); + Reaction reaction = model.getReactions().iterator().next(); + assertEquals(1, reaction.getOperators().size()); + assertEquals(2, reaction.getModifiers().size()); + + NodeOperator operator = reaction.getOperators().iterator().next(); + assertTrue(operator.isModifierOperator()); + assertEquals(UnknownOperator.class, operator.getClass()); } @Test public void testComplexReaction() throws Exception { - Model model; - try { - model = getModelForFile("testFiles/reactions/complexReaction.xml"); - Reaction reaction = model.getReactions().iterator().next(); - assertEquals(0, reaction.getModifiers().size()); - assertEquals(2, reaction.getOperators().size()); - assertEquals(2, reaction.getProducts().size()); - assertEquals(2, reaction.getReactants().size()); - - NodeOperator operator = reaction.getOperators().iterator().next(); - assertEquals(AndOperator.class, operator.getClass()); - - // NormalImageGenerator generator = new NormalImageGenerator(1, 0, 0, - // 1024, 1024, model, true, false, 0,false); - // generator.saveToPNG("tmp.png"); - // Desktop.getDesktop().open(new File("tmp.png")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Model model = getModelForFile("testFiles/reactions/complexReaction.xml"); + Reaction reaction = model.getReactions().iterator().next(); + assertEquals(0, reaction.getModifiers().size()); + assertEquals(2, reaction.getOperators().size()); + assertEquals(2, reaction.getProducts().size()); + assertEquals(2, reaction.getReactants().size()); + + NodeOperator operator = reaction.getOperators().iterator().next(); + assertEquals(AndOperator.class, operator.getClass()); } @Test public void testComplexModifiers5() throws Exception { - Model model; - try { - model = getModelForFile("testFiles/reactions/complexModifier5.xml"); - - Reaction reaction = model.getReactions().iterator().next(); - assertEquals(4, reaction.getModifiers().size()); - assertEquals(1, reaction.getOperators().size()); - assertEquals(2, reaction.getOperators().iterator().next().getInputs().size()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Model model = getModelForFile("testFiles/reactions/complexModifier5.xml"); + + Reaction reaction = model.getReactions().iterator().next(); + assertEquals(4, reaction.getModifiers().size()); + assertEquals(1, reaction.getOperators().size()); + assertEquals(2, reaction.getOperators().iterator().next().getInputs().size()); } @Test public void testProblematicAnchors() throws Exception { - Model model; - try { - model = getModelForFile("testFiles/reactions/problemWithAnchors2.xml"); - - Reaction reaction1 = null; - Reaction reaction2 = null; - for (Reaction reaction : model.getReactions()) { - if (reaction.getIdReaction().equals("re2")) - reaction1 = reaction; - if (reaction.getIdReaction().equals("re3")) - reaction2 = reaction; - } - Reactant reactant = reaction1.getReactants().get(0); - Element alias1 = reaction1.getReactants().get(0).getElement(); - Element alias2 = reaction1.getProducts().get(0).getElement(); - Product product = reaction1.getProducts().get(0); - Point2D point = new Point2D.Double(alias1.getX() + alias1.getWidth() / 2, alias1.getY() + alias1.getHeight()); - Point2D point2 = new Point2D.Double(alias2.getX(), alias2.getY() + alias2.getHeight() / 2); - assertTrue(point.distance(reactant.getLine().getPoints().get(0)) < 1); - assertTrue(point2.distance(product.getLine().getEndPoint()) < 1); - - reactant = reaction2.getReactants().get(0); - alias1 = reaction2.getReactants().get(0).getElement(); - alias2 = reaction2.getProducts().get(0).getElement(); - product = reaction2.getProducts().get(0); - point = new Point2D.Double(alias1.getX() + alias1.getWidth(), alias1.getY() + alias1.getHeight() / 2); - point2 = new Point2D.Double(alias2.getX(), alias2.getY() + alias2.getHeight() / 2); - assertTrue(point.distance(reactant.getLine().getPoints().get(0)) < 1); - assertTrue(point2.distance(product.getLine().getEndPoint()) < 1); - - // NormalImageGenerator generator = new NormalImageGenerator(1, 0, 0, - // 1024, 1024, model, true, false, 0, false); - // generator.saveToPNG("tmp.png"); - // Desktop.getDesktop().open(new File("tmp.png")); - - } catch (Exception e) { - e.printStackTrace(); - throw e; + Model model = getModelForFile("testFiles/reactions/problemWithAnchors2.xml"); + + Reaction reaction1 = null; + Reaction reaction2 = null; + for (Reaction reaction : model.getReactions()) { + if (reaction.getIdReaction().equals("re2")) + reaction1 = reaction; + if (reaction.getIdReaction().equals("re3")) + reaction2 = reaction; } + Reactant reactant = reaction1.getReactants().get(0); + Element alias1 = reaction1.getReactants().get(0).getElement(); + Element alias2 = reaction1.getProducts().get(0).getElement(); + Product product = reaction1.getProducts().get(0); + Point2D point = new Point2D.Double(alias1.getX() + alias1.getWidth() / 2, alias1.getY() + alias1.getHeight()); + Point2D point2 = new Point2D.Double(alias2.getX(), alias2.getY() + alias2.getHeight() / 2); + assertTrue(point.distance(reactant.getLine().getPoints().get(0)) < 1); + assertTrue(point2.distance(product.getLine().getEndPoint()) < 1); + + reactant = reaction2.getReactants().get(0); + alias1 = reaction2.getReactants().get(0).getElement(); + alias2 = reaction2.getProducts().get(0).getElement(); + product = reaction2.getProducts().get(0); + point = new Point2D.Double(alias1.getX() + alias1.getWidth(), alias1.getY() + alias1.getHeight() / 2); + point2 = new Point2D.Double(alias2.getX(), alias2.getY() + alias2.getHeight() / 2); + assertTrue(point.distance(reactant.getLine().getPoints().get(0)) < 1); + assertTrue(point2.distance(product.getLine().getEndPoint()) < 1); } @Test public void testProblematicAnchors3() throws Exception { - Model model; - try { - model = getModelForFile("testFiles/reactions/problemWithAnchors3.xml"); - Reaction reaction = null; - for (Reaction reaction2 : model.getReactions()) { - if (reaction2.getIdReaction().equals("re3")) - reaction = reaction2; - } - Point2D point = new Point2D.Double(164.85583789974368, 86.060142902597); - Point2D point2 = new Point2D.Double(397.06477630152193, 284.99999999999994); - - assertTrue(point.distance(reaction.getModifiers().get(0).getLine().getPoints().get(0)) < 1); - assertTrue(point2.distance(reaction.getModifiers().get(1).getLine().getPoints().get(0)) < 1); - - // NormalImageGenerator generator = new NormalImageGenerator(1, 0, 0, - // 1024, 1024, model, true, false, 0, false); - // generator.saveToPNG("tmp.png"); - // Desktop.getDesktop().open(new File("tmp.png")); - - } catch (Exception e) { - e.printStackTrace(); - throw e; + Model model = getModelForFile("testFiles/reactions/problemWithAnchors3.xml"); + Reaction reaction = null; + for (Reaction reaction2 : model.getReactions()) { + if (reaction2.getIdReaction().equals("re3")) + reaction = reaction2; } + Point2D point = new Point2D.Double(164.85583789974368, 86.060142902597); + Point2D point2 = new Point2D.Double(397.06477630152193, 284.99999999999994); + + assertTrue(point.distance(reaction.getModifiers().get(0).getLine().getPoints().get(0)) < 1); + assertTrue(point2.distance(reaction.getModifiers().get(1).getLine().getPoints().get(0)) < 1); } @Test public void testPositiveInfluence() throws Exception { - Model model; - try { - model = getModelForFile("testFiles/reactions/positive_influence.xml"); - Reaction reaction = model.getReactions().iterator().next(); - assertNull(reaction.getReactionRect()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Model model = getModelForFile("testFiles/reactions/positive_influence.xml"); + Reaction reaction = model.getReactions().iterator().next(); + assertNull(reaction.getReactionRect()); } @Test public void testProblematicAnchors2() throws Exception { - Model model; - try { - model = getModelForFile("testFiles/reactions/complexReactionWithModifier.xml"); - Reaction reaction = model.getReactions().iterator().next(); - assertEquals(reaction.getProducts().get(0).getLine().length(), reaction.getReactants().get(0).getLine().length(), - 1e-6); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Model model = getModelForFile("testFiles/reactions/complexReactionWithModifier.xml"); + Reaction reaction = model.getReactions().iterator().next(); + assertEquals(reaction.getProducts().get(0).getLine().length(), reaction.getReactants().get(0).getLine().length(), + 1e-6); } @Test public void testProblematicAnchorsWithTwoReactantReaction() throws Exception { - Model model; - try { - model = getModelForFile("testFiles/reactions/centeredAnchorInModifier.xml"); - Reaction reaction = model.getReactions().iterator().next(); - Reactant r = null; - for (Reactant reactant : reaction.getReactants()) { - if (reactant.getElement().getName().equals("s3")) { - r = reactant; - } + Model model = getModelForFile("testFiles/reactions/centeredAnchorInModifier.xml"); + Reaction reaction = model.getReactions().iterator().next(); + Reactant r = null; + for (Reactant reactant : reaction.getReactants()) { + if (reactant.getElement().getName().equals("s3")) { + r = reactant; } - assertNotNull(r); - // I think there is still a bug because it should work with smaller delta - // :) - assertEquals(r.getLine().getPoints().get(1).getX(), r.getLine().getPoints().get(2).getX(), 1); - - } catch (Exception e) { - e.printStackTrace(); - throw e; } + assertNotNull(r); + // I think there is still a bug because it should work with smaller delta + // :) + assertEquals(r.getLine().getPoints().get(1).getX(), r.getLine().getPoints().get(2).getX(), 1); } @Test public void testReactionWithModifiers() throws Exception { - Model model; - try { - model = getModelForFile("testFiles/reactions/reactionWithModifiers.xml"); - Reaction reaction = model.getReactions().iterator().next(); - List<Modifier> modifiers = reaction.getModifiers(); - Modifier sa3 = null; - Modifier sa4 = null; - for (Modifier modifier : modifiers) { - if (modifier.getElement().getElementId().equals("sa3")) { - sa3 = modifier; - } - if (modifier.getElement().getElementId().equals("sa4")) { - sa4 = modifier; - } + Model model = getModelForFile("testFiles/reactions/reactionWithModifiers.xml"); + Reaction reaction = model.getReactions().iterator().next(); + List<Modifier> modifiers = reaction.getModifiers(); + Modifier sa3 = null; + Modifier sa4 = null; + for (Modifier modifier : modifiers) { + if (modifier.getElement().getElementId().equals("sa3")) { + sa3 = modifier; + } + if (modifier.getElement().getElementId().equals("sa4")) { + sa4 = modifier; } - assertEquals(sa3.getLine().getPoints().get(0).distance(new Point2D.Double(101.9591678008944, 68.0)), 0, EPSILON); - assertEquals( - sa3.getLine().getPoints().get(1).distance(new Point2D.Double(101.86750788643532, 112.89589905362774)), 0, - EPSILON); - assertEquals( - sa3.getLine().getPoints().get(2).distance(new Point2D.Double(190.66666666666666, 117.66666666666667)), 0, - EPSILON); - - assertEquals(sa4.getLine().getPoints().get(0).distance(new Point2D.Double(267.7075561388218, 54.00000000000001)), - 0, EPSILON); - assertEquals(sa4.getLine().getPoints().get(1).distance(new Point2D.Double(298.3735877669656, 71.67109819284718)), - 0, EPSILON); - assertEquals( - sa4.getLine().getPoints().get(2).distance(new Point2D.Double(190.66666666666666, 117.66666666666667)), 0, - EPSILON); - - // new NormalImageGenerator(1, 0, 0, 1024, 1024, model, true, false, 0, - // false).saveToPNG("tmp.png"); - // Desktop.getDesktop().open(new File("tmp.png")); - - } catch (Exception e) { - e.printStackTrace(); - throw e; } + assertEquals(sa3.getLine().getPoints().get(0).distance(new Point2D.Double(101.9591678008944, 68.0)), 0, EPSILON); + assertEquals(sa3.getLine().getPoints().get(1).distance(new Point2D.Double(101.86750788643532, 112.89589905362774)), + 0, EPSILON); + assertEquals(sa3.getLine().getPoints().get(2).distance(new Point2D.Double(190.66666666666666, 117.66666666666667)), + 0, EPSILON); + + assertEquals(sa4.getLine().getPoints().get(0).distance(new Point2D.Double(267.7075561388218, 54.00000000000001)), 0, + EPSILON); + assertEquals(sa4.getLine().getPoints().get(1).distance(new Point2D.Double(298.3735877669656, 71.67109819284718)), 0, + EPSILON); + assertEquals(sa4.getLine().getPoints().get(2).distance(new Point2D.Double(190.66666666666666, 117.66666666666667)), + 0, EPSILON); + } @Test public void testReactionOperatorsWithOperators() throws Exception { - Model model; - try { - model = getModelForFile("testFiles/reactions/reactionWithOperators.xml"); - Reaction reaction = model.getReactions().iterator().next(); - NodeOperator operator1 = reaction.getOperators().get(0); - NodeOperator operator2 = reaction.getOperators().get(1); - NodeOperator operator3 = reaction.getOperators().get(2); - - Product product1 = reaction.getProducts().get(0); - Product product2 = reaction.getProducts().get(1); - - assertEquals(0, operator1.getLine().getPoints().get(0).distance(new Point2D.Double(287.0, 242.00000000000009)), - EPSILON); - assertEquals(0, - operator1.getLine().getPoints().get(1).distance(new Point2D.Double(287.97349260719136, 204.40292958328325)), - EPSILON); - assertEquals(0, operator1.getLine().getEndPoint().distance(operator2.getLine().getBeginPoint()), EPSILON); - - assertEquals(0, - operator2.getLine().getPoints().get(0).distance(new Point2D.Double(359.1840955643148, 203.94471254019686)), - EPSILON); - assertEquals(0, - operator2.getLine().getPoints().get(1).distance(new Point2D.Double(372.9868291110932, 203.8558964441427)), - EPSILON); - - assertEquals(0, - operator3.getLine().getPoints().get(0).distance(new Point2D.Double(394.78939704287654, 203.71560401865366)), - EPSILON); - assertEquals(0, - operator3.getLine().getPoints().get(1).distance(new Point2D.Double(380.9866634960982, 203.80442011470782)), - EPSILON); - - assertEquals(0, - product1.getLine().getPoints().get(0).distance(new Point2D.Double(394.78939704287654, 203.71560401865366)), - EPSILON); - assertEquals(0, product1.getLine().getPoints().get(1).distance(new Point2D.Double(466.0, 203.25738697556727)), - EPSILON); - - assertEquals(0, - product2.getLine().getPoints().get(0).distance(new Point2D.Double(394.78939704287654, 203.71560401865366)), - EPSILON); - assertEquals(0, - product2.getLine().getPoints().get(1).distance(new Point2D.Double(452.96894321929705, 107.00000000000001)), - EPSILON); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Model model = getModelForFile("testFiles/reactions/reactionWithOperators.xml"); + Reaction reaction = model.getReactions().iterator().next(); + NodeOperator operator1 = reaction.getOperators().get(0); + NodeOperator operator2 = reaction.getOperators().get(1); + NodeOperator operator3 = reaction.getOperators().get(2); + + Product product1 = reaction.getProducts().get(0); + Product product2 = reaction.getProducts().get(1); + + assertEquals(0, operator1.getLine().getPoints().get(0).distance(new Point2D.Double(287.0, 242.00000000000009)), + EPSILON); + assertEquals(0, + operator1.getLine().getPoints().get(1).distance(new Point2D.Double(287.97349260719136, 204.40292958328325)), + EPSILON); + assertEquals(0, operator1.getLine().getEndPoint().distance(operator2.getLine().getBeginPoint()), EPSILON); + + assertEquals(0, + operator2.getLine().getPoints().get(0).distance(new Point2D.Double(359.1840955643148, 203.94471254019686)), + EPSILON); + assertEquals(0, + operator2.getLine().getPoints().get(1).distance(new Point2D.Double(372.9868291110932, 203.8558964441427)), + EPSILON); + + assertEquals(0, + operator3.getLine().getPoints().get(0).distance(new Point2D.Double(394.78939704287654, 203.71560401865366)), + EPSILON); + assertEquals(0, + operator3.getLine().getPoints().get(1).distance(new Point2D.Double(380.9866634960982, 203.80442011470782)), + EPSILON); + + assertEquals(0, + product1.getLine().getPoints().get(0).distance(new Point2D.Double(394.78939704287654, 203.71560401865366)), + EPSILON); + assertEquals(0, product1.getLine().getPoints().get(1).distance(new Point2D.Double(466.0, 203.25738697556727)), + EPSILON); + + assertEquals(0, + product2.getLine().getPoints().get(0).distance(new Point2D.Double(394.78939704287654, 203.71560401865366)), + EPSILON); + assertEquals(0, + product2.getLine().getPoints().get(1).distance(new Point2D.Double(452.96894321929705, 107.00000000000001)), + EPSILON); } @Test public void testReactionProductsWithOperators() throws Exception { - Model model; - try { - model = getModelForFile("testFiles/reactions/reactionWithOperators.xml"); - Reaction reaction = model.getReactions().iterator().next(); - - Product product1 = reaction.getProducts().get(0); - Product product2 = reaction.getProducts().get(1); - - assertEquals( - product1.getLine().getPoints().get(0).distance(new Point2D.Double(394.78939704287654, 203.71560401865366)), 0, - EPSILON); - assertEquals(product1.getLine().getPoints().get(1).distance(new Point2D.Double(466.0, 203.25738697556727)), 0, - EPSILON); - - assertEquals( - product2.getLine().getPoints().get(0).distance(new Point2D.Double(394.78939704287654, 203.71560401865366)), 0, - EPSILON); - assertEquals( - product2.getLine().getPoints().get(1).distance(new Point2D.Double(452.96894321929705, 107.00000000000001)), 0, - EPSILON); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Model model = getModelForFile("testFiles/reactions/reactionWithOperators.xml"); + Reaction reaction = model.getReactions().iterator().next(); + + Product product1 = reaction.getProducts().get(0); + Product product2 = reaction.getProducts().get(1); + + assertEquals( + product1.getLine().getPoints().get(0).distance(new Point2D.Double(394.78939704287654, 203.71560401865366)), 0, + EPSILON); + assertEquals(product1.getLine().getPoints().get(1).distance(new Point2D.Double(466.0, 203.25738697556727)), 0, + EPSILON); + + assertEquals( + product2.getLine().getPoints().get(0).distance(new Point2D.Double(394.78939704287654, 203.71560401865366)), 0, + EPSILON); + assertEquals( + product2.getLine().getPoints().get(1).distance(new Point2D.Double(452.96894321929705, 107.00000000000001)), 0, + EPSILON); } @Test public void testReactionReactantsWithOperators() throws Exception { - Model model; - try { - model = getModelForFile("testFiles/reactions/reactionWithOperators.xml"); - Reaction reaction = model.getReactions().iterator().next(); - - Reactant reactant1 = reaction.getReactants().get(0); - Reactant reactant2 = reaction.getReactants().get(1); - Reactant reactant3 = reaction.getReactants().get(2); - - assertEquals( - reactant1.getLine().getPoints().get(0).distance(new Point2D.Double(112.53618421052632, 167.46381578947367)), - 0, EPSILON); - assertEquals(reactant1.getLine().getPoints().get(1).distance(new Point2D.Double(287.0, 242.00000000000009)), 0, - EPSILON); - - assertEquals(reactant2.getLine().getPoints().get(0).distance(new Point2D.Double(121.0, 242.0)), 0, EPSILON); - assertEquals(reactant2.getLine().getPoints().get(1).distance(new Point2D.Double(287.0, 242.00000000000009)), 0, - EPSILON); - - assertEquals( - reactant3.getLine().getPoints().get(0).distance(new Point2D.Double(116.65392247520951, 72.34607752479052)), 0, - EPSILON); - assertEquals( - reactant3.getLine().getPoints().get(1).distance(new Point2D.Double(359.1840955643148, 203.94471254019686)), 0, - EPSILON); - - // NormalImageGenerator generator = new NormalImageGenerator(1, 0, 0, - // 1024, 1024, model, true, false, 0, false); - // generator.saveToPNG("tmp.png"); - // Desktop.getDesktop().open(new File("tmp.png")); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Model model = getModelForFile("testFiles/reactions/reactionWithOperators.xml"); + Reaction reaction = model.getReactions().iterator().next(); + + Reactant reactant1 = reaction.getReactants().get(0); + Reactant reactant2 = reaction.getReactants().get(1); + Reactant reactant3 = reaction.getReactants().get(2); + + assertEquals( + reactant1.getLine().getPoints().get(0).distance(new Point2D.Double(112.53618421052632, 167.46381578947367)), + 0, EPSILON); + assertEquals(reactant1.getLine().getPoints().get(1).distance(new Point2D.Double(287.0, 242.00000000000009)), 0, + EPSILON); + + assertEquals(reactant2.getLine().getPoints().get(0).distance(new Point2D.Double(121.0, 242.0)), 0, EPSILON); + assertEquals(reactant2.getLine().getPoints().get(1).distance(new Point2D.Double(287.0, 242.00000000000009)), 0, + EPSILON); + + assertEquals( + reactant3.getLine().getPoints().get(0).distance(new Point2D.Double(116.65392247520951, 72.34607752479052)), 0, + EPSILON); + assertEquals( + reactant3.getLine().getPoints().get(1).distance(new Point2D.Double(359.1840955643148, 203.94471254019686)), 0, + EPSILON); } @Test public void testTransitionReactionToXml() throws Exception { - try { - Model model = getModelFilledWithSpecies(); - String xmlString = readFile("testFiles/xmlNodeTestExamples/reaction_transition.xml"); - - Node node = getNodeFromXmlString(xmlString); - Reaction reaction1 = parser.getReaction(node, model); - - String xmlString2 = parser.toXml(reaction1); - assertNotNull(xmlString2); - // logger.debug(xmlString2); - Node node2 = getNodeFromXmlString(xmlString2); - Reaction reaction2 = parser.getReaction(node2, model); - - assertEquals(reaction1.getClass(), reaction2.getClass()); - assertEquals(reaction1.getReactants().size(), reaction2.getReactants().size()); - Reactant reactant1 = reaction1.getReactants().get(0); - Reactant reactant2 = reaction2.getReactants().get(0); - assertEquals(reactant1.getLine().getBeginAtd().getArrowType(), reactant2.getLine().getBeginAtd().getArrowType()); - assertEquals(reactant1.getLine().getEndAtd().getArrowType(), reactant2.getLine().getEndAtd().getArrowType()); - assertEquals(reactant1.getLine().getLines().size(), reactant2.getLine().getLines().size()); - - Product product1 = reaction1.getProducts().get(0); - Product product2 = reaction2.getProducts().get(0); - assertEquals(product1.getLine().getBeginAtd().getArrowType(), product2.getLine().getBeginAtd().getArrowType()); - assertEquals(product1.getLine().getEndAtd().getArrowType(), product2.getLine().getEndAtd().getArrowType()); - assertEquals(product1.getLine().getLines().size(), product2.getLine().getLines().size()); - - assertEquals(reactant1.getLine().getEndPoint().getX(), reactant2.getLine().getEndPoint().getX(), EPSILON); - assertEquals(reactant1.getLine().getEndPoint().getY(), reactant2.getLine().getEndPoint().getY(), EPSILON); - - assertEquals(reaction1.getReactionRect(), reaction2.getReactionRect()); - - List<Line2D> lines1 = reaction1.getLines(); - List<Line2D> lines2 = reaction2.getLines(); - - for (int i = 0; i < lines1.size(); i++) { - assertEquals(lines1.get(i).getX1(), lines2.get(i).getX1(), 1e-6); - assertEquals(lines1.get(i).getX2(), lines2.get(i).getX2(), 1e-6); - assertEquals(lines1.get(i).getY1(), lines2.get(i).getY1(), 1e-6); - assertEquals(lines1.get(i).getY2(), lines2.get(i).getY2(), 1e-6); - } - - assertEquals(product1.getLine().getColor(), product2.getLine().getColor()); - assertEquals(product1.getLine().getWidth(), product2.getLine().getWidth(), 1e-6); - assertEquals(reaction1.getLine().getColor(), product2.getLine().getColor()); - - } catch (Exception e) { - logger.error(e.getMessage(), e); - throw e; + Model model = getModelFilledWithSpecies(); + String xmlString = readFile("testFiles/xmlNodeTestExamples/reaction_transition.xml"); + + Node node = getNodeFromXmlString(xmlString); + Reaction reaction1 = parser.getReaction(node, model); + + String xmlString2 = parser.toXml(reaction1); + assertNotNull(xmlString2); + // logger.debug(xmlString2); + Node node2 = getNodeFromXmlString(xmlString2); + Reaction reaction2 = parser.getReaction(node2, model); + + assertEquals(reaction1.getClass(), reaction2.getClass()); + assertEquals(reaction1.getReactants().size(), reaction2.getReactants().size()); + Reactant reactant1 = reaction1.getReactants().get(0); + Reactant reactant2 = reaction2.getReactants().get(0); + assertEquals(reactant1.getLine().getBeginAtd().getArrowType(), reactant2.getLine().getBeginAtd().getArrowType()); + assertEquals(reactant1.getLine().getEndAtd().getArrowType(), reactant2.getLine().getEndAtd().getArrowType()); + assertEquals(reactant1.getLine().getLines().size(), reactant2.getLine().getLines().size()); + + Product product1 = reaction1.getProducts().get(0); + Product product2 = reaction2.getProducts().get(0); + assertEquals(product1.getLine().getBeginAtd().getArrowType(), product2.getLine().getBeginAtd().getArrowType()); + assertEquals(product1.getLine().getEndAtd().getArrowType(), product2.getLine().getEndAtd().getArrowType()); + assertEquals(product1.getLine().getLines().size(), product2.getLine().getLines().size()); + + assertEquals(reactant1.getLine().getEndPoint().getX(), reactant2.getLine().getEndPoint().getX(), EPSILON); + assertEquals(reactant1.getLine().getEndPoint().getY(), reactant2.getLine().getEndPoint().getY(), EPSILON); + + assertEquals(reaction1.getReactionRect(), reaction2.getReactionRect()); + + List<Line2D> lines1 = reaction1.getLines(); + List<Line2D> lines2 = reaction2.getLines(); + + for (int i = 0; i < lines1.size(); i++) { + assertEquals(lines1.get(i).getX1(), lines2.get(i).getX1(), 1e-6); + assertEquals(lines1.get(i).getX2(), lines2.get(i).getX2(), 1e-6); + assertEquals(lines1.get(i).getY1(), lines2.get(i).getY1(), 1e-6); + assertEquals(lines1.get(i).getY2(), lines2.get(i).getY2(), 1e-6); } + + assertEquals(product1.getLine().getColor(), product2.getLine().getColor()); + assertEquals(product1.getLine().getWidth(), product2.getLine().getWidth(), 1e-6); + assertEquals(reaction1.getLine().getColor(), product2.getLine().getColor()); } @Test public void testTransitionWidthAdditionalNodelReactionToXml() throws Exception { - try { - Model model = getModelFilledWithSpecies(); - String xmlString = readFile("testFiles/xmlNodeTestExamples/reaction_transitionWithAdditionalNodes.xml"); - Node node = getNodeFromXmlString(xmlString); - Reaction reaction1 = parser.getReaction(node, model); - - String xmlString2 = parser.toXml(reaction1); - assertNotNull(xmlString2); - // logger.debug(xmlString2); - Node node2 = getNodeFromXmlString(xmlString2); - Reaction reaction2 = parser.getReaction(node2, model); - - assertEquals(reaction1.getClass(), reaction2.getClass()); - assertEquals(reaction1.getReactants().size(), reaction2.getReactants().size()); - Reactant reactant1 = reaction1.getReactants().get(1); - Reactant reactant2 = reaction2.getReactants().get(1); - assertEquals(reactant1.getLine().getBeginAtd().getArrowType(), reactant2.getLine().getBeginAtd().getArrowType()); - assertEquals(reactant1.getLine().getEndAtd().getArrowType(), reactant2.getLine().getEndAtd().getArrowType()); - assertEquals(reactant1.getLine().getLines().size(), reactant2.getLine().getLines().size()); - - Product product1 = reaction1.getProducts().get(1); - Product product2 = reaction2.getProducts().get(1); - assertEquals(product1.getLine().getBeginAtd().getArrowType(), product2.getLine().getBeginAtd().getArrowType()); - assertEquals(product1.getLine().getEndAtd().getArrowType(), product2.getLine().getEndAtd().getArrowType()); - assertEquals(product1.getLine().getLines().size(), product2.getLine().getLines().size()); - - assertTrue(reactant1.getLine().getEndPoint().distance(reactant2.getLine().getEndPoint()) < 1e-6); - assertEquals(reaction1.getReactionRect(), reaction2.getReactionRect()); - - List<Line2D> lines1 = reaction1.getLines(); - List<Line2D> lines2 = reaction2.getLines(); - - for (int i = 0; i < lines1.size(); i++) { - assertEquals(lines1.get(i).getX1(), lines2.get(i).getX1(), 1e-6); - assertEquals(lines1.get(i).getX2(), lines2.get(i).getX2(), 1e-6); - assertEquals(lines1.get(i).getY1(), lines2.get(i).getY1(), 1e-6); - assertEquals(lines1.get(i).getY2(), lines2.get(i).getY2(), 1e-6); - } - - assertEquals(product1.getLine().getColor(), product2.getLine().getColor()); - assertEquals(product1.getLine().getWidth(), product2.getLine().getWidth(), 1e-6); - - } catch (Exception e) { - logger.error(e.getMessage(), e); - throw e; + Model model = getModelFilledWithSpecies(); + String xmlString = readFile("testFiles/xmlNodeTestExamples/reaction_transitionWithAdditionalNodes.xml"); + Node node = getNodeFromXmlString(xmlString); + Reaction reaction1 = parser.getReaction(node, model); + + String xmlString2 = parser.toXml(reaction1); + assertNotNull(xmlString2); + // logger.debug(xmlString2); + Node node2 = getNodeFromXmlString(xmlString2); + Reaction reaction2 = parser.getReaction(node2, model); + + assertEquals(reaction1.getClass(), reaction2.getClass()); + assertEquals(reaction1.getReactants().size(), reaction2.getReactants().size()); + Reactant reactant1 = reaction1.getReactants().get(1); + Reactant reactant2 = reaction2.getReactants().get(1); + assertEquals(reactant1.getLine().getBeginAtd().getArrowType(), reactant2.getLine().getBeginAtd().getArrowType()); + assertEquals(reactant1.getLine().getEndAtd().getArrowType(), reactant2.getLine().getEndAtd().getArrowType()); + assertEquals(reactant1.getLine().getLines().size(), reactant2.getLine().getLines().size()); + + Product product1 = reaction1.getProducts().get(1); + Product product2 = reaction2.getProducts().get(1); + assertEquals(product1.getLine().getBeginAtd().getArrowType(), product2.getLine().getBeginAtd().getArrowType()); + assertEquals(product1.getLine().getEndAtd().getArrowType(), product2.getLine().getEndAtd().getArrowType()); + assertEquals(product1.getLine().getLines().size(), product2.getLine().getLines().size()); + + assertTrue(reactant1.getLine().getEndPoint().distance(reactant2.getLine().getEndPoint()) < 1e-6); + assertEquals(reaction1.getReactionRect(), reaction2.getReactionRect()); + + List<Line2D> lines1 = reaction1.getLines(); + List<Line2D> lines2 = reaction2.getLines(); + + for (int i = 0; i < lines1.size(); i++) { + assertEquals(lines1.get(i).getX1(), lines2.get(i).getX1(), 1e-6); + assertEquals(lines1.get(i).getX2(), lines2.get(i).getX2(), 1e-6); + assertEquals(lines1.get(i).getY1(), lines2.get(i).getY1(), 1e-6); + assertEquals(lines1.get(i).getY2(), lines2.get(i).getY2(), 1e-6); } + + assertEquals(product1.getLine().getColor(), product2.getLine().getColor()); + assertEquals(product1.getLine().getWidth(), product2.getLine().getWidth(), 1e-6); } @Test public void testTranslationToXml() throws Exception { - try { - Model model = getModelFilledWithSpecies(); - String xmlString = readFile("testFiles/xmlNodeTestExamples/reaction_translation.xml"); - Node node = getNodeFromXmlString(xmlString); - Reaction reaction1 = parser.getReaction(node, model); - - String xmlString2 = parser.toXml(reaction1); - assertNotNull(xmlString2); - // logger.debug(xmlString2); - Node node2 = getNodeFromXmlString(xmlString2); - Reaction reaction2 = parser.getReaction(node2, model); - - assertEquals(reaction1.getClass(), reaction2.getClass()); - assertEquals(reaction1.getReactants().size(), reaction2.getReactants().size()); - Reactant reactant1 = reaction1.getReactants().get(1); - Reactant reactant2 = reaction2.getReactants().get(1); - assertEquals(reactant1.getLine().getBeginAtd().getArrowType(), reactant2.getLine().getBeginAtd().getArrowType()); - assertEquals(reactant1.getLine().getEndAtd().getArrowType(), reactant2.getLine().getEndAtd().getArrowType()); - assertEquals(reactant1.getLine().getLines().size(), reactant2.getLine().getLines().size()); - - Product product1 = reaction1.getProducts().get(1); - Product product2 = reaction2.getProducts().get(1); - assertEquals(product1.getLine().getBeginAtd().getArrowType(), product2.getLine().getBeginAtd().getArrowType()); - assertEquals(product1.getLine().getEndAtd().getArrowType(), product2.getLine().getEndAtd().getArrowType()); - assertEquals(product1.getLine().getLines().size(), product2.getLine().getLines().size()); - - assertTrue(reactant1.getLine().getEndPoint().distance(reactant2.getLine().getEndPoint()) < 1e-6); - assertEquals(reaction1.getReactionRect(), reaction2.getReactionRect()); - - List<Line2D> lines1 = reaction1.getLines(); - List<Line2D> lines2 = reaction2.getLines(); - - for (int i = 0; i < lines1.size(); i++) { - assertEquals(lines1.get(i).getX1(), lines2.get(i).getX1(), 1e-6); - assertEquals(lines1.get(i).getX2(), lines2.get(i).getX2(), 1e-6); - assertEquals(lines1.get(i).getY1(), lines2.get(i).getY1(), 1e-6); - assertEquals(lines1.get(i).getY2(), lines2.get(i).getY2(), 1e-6); - } - - assertEquals(product1.getLine().getColor(), product2.getLine().getColor()); - assertEquals(product1.getLine().getWidth(), product2.getLine().getWidth(), 1e-6); - - } catch (Exception e) { - logger.error(e.getMessage(), e); - throw e; + Model model = getModelFilledWithSpecies(); + String xmlString = readFile("testFiles/xmlNodeTestExamples/reaction_translation.xml"); + Node node = getNodeFromXmlString(xmlString); + Reaction reaction1 = parser.getReaction(node, model); + + String xmlString2 = parser.toXml(reaction1); + assertNotNull(xmlString2); + Node node2 = getNodeFromXmlString(xmlString2); + Reaction reaction2 = parser.getReaction(node2, model); + + assertEquals(reaction1.getClass(), reaction2.getClass()); + assertEquals(reaction1.getReactants().size(), reaction2.getReactants().size()); + Reactant reactant1 = reaction1.getReactants().get(1); + Reactant reactant2 = reaction2.getReactants().get(1); + assertEquals(reactant1.getLine().getBeginAtd().getArrowType(), reactant2.getLine().getBeginAtd().getArrowType()); + assertEquals(reactant1.getLine().getEndAtd().getArrowType(), reactant2.getLine().getEndAtd().getArrowType()); + assertEquals(reactant1.getLine().getLines().size(), reactant2.getLine().getLines().size()); + + Product product1 = reaction1.getProducts().get(1); + Product product2 = reaction2.getProducts().get(1); + assertEquals(product1.getLine().getBeginAtd().getArrowType(), product2.getLine().getBeginAtd().getArrowType()); + assertEquals(product1.getLine().getEndAtd().getArrowType(), product2.getLine().getEndAtd().getArrowType()); + assertEquals(product1.getLine().getLines().size(), product2.getLine().getLines().size()); + + assertTrue(reactant1.getLine().getEndPoint().distance(reactant2.getLine().getEndPoint()) < 1e-6); + assertEquals(reaction1.getReactionRect(), reaction2.getReactionRect()); + + List<Line2D> lines1 = reaction1.getLines(); + List<Line2D> lines2 = reaction2.getLines(); + + for (int i = 0; i < lines1.size(); i++) { + assertEquals(lines1.get(i).getX1(), lines2.get(i).getX1(), 1e-6); + assertEquals(lines1.get(i).getX2(), lines2.get(i).getX2(), 1e-6); + assertEquals(lines1.get(i).getY1(), lines2.get(i).getY1(), 1e-6); + assertEquals(lines1.get(i).getY2(), lines2.get(i).getY2(), 1e-6); } + + assertEquals(product1.getLine().getColor(), product2.getLine().getColor()); + assertEquals(product1.getLine().getWidth(), product2.getLine().getWidth(), 1e-6); } @Test public void testTransportToXml() throws Exception { - try { - Model model = getModelFilledWithSpecies(); - String xmlString = readFile("testFiles/xmlNodeTestExamples/reaction_transport.xml"); - Node node = getNodeFromXmlString(xmlString); - Reaction reaction1 = parser.getReaction(node, model); - - String xmlString2 = parser.toXml(reaction1); - assertNotNull(xmlString2); - // logger.debug(xmlString2); - Node node2 = getNodeFromXmlString(xmlString2); - Reaction reaction2 = parser.getReaction(node2, model); - - List<Line2D> lines1 = reaction1.getLines(); - List<Line2D> lines2 = reaction2.getLines(); - - for (int i = 0; i < lines1.size(); i++) { - assertEquals(lines1.get(i).getX1(), lines2.get(i).getX1(), 1e-6); - assertEquals(lines1.get(i).getX2(), lines2.get(i).getX2(), 1e-6); - assertEquals(lines1.get(i).getY1(), lines2.get(i).getY1(), 1e-6); - assertEquals(lines1.get(i).getY2(), lines2.get(i).getY2(), 1e-6); - } - assertEquals(reaction1.getClass(), reaction2.getClass()); - assertEquals(reaction1.getMiriamData().size(), reaction2.getMiriamData().size()); - assertEquals(reaction1.getNotes().trim(), reaction2.getNotes().trim()); - } catch (Exception e) { - logger.error(e.getMessage(), e); - throw e; + Model model = getModelFilledWithSpecies(); + String xmlString = readFile("testFiles/xmlNodeTestExamples/reaction_transport.xml"); + Node node = getNodeFromXmlString(xmlString); + Reaction reaction1 = parser.getReaction(node, model); + + String xmlString2 = parser.toXml(reaction1); + assertNotNull(xmlString2); + Node node2 = getNodeFromXmlString(xmlString2); + Reaction reaction2 = parser.getReaction(node2, model); + + List<Line2D> lines1 = reaction1.getLines(); + List<Line2D> lines2 = reaction2.getLines(); + + for (int i = 0; i < lines1.size(); i++) { + assertEquals(lines1.get(i).getX1(), lines2.get(i).getX1(), 1e-6); + assertEquals(lines1.get(i).getX2(), lines2.get(i).getX2(), 1e-6); + assertEquals(lines1.get(i).getY1(), lines2.get(i).getY1(), 1e-6); + assertEquals(lines1.get(i).getY2(), lines2.get(i).getY2(), 1e-6); } + assertEquals(reaction1.getClass(), reaction2.getClass()); + assertEquals(reaction1.getMiriamData().size(), reaction2.getMiriamData().size()); + assertEquals(reaction1.getNotes().trim(), reaction2.getNotes().trim()); } @Test public void testTruncationToXml() throws Exception { - try { - Model model = getModelFilledWithSpecies(); - String xmlString = readFile("testFiles/xmlNodeTestExamples/reaction_truncation.xml"); - Node node = getNodeFromXmlString(xmlString); - Reaction reaction1 = parser.getReaction(node, model); - - String xmlString2 = parser.toXml(reaction1); - assertNotNull(xmlString2); - // logger.debug(xmlString2); - Node node2 = getNodeFromXmlString(xmlString2); - Reaction reaction2 = parser.getReaction(node2, model); - - List<Line2D> lines1 = reaction1.getLines(); - List<Line2D> lines2 = reaction2.getLines(); - - for (int i = 0; i < lines1.size(); i++) { - assertEquals(lines1.get(i).getX1(), lines2.get(i).getX1(), 1e-6); - assertEquals(lines1.get(i).getX2(), lines2.get(i).getX2(), 1e-6); - assertEquals(lines1.get(i).getY1(), lines2.get(i).getY1(), 1e-6); - assertEquals(lines1.get(i).getY2(), lines2.get(i).getY2(), 1e-6); - } - assertEquals(reaction1.getClass(), reaction2.getClass()); - } catch (Exception e) { - logger.error(e.getMessage(), e); - throw e; + Model model = getModelFilledWithSpecies(); + String xmlString = readFile("testFiles/xmlNodeTestExamples/reaction_truncation.xml"); + Node node = getNodeFromXmlString(xmlString); + Reaction reaction1 = parser.getReaction(node, model); + + String xmlString2 = parser.toXml(reaction1); + assertNotNull(xmlString2); + // logger.debug(xmlString2); + Node node2 = getNodeFromXmlString(xmlString2); + Reaction reaction2 = parser.getReaction(node2, model); + + List<Line2D> lines1 = reaction1.getLines(); + List<Line2D> lines2 = reaction2.getLines(); + + for (int i = 0; i < lines1.size(); i++) { + assertEquals(lines1.get(i).getX1(), lines2.get(i).getX1(), 1e-6); + assertEquals(lines1.get(i).getX2(), lines2.get(i).getX2(), 1e-6); + assertEquals(lines1.get(i).getY1(), lines2.get(i).getY1(), 1e-6); + assertEquals(lines1.get(i).getY2(), lines2.get(i).getY2(), 1e-6); } + assertEquals(reaction1.getClass(), reaction2.getClass()); } @Test public void testTruncationWithModifierToXml() throws Exception { - try { - Model model = getModelFilledWithSpecies(); - String xmlString = readFile("testFiles/xmlNodeTestExamples/reaction_truncationWithModifier.xml"); - Node node = getNodeFromXmlString(xmlString); - Reaction reaction1 = parser.getReaction(node, model); - - String xmlString2 = parser.toXml(reaction1); - assertNotNull(xmlString2); - // logger.debug(xmlString2); - Node node2 = getNodeFromXmlString(xmlString2); - Reaction reaction2 = parser.getReaction(node2, model); - - List<Line2D> lines1 = reaction1.getLines(); - List<Line2D> lines2 = reaction2.getLines(); - - for (int i = 0; i < lines1.size(); i++) { - assertEquals(lines1.get(i).getX1(), lines2.get(i).getX1(), 1e-6); - assertEquals(lines1.get(i).getX2(), lines2.get(i).getX2(), 1e-6); - assertEquals(lines1.get(i).getY1(), lines2.get(i).getY1(), 1e-6); - assertEquals(lines1.get(i).getY2(), lines2.get(i).getY2(), 1e-6); - } - - assertEquals(reaction1.getClass(), reaction2.getClass()); - } catch (Exception e) { - e.printStackTrace(); - throw e; + Model model = getModelFilledWithSpecies(); + String xmlString = readFile("testFiles/xmlNodeTestExamples/reaction_truncationWithModifier.xml"); + Node node = getNodeFromXmlString(xmlString); + Reaction reaction1 = parser.getReaction(node, model); + + String xmlString2 = parser.toXml(reaction1); + assertNotNull(xmlString2); + // logger.debug(xmlString2); + Node node2 = getNodeFromXmlString(xmlString2); + Reaction reaction2 = parser.getReaction(node2, model); + + List<Line2D> lines1 = reaction1.getLines(); + List<Line2D> lines2 = reaction2.getLines(); + + for (int i = 0; i < lines1.size(); i++) { + assertEquals(lines1.get(i).getX1(), lines2.get(i).getX1(), 1e-6); + assertEquals(lines1.get(i).getX2(), lines2.get(i).getX2(), 1e-6); + assertEquals(lines1.get(i).getY1(), lines2.get(i).getY1(), 1e-6); + assertEquals(lines1.get(i).getY2(), lines2.get(i).getY2(), 1e-6); } + + assertEquals(reaction1.getClass(), reaction2.getClass()); } @Test public void testUnknownTransitionToXml() throws Exception { - try { - Model model = getModelFilledWithSpecies(); - String xmlString = readFile("testFiles/xmlNodeTestExamples/reaction_unknown_transition.xml"); - Node node = getNodeFromXmlString(xmlString); - Reaction reaction1 = parser.getReaction(node, model); - - String xmlString2 = parser.toXml(reaction1); - assertNotNull(xmlString2); - // logger.debug(xmlString2); - Node node2 = getNodeFromXmlString(xmlString2); - Reaction reaction2 = parser.getReaction(node2, model); - - List<Line2D> lines1 = reaction1.getLines(); - List<Line2D> lines2 = reaction2.getLines(); - - for (int i = 0; i < lines1.size(); i++) { - assertEquals(lines1.get(i).getX1(), lines2.get(i).getX1(), 1e-6); - assertEquals(lines1.get(i).getX2(), lines2.get(i).getX2(), 1e-6); - assertEquals(lines1.get(i).getY1(), lines2.get(i).getY1(), 1e-6); - assertEquals(lines1.get(i).getY2(), lines2.get(i).getY2(), 1e-6); - } - assertEquals(reaction1.getClass(), reaction2.getClass()); - } catch (Exception e) { - logger.error(e.getMessage(), e); - throw e; + Model model = getModelFilledWithSpecies(); + String xmlString = readFile("testFiles/xmlNodeTestExamples/reaction_unknown_transition.xml"); + Node node = getNodeFromXmlString(xmlString); + Reaction reaction1 = parser.getReaction(node, model); + + String xmlString2 = parser.toXml(reaction1); + assertNotNull(xmlString2); + // logger.debug(xmlString2); + Node node2 = getNodeFromXmlString(xmlString2); + Reaction reaction2 = parser.getReaction(node2, model); + + List<Line2D> lines1 = reaction1.getLines(); + List<Line2D> lines2 = reaction2.getLines(); + + for (int i = 0; i < lines1.size(); i++) { + assertEquals(lines1.get(i).getX1(), lines2.get(i).getX1(), 1e-6); + assertEquals(lines1.get(i).getX2(), lines2.get(i).getX2(), 1e-6); + assertEquals(lines1.get(i).getY1(), lines2.get(i).getY1(), 1e-6); + assertEquals(lines1.get(i).getY2(), lines2.get(i).getY2(), 1e-6); } + assertEquals(reaction1.getClass(), reaction2.getClass()); } @Test public void testTransitionOmittedToXml() throws Exception { - try { - Model model = getModelFilledWithSpecies(); - String xmlString = readFile("testFiles/xmlNodeTestExamples/reaction_transition_omitted.xml"); - Node node = getNodeFromXmlString(xmlString); - Reaction reaction1 = parser.getReaction(node, model); - - String xmlString2 = parser.toXml(reaction1); - assertNotNull(xmlString2); - // logger.debug(xmlString2); - Node node2 = getNodeFromXmlString(xmlString2); - Reaction reaction2 = parser.getReaction(node2, model); - - List<Line2D> lines1 = reaction1.getLines(); - List<Line2D> lines2 = reaction2.getLines(); - - for (int i = 0; i < lines1.size(); i++) { - assertEquals(lines1.get(i).getX1(), lines2.get(i).getX1(), 1e-6); - assertEquals(lines1.get(i).getX2(), lines2.get(i).getX2(), 1e-6); - assertEquals(lines1.get(i).getY1(), lines2.get(i).getY1(), 1e-6); - assertEquals(lines1.get(i).getY2(), lines2.get(i).getY2(), 1e-6); - } - assertEquals(reaction1.getClass(), reaction2.getClass()); - } catch (Exception e) { - logger.error(e.getMessage(), e); - throw e; + Model model = getModelFilledWithSpecies(); + String xmlString = readFile("testFiles/xmlNodeTestExamples/reaction_transition_omitted.xml"); + Node node = getNodeFromXmlString(xmlString); + Reaction reaction1 = parser.getReaction(node, model); + + String xmlString2 = parser.toXml(reaction1); + assertNotNull(xmlString2); + // logger.debug(xmlString2); + Node node2 = getNodeFromXmlString(xmlString2); + Reaction reaction2 = parser.getReaction(node2, model); + + List<Line2D> lines1 = reaction1.getLines(); + List<Line2D> lines2 = reaction2.getLines(); + + for (int i = 0; i < lines1.size(); i++) { + assertEquals(lines1.get(i).getX1(), lines2.get(i).getX1(), 1e-6); + assertEquals(lines1.get(i).getX2(), lines2.get(i).getX2(), 1e-6); + assertEquals(lines1.get(i).getY1(), lines2.get(i).getY1(), 1e-6); + assertEquals(lines1.get(i).getY2(), lines2.get(i).getY2(), 1e-6); } + assertEquals(reaction1.getClass(), reaction2.getClass()); } @Test public void testTranscriptionToXml() throws Exception { - try { - Model model = getModelFilledWithSpecies(); - String xmlString = readFile("testFiles/xmlNodeTestExamples/reaction_transcription.xml"); - Node node = getNodeFromXmlString(xmlString); - Reaction reaction1 = parser.getReaction(node, model); - - String xmlString2 = parser.toXml(reaction1); - assertNotNull(xmlString2); - // logger.debug(xmlString2); - Node node2 = getNodeFromXmlString(xmlString2); - Reaction reaction2 = parser.getReaction(node2, model); - - List<Line2D> lines1 = reaction1.getLines(); - List<Line2D> lines2 = reaction2.getLines(); - - for (int i = 0; i < lines1.size(); i++) { - assertEquals(lines1.get(i).getX1(), lines2.get(i).getX1(), 1e-6); - assertEquals(lines1.get(i).getX2(), lines2.get(i).getX2(), 1e-6); - assertEquals(lines1.get(i).getY1(), lines2.get(i).getY1(), 1e-6); - assertEquals(lines1.get(i).getY2(), lines2.get(i).getY2(), 1e-6); - } - assertEquals(reaction1.getClass(), reaction2.getClass()); - } catch (Exception e) { - logger.error(e.getMessage(), e); - throw e; + Model model = getModelFilledWithSpecies(); + String xmlString = readFile("testFiles/xmlNodeTestExamples/reaction_transcription.xml"); + Node node = getNodeFromXmlString(xmlString); + Reaction reaction1 = parser.getReaction(node, model); + + String xmlString2 = parser.toXml(reaction1); + assertNotNull(xmlString2); + // logger.debug(xmlString2); + Node node2 = getNodeFromXmlString(xmlString2); + Reaction reaction2 = parser.getReaction(node2, model); + + List<Line2D> lines1 = reaction1.getLines(); + List<Line2D> lines2 = reaction2.getLines(); + + for (int i = 0; i < lines1.size(); i++) { + assertEquals(lines1.get(i).getX1(), lines2.get(i).getX1(), 1e-6); + assertEquals(lines1.get(i).getX2(), lines2.get(i).getX2(), 1e-6); + assertEquals(lines1.get(i).getY1(), lines2.get(i).getY1(), 1e-6); + assertEquals(lines1.get(i).getY2(), lines2.get(i).getY2(), 1e-6); } + assertEquals(reaction1.getClass(), reaction2.getClass()); } @Test public void testTranscriptionWithAdditionsToXml() throws Exception { - try { - Model model = getModelFilledWithSpecies(); - String xmlString = readFile("testFiles/xmlNodeTestExamples/reaction_transcription_with_additions.xml"); - Node node = getNodeFromXmlString(xmlString); - Reaction reaction1 = parser.getReaction(node, model); - - String xmlString2 = parser.toXml(reaction1); - assertNotNull(xmlString2); - // logger.debug(xmlString2); - Node node2 = getNodeFromXmlString(xmlString2); - Reaction reaction2 = parser.getReaction(node2, model); - - List<Line2D> lines1 = reaction1.getLines(); - List<Line2D> lines2 = reaction2.getLines(); - - for (int i = 0; i < lines1.size(); i++) { - assertEquals(lines1.get(i).getX1(), lines2.get(i).getX1(), 1e-6); - assertEquals(lines1.get(i).getX2(), lines2.get(i).getX2(), 1e-6); - assertEquals(lines1.get(i).getY1(), lines2.get(i).getY1(), 1e-6); - assertEquals(lines1.get(i).getY2(), lines2.get(i).getY2(), 1e-6); - } - assertEquals(reaction1.getClass(), reaction2.getClass()); - } catch (Exception e) { - e.printStackTrace(); - throw e; + Model model = getModelFilledWithSpecies(); + String xmlString = readFile("testFiles/xmlNodeTestExamples/reaction_transcription_with_additions.xml"); + Node node = getNodeFromXmlString(xmlString); + Reaction reaction1 = parser.getReaction(node, model); + + String xmlString2 = parser.toXml(reaction1); + assertNotNull(xmlString2); + // logger.debug(xmlString2); + Node node2 = getNodeFromXmlString(xmlString2); + Reaction reaction2 = parser.getReaction(node2, model); + + List<Line2D> lines1 = reaction1.getLines(); + List<Line2D> lines2 = reaction2.getLines(); + + for (int i = 0; i < lines1.size(); i++) { + assertEquals(lines1.get(i).getX1(), lines2.get(i).getX1(), 1e-6); + assertEquals(lines1.get(i).getX2(), lines2.get(i).getX2(), 1e-6); + assertEquals(lines1.get(i).getY1(), lines2.get(i).getY1(), 1e-6); + assertEquals(lines1.get(i).getY2(), lines2.get(i).getY2(), 1e-6); } + assertEquals(reaction1.getClass(), reaction2.getClass()); } @Test public void testReactionWithOperatorsToXml() throws Exception { - try { - Model model = getModelFilledWithSpecies(); - String xmlString = readFile("testFiles/xmlNodeTestExamples/reaction_with_operators.xml"); - Node node = getNodeFromXmlString(xmlString); - Reaction reaction1 = parser.getReaction(node, model); - - String xmlString2 = parser.toXml(reaction1); - assertNotNull(xmlString2); - // logger.debug(xmlString2); - Node node2 = getNodeFromXmlString(xmlString2); - Reaction reaction2 = parser.getReaction(node2, model); - - List<Line2D> lines1 = reaction1.getLines(); - List<Line2D> lines2 = reaction2.getLines(); - - for (int i = 0; i < lines1.size(); i++) { - assertEquals(lines1.get(i).getX1(), lines2.get(i).getX1(), 1e-6); - assertEquals(lines1.get(i).getX2(), lines2.get(i).getX2(), 1e-6); - assertEquals(lines1.get(i).getY1(), lines2.get(i).getY1(), 1e-6); - assertEquals(lines1.get(i).getY2(), lines2.get(i).getY2(), 1e-6); - } - assertEquals(reaction1.getClass(), reaction2.getClass()); - } catch (Exception e) { - logger.error(e.getMessage(), e); - throw e; + Model model = getModelFilledWithSpecies(); + String xmlString = readFile("testFiles/xmlNodeTestExamples/reaction_with_operators.xml"); + Node node = getNodeFromXmlString(xmlString); + Reaction reaction1 = parser.getReaction(node, model); + + String xmlString2 = parser.toXml(reaction1); + assertNotNull(xmlString2); + // logger.debug(xmlString2); + Node node2 = getNodeFromXmlString(xmlString2); + Reaction reaction2 = parser.getReaction(node2, model); + + List<Line2D> lines1 = reaction1.getLines(); + List<Line2D> lines2 = reaction2.getLines(); + + for (int i = 0; i < lines1.size(); i++) { + assertEquals(lines1.get(i).getX1(), lines2.get(i).getX1(), 1e-6); + assertEquals(lines1.get(i).getX2(), lines2.get(i).getX2(), 1e-6); + assertEquals(lines1.get(i).getY1(), lines2.get(i).getY1(), 1e-6); + assertEquals(lines1.get(i).getY2(), lines2.get(i).getY2(), 1e-6); } + assertEquals(reaction1.getClass(), reaction2.getClass()); } @Test public void testReactionWithModifiersToXml() throws Exception { - try { - Model model = getModelFilledWithSpecies(); - String xmlString = readFile("testFiles/xmlNodeTestExamples/reaction_with_modifiers.xml"); - Node node = getNodeFromXmlString(xmlString); - Reaction reaction1 = parser.getReaction(node, model); - - String xmlString2 = parser.toXml(reaction1); - assertNotNull(xmlString2); - // logger.debug(xmlString2); - Node node2 = getNodeFromXmlString(xmlString2); - - Reaction reaction2 = parser.getReaction(node2, model); - - List<Line2D> lines1 = reaction1.getLines(); - List<Line2D> lines2 = reaction2.getLines(); - - for (int i = 0; i < lines1.size(); i++) { - assertEquals(lines1.get(i).getX1(), lines2.get(i).getX1(), 1e-6); - assertEquals(lines1.get(i).getX2(), lines2.get(i).getX2(), 1e-6); - assertEquals(lines1.get(i).getY1(), lines2.get(i).getY1(), 1e-6); - assertEquals(lines1.get(i).getY2(), lines2.get(i).getY2(), 1e-6); - } - assertEquals(reaction1.getClass(), reaction2.getClass()); - } catch (Exception e) { - logger.error(e.getMessage(), e); - throw e; + Model model = getModelFilledWithSpecies(); + String xmlString = readFile("testFiles/xmlNodeTestExamples/reaction_with_modifiers.xml"); + Node node = getNodeFromXmlString(xmlString); + Reaction reaction1 = parser.getReaction(node, model); + + String xmlString2 = parser.toXml(reaction1); + assertNotNull(xmlString2); + // logger.debug(xmlString2); + Node node2 = getNodeFromXmlString(xmlString2); + + Reaction reaction2 = parser.getReaction(node2, model); + + List<Line2D> lines1 = reaction1.getLines(); + List<Line2D> lines2 = reaction2.getLines(); + + for (int i = 0; i < lines1.size(); i++) { + assertEquals(lines1.get(i).getX1(), lines2.get(i).getX1(), 1e-6); + assertEquals(lines1.get(i).getX2(), lines2.get(i).getX2(), 1e-6); + assertEquals(lines1.get(i).getY1(), lines2.get(i).getY1(), 1e-6); + assertEquals(lines1.get(i).getY2(), lines2.get(i).getY2(), 1e-6); } + assertEquals(reaction1.getClass(), reaction2.getClass()); } @Test public void testReactionPositiveInfluenceToXml() throws Exception { - try { - Model model = getModelFilledWithSpecies(); - String xmlString = readFile("testFiles/xmlNodeTestExamples/reaction_positive_influence.xml"); - Node node = getNodeFromXmlString(xmlString); - Reaction reaction1 = parser.getReaction(node, model); - - String xmlString2 = parser.toXml(reaction1); - assertNotNull(xmlString2); - // logger.debug(xmlString2); - Node node2 = getNodeFromXmlString(xmlString2); - Reaction reaction2 = parser.getReaction(node2, model); - - List<Line2D> lines1 = reaction1.getLines(); - List<Line2D> lines2 = reaction2.getLines(); - - for (int i = 0; i < lines1.size(); i++) { - assertEquals(lines1.get(i).getX1(), lines2.get(i).getX1(), 1e-6); - assertEquals(lines1.get(i).getX2(), lines2.get(i).getX2(), 1e-6); - assertEquals(lines1.get(i).getY1(), lines2.get(i).getY1(), 1e-6); - assertEquals(lines1.get(i).getY2(), lines2.get(i).getY2(), 1e-6); - } - assertEquals(reaction1.getClass(), reaction2.getClass()); - } catch (Exception e) { - logger.error(e.getMessage(), e); - throw e; + Model model = getModelFilledWithSpecies(); + String xmlString = readFile("testFiles/xmlNodeTestExamples/reaction_positive_influence.xml"); + Node node = getNodeFromXmlString(xmlString); + Reaction reaction1 = parser.getReaction(node, model); + + String xmlString2 = parser.toXml(reaction1); + assertNotNull(xmlString2); + // logger.debug(xmlString2); + Node node2 = getNodeFromXmlString(xmlString2); + Reaction reaction2 = parser.getReaction(node2, model); + + List<Line2D> lines1 = reaction1.getLines(); + List<Line2D> lines2 = reaction2.getLines(); + + for (int i = 0; i < lines1.size(); i++) { + assertEquals(lines1.get(i).getX1(), lines2.get(i).getX1(), 1e-6); + assertEquals(lines1.get(i).getX2(), lines2.get(i).getX2(), 1e-6); + assertEquals(lines1.get(i).getY1(), lines2.get(i).getY1(), 1e-6); + assertEquals(lines1.get(i).getY2(), lines2.get(i).getY2(), 1e-6); } + assertEquals(reaction1.getClass(), reaction2.getClass()); } @Test public void testReactionHeterodimerWithAdditionsToXml() throws Exception { - try { - Model model = getModelFilledWithSpecies(); - String xmlString = readFile("testFiles/xmlNodeTestExamples/reaction_heterodimer_with_additions.xml"); - Node node = getNodeFromXmlString(xmlString); - Reaction reaction1 = parser.getReaction(node, model); - - String xmlString2 = parser.toXml(reaction1); - assertNotNull(xmlString2); - // logger.debug(xmlString2); - Node node2 = getNodeFromXmlString(xmlString2); - Reaction reaction2 = parser.getReaction(node2, model); - - assertEquals(reaction1.getNodes().size(), reaction2.getNodes().size()); - - List<Line2D> lines1 = reaction1.getLines(); - List<Line2D> lines2 = reaction2.getLines(); - - for (int i = 0; i < lines1.size(); i++) { - assertEquals(lines1.get(i).getX1(), lines2.get(i).getX1(), 1e-6); - assertEquals(lines1.get(i).getX2(), lines2.get(i).getX2(), 1e-6); - assertEquals(lines1.get(i).getY1(), lines2.get(i).getY1(), 1e-6); - assertEquals(lines1.get(i).getY2(), lines2.get(i).getY2(), 1e-6); - } - assertEquals(reaction1.getClass(), reaction2.getClass()); - } catch (Exception e) { - e.printStackTrace(); - throw e; + Model model = getModelFilledWithSpecies(); + String xmlString = readFile("testFiles/xmlNodeTestExamples/reaction_heterodimer_with_additions.xml"); + Node node = getNodeFromXmlString(xmlString); + Reaction reaction1 = parser.getReaction(node, model); + + String xmlString2 = parser.toXml(reaction1); + assertNotNull(xmlString2); + // logger.debug(xmlString2); + Node node2 = getNodeFromXmlString(xmlString2); + Reaction reaction2 = parser.getReaction(node2, model); + + assertEquals(reaction1.getNodes().size(), reaction2.getNodes().size()); + + List<Line2D> lines1 = reaction1.getLines(); + List<Line2D> lines2 = reaction2.getLines(); + + for (int i = 0; i < lines1.size(); i++) { + assertEquals(lines1.get(i).getX1(), lines2.get(i).getX1(), 1e-6); + assertEquals(lines1.get(i).getX2(), lines2.get(i).getX2(), 1e-6); + assertEquals(lines1.get(i).getY1(), lines2.get(i).getY1(), 1e-6); + assertEquals(lines1.get(i).getY2(), lines2.get(i).getY2(), 1e-6); } + assertEquals(reaction1.getClass(), reaction2.getClass()); } @Test public void testReactionHeterodimerToXml() throws Exception { - try { - Model model = getModelFilledWithSpecies(); - String xmlString = readFile("testFiles/xmlNodeTestExamples/reaction_heterodimer.xml"); - Node node = getNodeFromXmlString(xmlString); - Reaction reaction1 = parser.getReaction(node, model); - - String xmlString2 = parser.toXml(reaction1); - assertNotNull(xmlString2); - // logger.debug(xmlString2); - Node node2 = getNodeFromXmlString(xmlString2); - Reaction reaction2 = parser.getReaction(node2, model); - - assertEquals(reaction1.getNodes().size(), reaction2.getNodes().size()); - - List<Line2D> lines1 = reaction1.getLines(); - List<Line2D> lines2 = reaction2.getLines(); - - for (int i = 0; i < lines1.size(); i++) { - assertEquals(lines1.get(i).getX1(), lines2.get(i).getX1(), 1e-6); - assertEquals(lines1.get(i).getX2(), lines2.get(i).getX2(), 1e-6); - assertEquals(lines1.get(i).getY1(), lines2.get(i).getY1(), 1e-6); - assertEquals(lines1.get(i).getY2(), lines2.get(i).getY2(), 1e-6); - } - assertEquals(reaction1.getClass(), reaction2.getClass()); - } catch (Exception e) { - logger.error(e.getMessage(), e); - throw e; + Model model = getModelFilledWithSpecies(); + String xmlString = readFile("testFiles/xmlNodeTestExamples/reaction_heterodimer.xml"); + Node node = getNodeFromXmlString(xmlString); + Reaction reaction1 = parser.getReaction(node, model); + + String xmlString2 = parser.toXml(reaction1); + assertNotNull(xmlString2); + // logger.debug(xmlString2); + Node node2 = getNodeFromXmlString(xmlString2); + Reaction reaction2 = parser.getReaction(node2, model); + + assertEquals(reaction1.getNodes().size(), reaction2.getNodes().size()); + + List<Line2D> lines1 = reaction1.getLines(); + List<Line2D> lines2 = reaction2.getLines(); + + for (int i = 0; i < lines1.size(); i++) { + assertEquals(lines1.get(i).getX1(), lines2.get(i).getX1(), 1e-6); + assertEquals(lines1.get(i).getX2(), lines2.get(i).getX2(), 1e-6); + assertEquals(lines1.get(i).getY1(), lines2.get(i).getY1(), 1e-6); + assertEquals(lines1.get(i).getY2(), lines2.get(i).getY2(), 1e-6); } + assertEquals(reaction1.getClass(), reaction2.getClass()); } @Test public void testOperatorInReactionHeterodimer() throws Exception { - try { - Model model = getModelFilledWithSpecies(); - String xmlString = readFile("testFiles/xmlNodeTestExamples/reaction_heterodimer.xml"); - Node node = getNodeFromXmlString(xmlString); - Reaction reaction1 = parser.getReaction(node, model); - for (NodeOperator operator : reaction1.getOperators()) { - assertTrue(operator instanceof AssociationOperator); - } - } catch (Exception e) { - logger.error(e.getMessage(), e); - throw e; + Model model = getModelFilledWithSpecies(); + String xmlString = readFile("testFiles/xmlNodeTestExamples/reaction_heterodimer.xml"); + Node node = getNodeFromXmlString(xmlString); + Reaction reaction1 = parser.getReaction(node, model); + for (NodeOperator operator : reaction1.getOperators()) { + assertTrue(operator instanceof AssociationOperator); } } @Test public void testReactionDissociationWithAdditionToXml() throws Exception { - try { - Model model = getModelFilledWithSpecies(); - String xmlString = readFile("testFiles/xmlNodeTestExamples/reaction_dissociation_with_addition.xml"); - Node node = getNodeFromXmlString(xmlString); - Reaction reaction1 = parser.getReaction(node, model); - - String xmlString2 = parser.toXml(reaction1); - assertNotNull(xmlString2); - // logger.debug(xmlString2); - Node node2 = getNodeFromXmlString(xmlString2); - Reaction reaction2 = parser.getReaction(node2, model); - - assertEquals(reaction1.getName(), reaction2.getName()); - assertNotNull(reaction1.getName()); - assertFalse(reaction1.getName().trim().equals("")); - List<Line2D> lines1 = reaction1.getLines(); - List<Line2D> lines2 = reaction2.getLines(); - - for (int i = 0; i < lines1.size(); i++) { - assertEquals(lines1.get(i).getX1(), lines2.get(i).getX1(), 1e-6); - assertEquals(lines1.get(i).getX2(), lines2.get(i).getX2(), 1e-6); - assertEquals(lines1.get(i).getY1(), lines2.get(i).getY1(), 1e-6); - assertEquals(lines1.get(i).getY2(), lines2.get(i).getY2(), 1e-6); - } - assertEquals(reaction1.getClass(), reaction2.getClass()); - } catch (Exception e) { - logger.error(e.getMessage(), e); - throw e; + Model model = getModelFilledWithSpecies(); + String xmlString = readFile("testFiles/xmlNodeTestExamples/reaction_dissociation_with_addition.xml"); + Node node = getNodeFromXmlString(xmlString); + Reaction reaction1 = parser.getReaction(node, model); + + String xmlString2 = parser.toXml(reaction1); + assertNotNull(xmlString2); + // logger.debug(xmlString2); + Node node2 = getNodeFromXmlString(xmlString2); + Reaction reaction2 = parser.getReaction(node2, model); + + assertEquals(reaction1.getName(), reaction2.getName()); + assertNotNull(reaction1.getName()); + assertFalse(reaction1.getName().trim().equals("")); + List<Line2D> lines1 = reaction1.getLines(); + List<Line2D> lines2 = reaction2.getLines(); + + for (int i = 0; i < lines1.size(); i++) { + assertEquals(lines1.get(i).getX1(), lines2.get(i).getX1(), 1e-6); + assertEquals(lines1.get(i).getX2(), lines2.get(i).getX2(), 1e-6); + assertEquals(lines1.get(i).getY1(), lines2.get(i).getY1(), 1e-6); + assertEquals(lines1.get(i).getY2(), lines2.get(i).getY2(), 1e-6); } + assertEquals(reaction1.getClass(), reaction2.getClass()); } private Model getModelFilledWithSpecies() { @@ -1703,247 +1290,172 @@ public class ReactionParserTests extends CellDesignerTestFunctions { @Test public void testLogiGateAndReaction() throws Exception { - Model model; - try { - model = getModelForFile("testFiles/reactions/logicGateAnd.xml"); - assertEquals(1, model.getReactions().size()); - Reaction reaction = model.getReactions().iterator().next(); - assertTrue(reaction instanceof ReducedTriggerReaction); - assertEquals(1, reaction.getOperators().size()); - assertTrue(reaction.getOperators().get(0) instanceof AndOperator); - assertEquals(2, reaction.getReactants().size()); - assertEquals(1, reaction.getProducts().size()); - - assertEquals(0.0, reaction.getReactants().get(0).getLine().getEndPoint().distance(200.0, 127.0), EPSILON); - assertEquals(0.0, reaction.getReactants().get(1).getLine().getEndPoint().distance(200.0, 127.0), EPSILON); - assertEquals(0.0, reaction.getOperators().get(0).getLine().getBeginPoint().distance(200.0, 127.0), EPSILON); - - super.testXmlSerialization(model); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Model model = getModelForFile("testFiles/reactions/logicGateAnd.xml"); + assertEquals(1, model.getReactions().size()); + Reaction reaction = model.getReactions().iterator().next(); + assertTrue(reaction instanceof ReducedTriggerReaction); + assertEquals(1, reaction.getOperators().size()); + assertTrue(reaction.getOperators().get(0) instanceof AndOperator); + assertEquals(2, reaction.getReactants().size()); + assertEquals(1, reaction.getProducts().size()); + + assertEquals(0.0, reaction.getReactants().get(0).getLine().getEndPoint().distance(200.0, 127.0), EPSILON); + assertEquals(0.0, reaction.getReactants().get(1).getLine().getEndPoint().distance(200.0, 127.0), EPSILON); + assertEquals(0.0, reaction.getOperators().get(0).getLine().getBeginPoint().distance(200.0, 127.0), EPSILON); + + super.testXmlSerialization(model); } @Test public void testLogiGateAndWithThreeInputsReaction() throws Exception { - Model model; - try { - model = getModelForFile("testFiles/reactions/logicGateAndWithThreeInputs.xml"); - assertEquals(1, model.getReactions().size()); - Reaction reaction = model.getReactions().iterator().next(); - assertTrue(reaction instanceof ReducedTriggerReaction); - - super.testXmlSerialization(model); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Model model = getModelForFile("testFiles/reactions/logicGateAndWithThreeInputs.xml"); + assertEquals(1, model.getReactions().size()); + Reaction reaction = model.getReactions().iterator().next(); + assertTrue(reaction instanceof ReducedTriggerReaction); + + super.testXmlSerialization(model); } @Test public void testLogiGateOrReaction() throws Exception { - Model model; - try { - model = getModelForFile("testFiles/reactions/logicGateOr.xml"); - assertEquals(1, model.getReactions().size()); - Reaction reaction = model.getReactions().iterator().next(); - assertTrue(reaction instanceof NegativeInfluenceReaction); - assertEquals(1, reaction.getOperators().size()); - assertTrue(reaction.getOperators().get(0) instanceof OrOperator); - assertEquals(2, reaction.getReactants().size()); - assertEquals(1, reaction.getProducts().size()); - - assertEquals(0.0, reaction.getReactants().get(0).getLine().getEndPoint().distance(200.0, 127.0), EPSILON); - assertEquals(0.0, reaction.getReactants().get(1).getLine().getEndPoint().distance(200.0, 127.0), EPSILON); - assertEquals(0.0, reaction.getOperators().get(0).getLine().getBeginPoint().distance(200.0, 127.0), EPSILON); - - super.testXmlSerialization(model); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Model model = getModelForFile("testFiles/reactions/logicGateOr.xml"); + assertEquals(1, model.getReactions().size()); + Reaction reaction = model.getReactions().iterator().next(); + assertTrue(reaction instanceof NegativeInfluenceReaction); + assertEquals(1, reaction.getOperators().size()); + assertTrue(reaction.getOperators().get(0) instanceof OrOperator); + assertEquals(2, reaction.getReactants().size()); + assertEquals(1, reaction.getProducts().size()); + + assertEquals(0.0, reaction.getReactants().get(0).getLine().getEndPoint().distance(200.0, 127.0), EPSILON); + assertEquals(0.0, reaction.getReactants().get(1).getLine().getEndPoint().distance(200.0, 127.0), EPSILON); + assertEquals(0.0, reaction.getOperators().get(0).getLine().getBeginPoint().distance(200.0, 127.0), EPSILON); + + super.testXmlSerialization(model); } @Test public void testLogiGateNotReaction() throws Exception { - Model model; - try { - model = getModelForFile("testFiles/reactions/logicGateNot.xml"); - assertEquals(1, model.getReactions().size()); - Reaction reaction = model.getReactions().iterator().next(); - assertTrue(reaction instanceof UnknownReducedPhysicalStimulationReaction); - assertEquals(1, reaction.getOperators().size()); - assertTrue(reaction.getOperators().get(0) instanceof NandOperator); - assertEquals(2, reaction.getReactants().size()); - assertEquals(1, reaction.getProducts().size()); - - assertEquals(0.0, reaction.getReactants().get(0).getLine().getEndPoint().distance(200.0, 127.0), EPSILON); - assertEquals(0.0, reaction.getReactants().get(1).getLine().getEndPoint().distance(200.0, 127.0), EPSILON); - assertEquals(0.0, reaction.getOperators().get(0).getLine().getBeginPoint().distance(200.0, 127.0), EPSILON); - - assertNotNull(reaction.getLine()); - - super.testXmlSerialization(model); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Model model = getModelForFile("testFiles/reactions/logicGateNot.xml"); + assertEquals(1, model.getReactions().size()); + Reaction reaction = model.getReactions().iterator().next(); + assertTrue(reaction instanceof UnknownReducedPhysicalStimulationReaction); + assertEquals(1, reaction.getOperators().size()); + assertTrue(reaction.getOperators().get(0) instanceof NandOperator); + assertEquals(2, reaction.getReactants().size()); + assertEquals(1, reaction.getProducts().size()); + + assertEquals(0.0, reaction.getReactants().get(0).getLine().getEndPoint().distance(200.0, 127.0), EPSILON); + assertEquals(0.0, reaction.getReactants().get(1).getLine().getEndPoint().distance(200.0, 127.0), EPSILON); + assertEquals(0.0, reaction.getOperators().get(0).getLine().getBeginPoint().distance(200.0, 127.0), EPSILON); + + assertNotNull(reaction.getLine()); + + super.testXmlSerialization(model); } @Test public void testLogiGateUnknownReaction() throws Exception { - Model model; - try { - model = getModelForFile("testFiles/reactions/logicGateUnknown.xml"); - assertEquals(1, model.getReactions().size()); - Reaction reaction = model.getReactions().iterator().next(); - assertTrue(reaction instanceof ReducedTriggerReaction); - assertEquals(1, reaction.getOperators().size()); - assertTrue(reaction.getOperators().get(0) instanceof UnknownOperator); - assertEquals(2, reaction.getReactants().size()); - assertEquals(1, reaction.getProducts().size()); - - assertEquals(0.0, reaction.getReactants().get(0).getLine().getEndPoint().distance(200.0, 127.0), EPSILON); - assertEquals(0.0, reaction.getReactants().get(1).getLine().getEndPoint().distance(200.0, 127.0), EPSILON); - assertEquals(0.0, reaction.getOperators().get(0).getLine().getBeginPoint().distance(200.0, 127.0), EPSILON); - - super.testXmlSerialization(model); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Model model = getModelForFile("testFiles/reactions/logicGateUnknown.xml"); + assertEquals(1, model.getReactions().size()); + Reaction reaction = model.getReactions().iterator().next(); + assertTrue(reaction instanceof ReducedTriggerReaction); + assertEquals(1, reaction.getOperators().size()); + assertTrue(reaction.getOperators().get(0) instanceof UnknownOperator); + assertEquals(2, reaction.getReactants().size()); + assertEquals(1, reaction.getProducts().size()); + + assertEquals(0.0, reaction.getReactants().get(0).getLine().getEndPoint().distance(200.0, 127.0), EPSILON); + assertEquals(0.0, reaction.getReactants().get(1).getLine().getEndPoint().distance(200.0, 127.0), EPSILON); + assertEquals(0.0, reaction.getOperators().get(0).getLine().getBeginPoint().distance(200.0, 127.0), EPSILON); + + super.testXmlSerialization(model); } @Test public void testHeterodimerWithAdditionalReactant() throws Exception { - Model model; - try { - model = getModelForFile("testFiles/reactions/heterodimer_association_with_additional_reactant.xml"); - assertEquals(1, model.getReactions().size()); - Reaction reaction = model.getReactions().iterator().next(); - - NodeOperator o1 = reaction.getOperators().get(0); - NodeOperator o2 = reaction.getOperators().get(1); + Model model = getModelForFile("testFiles/reactions/heterodimer_association_with_additional_reactant.xml"); + assertEquals(1, model.getReactions().size()); + Reaction reaction = model.getReactions().iterator().next(); - assertEquals(0, o1.getLine().getEndPoint().distance(o2.getLine().getBeginPoint()), Configuration.EPSILON); + NodeOperator o1 = reaction.getOperators().get(0); + NodeOperator o2 = reaction.getOperators().get(1); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, o1.getLine().getEndPoint().distance(o2.getLine().getBeginPoint()), Configuration.EPSILON); } @Test public void testProblematicDrawing() throws Exception { - Model model; - try { - model = getModelForFile("testFiles/problematic/reaction_drawing_problem.xml"); - Reaction reaction = model.getReactionByReactionId("re1"); - assertNotNull(reaction.getLine()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Model model = getModelForFile("testFiles/problematic/reaction_drawing_problem.xml"); + Reaction reaction = model.getReactionByReactionId("re1"); + assertNotNull(reaction.getLine()); } @Test public void testProteinsInsideComplex() throws Exception { - try { - Model model = getModelForFile("testFiles/problematic/proteins_inside_complex.xml"); - for (Element el : model.getElements()) { - assertFalse(el.getClass().equals(Protein.class)); - } - } catch (Exception e) { - e.printStackTrace(); - throw e; + Model model = getModelForFile("testFiles/problematic/proteins_inside_complex.xml"); + for (Element el : model.getElements()) { + assertFalse(el.getClass().equals(Protein.class)); } } @Test public void testKinetcs() throws Exception { - try { - Model model = getModelForFile("testFiles/reactions/kinetics.xml"); - Reaction reaction = model.getReactionByReactionId("re1"); - assertNotNull(reaction.getKinetics()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Model model = getModelForFile("testFiles/reactions/kinetics.xml"); + Reaction reaction = model.getReactionByReactionId("re1"); + assertNotNull(reaction.getKinetics()); } @Test public void testKinetcsWithCompartment() throws Exception { - try { - Model model = getModelForFile("testFiles/reactions/kinetics_with_compartment.xml"); - Reaction reaction = model.getReactionByReactionId("re1"); - assertNotNull(reaction.getKinetics()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Model model = getModelForFile("testFiles/reactions/kinetics_with_compartment.xml"); + Reaction reaction = model.getReactionByReactionId("re1"); + assertNotNull(reaction.getKinetics()); } @Test public void testModifierWithOperator() throws Exception { - try { - Model model = getModelForFile("testFiles/reactions/modifier_with_operator.xml"); - Reaction reaction = model.getReactionByReactionId("re1"); - assertEquals(3, reaction.getOperators().iterator().next().getLine().getPoints().size()); - assertEquals(3, reaction.getModifiers().get(0).getLine().getPoints().size()); - assertEquals(3, reaction.getModifiers().get(1).getLine().getPoints().size()); - Model model2 = super.serializeModel(model); - reaction = model2.getReactionByReactionId("re1"); - assertEquals(3, reaction.getOperators().iterator().next().getLine().getPoints().size()); - assertEquals(3, reaction.getModifiers().get(0).getLine().getPoints().size()); - assertEquals(3, reaction.getModifiers().get(1).getLine().getPoints().size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Model model = getModelForFile("testFiles/reactions/modifier_with_operator.xml"); + Reaction reaction = model.getReactionByReactionId("re1"); + assertEquals(3, reaction.getOperators().iterator().next().getLine().getPoints().size()); + assertEquals(3, reaction.getModifiers().get(0).getLine().getPoints().size()); + assertEquals(3, reaction.getModifiers().get(1).getLine().getPoints().size()); + Model model2 = super.serializeModel(model); + reaction = model2.getReactionByReactionId("re1"); + assertEquals(3, reaction.getOperators().iterator().next().getLine().getPoints().size()); + assertEquals(3, reaction.getModifiers().get(0).getLine().getPoints().size()); + assertEquals(3, reaction.getModifiers().get(1).getLine().getPoints().size()); } @Test public void testProblematicHeterodimerAssociation() throws Exception { - Model model; - try { - model = getModelForFile("testFiles/problematic/problematic_heterodimer_association.xml"); - Reaction reaction = model.getReactions().iterator().next(); - for (Line2D line : reaction.getLines()) { - assertTrue("Expected coordinates must be not negative. Found: " + line.getP1(), line.getP1().getX() >= 0); - assertTrue("Expected coordinates must be not negative. Found: " + line.getP1(), line.getP1().getY() >= 0); - assertTrue("Expected coordinates must be not negative. Found: " + line.getP2(), line.getP2().getX() >= 0); - assertTrue("Expected coordinates must be not negative. Found: " + line.getP2(), line.getP2().getY() >= 0); - } - } catch (Exception e) { - e.printStackTrace(); - throw e; + Model model = getModelForFile("testFiles/problematic/problematic_heterodimer_association.xml"); + Reaction reaction = model.getReactions().iterator().next(); + for (Line2D line : reaction.getLines()) { + assertTrue("Expected coordinates must be not negative. Found: " + line.getP1(), line.getP1().getX() >= 0); + assertTrue("Expected coordinates must be not negative. Found: " + line.getP1(), line.getP1().getY() >= 0); + assertTrue("Expected coordinates must be not negative. Found: " + line.getP2(), line.getP2().getX() >= 0); + assertTrue("Expected coordinates must be not negative. Found: " + line.getP2(), line.getP2().getY() >= 0); } } @Test public void testGateReactionWithMoreParticipants() throws Exception { - Model model; - try { - model = getModelForFile("testFiles/reactions/logicGateWithMoreParticipants.xml"); - Reaction reaction = model.getReactionByReactionId("re1"); - assertEquals(3, reaction.getReactants().size()); - Reactant r1 = reaction.getReactants().get(0); - Reactant r2 = reaction.getReactants().get(1); - Reactant r3 = reaction.getReactants().get(2); - Product p = reaction.getProducts().get(0); - - assertEquals(3, r1.getLine().getPoints().size()); - assertEquals(2, r2.getLine().getPoints().size()); - assertEquals(3, r3.getLine().getPoints().size()); - - assertEquals(2, p.getLine().getPoints().size()); - - super.testXmlSerialization(model); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Model model = getModelForFile("testFiles/reactions/logicGateWithMoreParticipants.xml"); + Reaction reaction = model.getReactionByReactionId("re1"); + assertEquals(3, reaction.getReactants().size()); + Reactant r1 = reaction.getReactants().get(0); + Reactant r2 = reaction.getReactants().get(1); + Reactant r3 = reaction.getReactants().get(2); + Product p = reaction.getProducts().get(0); + + assertEquals(3, r1.getLine().getPoints().size()); + assertEquals(2, r2.getLine().getPoints().size()); + assertEquals(3, r3.getLine().getPoints().size()); + + assertEquals(2, p.getLine().getPoints().size()); + + super.testXmlSerialization(model); } } diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/reaction/ReactionToXmlTest.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/reaction/ReactionToXmlTest.java index f2a0a13b991394f56e4bd161b545da1c3f323f80..3b13bce3e6901607d6a2692c79a98ecb285104ce 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/reaction/ReactionToXmlTest.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/reaction/ReactionToXmlTest.java @@ -1,9 +1,6 @@ package lcsb.mapviewer.converter.model.celldesigner.reaction; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import java.awt.geom.Point2D; import java.util.ArrayList; @@ -11,10 +8,7 @@ import java.util.List; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import lcsb.mapviewer.common.exception.InvalidArgumentException; import lcsb.mapviewer.converter.model.celldesigner.CellDesignerElementCollection; @@ -24,20 +18,9 @@ import lcsb.mapviewer.model.map.InconsistentModelException; import lcsb.mapviewer.model.map.model.Model; import lcsb.mapviewer.model.map.model.ModelFullIndexed; import lcsb.mapviewer.model.map.modifier.Catalysis; -import lcsb.mapviewer.model.map.reaction.AndOperator; -import lcsb.mapviewer.model.map.reaction.Modifier; -import lcsb.mapviewer.model.map.reaction.NodeOperator; -import lcsb.mapviewer.model.map.reaction.OrOperator; -import lcsb.mapviewer.model.map.reaction.Product; -import lcsb.mapviewer.model.map.reaction.Reactant; -import lcsb.mapviewer.model.map.reaction.Reaction; -import lcsb.mapviewer.model.map.reaction.SplitOperator; -import lcsb.mapviewer.model.map.reaction.type.DissociationReaction; -import lcsb.mapviewer.model.map.reaction.type.TransportReaction; -import lcsb.mapviewer.model.map.reaction.type.TriggerReaction; -import lcsb.mapviewer.model.map.species.Complex; -import lcsb.mapviewer.model.map.species.GenericProtein; -import lcsb.mapviewer.model.map.species.Species; +import lcsb.mapviewer.model.map.reaction.*; +import lcsb.mapviewer.model.map.reaction.type.*; +import lcsb.mapviewer.model.map.species.*; public class ReactionToXmlTest extends CellDesignerTestFunctions { Logger logger = LogManager.getLogger(ReactionToXmlTest.class); @@ -152,7 +135,7 @@ public class ReactionToXmlTest extends CellDesignerTestFunctions { } - @Test + @Test(expected = InvalidArgumentException.class) public void testInvalidToXml() throws InconsistentModelException { Model model = new ModelFullIndexed(null); @@ -175,16 +158,11 @@ public class ReactionToXmlTest extends CellDesignerTestFunctions { reaction.addReactant(reactant); reaction.addProduct(product); - try { - toXmlParser.toXml(reaction); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - - } + toXmlParser.toXml(reaction); } - @Test + @Test(expected = InvalidArgumentException.class) public void testInvalidReaction() throws InconsistentModelException { Model model = new ModelFullIndexed(null); @@ -204,53 +182,31 @@ public class ReactionToXmlTest extends CellDesignerTestFunctions { reaction.addReactant(reactant); reaction.addProduct(product); - try { - toXmlParser.toXml(reaction); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - assertTrue(e.getMessage().contains("Unknown reaction type")); - } + toXmlParser.toXml(reaction); } - @Test + @Test(expected = InvalidArgumentException.class) public void testGetConnectSchemeXmlStringForReaction() { - try { - toXmlParser.getConnectSchemeXmlStringForReaction(new Reaction()); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - assertTrue(e.getMessage().contains("Unknown reaction type")); - } - + toXmlParser.getConnectSchemeXmlStringForReaction(new Reaction()); } - @Test + @Test(expected = InvalidArgumentException.class) public void testGetConnectSchemeXmlStringForReaction2() { - try { - // test internal implementation - toXmlParser = new ReactionToXml(elements, false) { - @Override - String getEditPointsXmlStringForReaction(Reaction reaction) { - return ""; - } - }; - toXmlParser.getConnectSchemeXmlStringForReaction(new DissociationReaction()); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - assertTrue(e.getMessage().contains("Invalid editPoints string")); - } - + // test internal implementation + toXmlParser = new ReactionToXml(elements, false) { + @Override + String getEditPointsXmlStringForReaction(Reaction reaction) { + return ""; + } + }; + toXmlParser.getConnectSchemeXmlStringForReaction(new DissociationReaction()); } @Test public void testExportColorReactionWithModifierOperator() throws Exception { - try { - Model model = getModelForFile("testFiles/colorfull_reaction_2.xml"); - testXmlSerialization(model); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Model model = getModelForFile("testFiles/colorfull_reaction_2.xml"); + testXmlSerialization(model); } @Test @@ -289,6 +245,7 @@ public class ReactionToXmlTest extends CellDesignerTestFunctions { String type = toXmlParser.getCellDesignerReactionTypeString(r); assertFalse("BOOLEAN_LOGIC_GATE".equals(type)); } + @Test public void testGetEditPointsXmlStringForSimpleReaction() { Reaction r = new TriggerReaction(); @@ -303,7 +260,7 @@ public class ReactionToXmlTest extends CellDesignerTestFunctions { String result = toXmlParser.getEditPointsXmlStringForSimpleReaction(r); assertTrue(result.isEmpty()); } - + @Test public void testGetEditPointsXmlStringForSimpleReactionWhenNotImportedFromCD() { Reaction r = new TriggerReaction(); @@ -318,6 +275,5 @@ public class ReactionToXmlTest extends CellDesignerTestFunctions { String result = toXmlParser.getEditPointsXmlStringForSimpleReaction(r); assertFalse(result.isEmpty()); } - } diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/species/AntisenseRnaXmlParserTest.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/species/AntisenseRnaXmlParserTest.java index 5155ede974ae4b1ffacbd0f92f850ec13eecdadd..4d9bc179245f2caccc34d4da1633fb5d4326d1ec 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/species/AntisenseRnaXmlParserTest.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/species/AntisenseRnaXmlParserTest.java @@ -1,8 +1,6 @@ package lcsb.mapviewer.converter.model.celldesigner.species; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import java.io.StringReader; @@ -11,9 +9,7 @@ import javax.xml.parsers.DocumentBuilderFactory; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.w3c.dom.Document; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; @@ -45,114 +41,72 @@ public class AntisenseRnaXmlParserTest extends CellDesignerTestFunctions { @Test public void testParseXmlSpecies() throws Exception { - try { - String xmlString = readFile(testAntisenseRnaFile); - Pair<String, CellDesignerAntisenseRna> result = antisenseRnaParser.parseXmlElement(xmlString); - CellDesignerAntisenseRna antisenseRna = result.getRight(); - assertEquals("arn1", result.getLeft()); - assertEquals("s1", antisenseRna.getName()); - assertTrue(antisenseRna.getNotes().contains("some notes")); - assertEquals(1, antisenseRna.getRegions().size()); - CellDesignerModificationResidue region = antisenseRna.getRegions().get(0); - assertEquals("tr1", region.getIdModificationResidue()); - assertEquals("zzz", region.getName()); - assertEquals(0.3, region.getSize(), 1e-6); - assertEquals(0.29999999999999993, region.getPos(), 1e-6); - assertEquals(ModificationType.CODING_REGION, region.getModificationType()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String xmlString = readFile(testAntisenseRnaFile); + Pair<String, CellDesignerAntisenseRna> result = antisenseRnaParser.parseXmlElement(xmlString); + CellDesignerAntisenseRna antisenseRna = result.getRight(); + assertEquals("arn1", result.getLeft()); + assertEquals("s1", antisenseRna.getName()); + assertTrue(antisenseRna.getNotes().contains("some notes")); + assertEquals(1, antisenseRna.getRegions().size()); + CellDesignerModificationResidue region = antisenseRna.getRegions().get(0); + assertEquals("tr1", region.getIdModificationResidue()); + assertEquals("zzz", region.getName()); + assertEquals(0.3, region.getSize(), 1e-6); + assertEquals(0.29999999999999993, region.getPos(), 1e-6); + assertEquals(ModificationType.CODING_REGION, region.getModificationType()); } - @Test + @Test(expected = InvalidXmlSchemaException.class) public void testParseInvalidXmlSpecies() throws Exception { - try { - String xmlString = readFile("testFiles/invalid/antisense_rna.xml"); - antisenseRnaParser.parseXmlElement(xmlString); - fail("Exception expected"); - } catch (InvalidXmlSchemaException e) { - assertTrue(e.getMessage().contains("Unknown element of celldesigner:listOfRegions")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String xmlString = readFile("testFiles/invalid/antisense_rna.xml"); + antisenseRnaParser.parseXmlElement(xmlString); } - @Test + @Test(expected = InvalidXmlSchemaException.class) public void testParseInvalidXmlSpecies2() throws Exception { - try { - String xmlString = readFile("testFiles/invalid/antisense_rna2.xml"); - antisenseRnaParser.parseXmlElement(xmlString); - fail("Exception expected"); - } catch (InvalidXmlSchemaException e) { - assertTrue(e.getMessage().contains("Unknown element of celldesigner:antisenseRna")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String xmlString = readFile("testFiles/invalid/antisense_rna2.xml"); + antisenseRnaParser.parseXmlElement(xmlString); } - @Test + @Test(expected = InvalidXmlSchemaException.class) public void testParseInvalidXmlSpecies3() throws Exception { - try { - String xmlString = readFile("testFiles/invalid/antisense_rna3.xml"); - antisenseRnaParser.parseXmlElement(xmlString); - fail("Exception expected"); - } catch (InvalidXmlSchemaException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String xmlString = readFile("testFiles/invalid/antisense_rna3.xml"); + antisenseRnaParser.parseXmlElement(xmlString); } - @Test + @Test(expected = InvalidXmlSchemaException.class) public void testParseInvalidXmlSpecies4() throws Exception { - try { - String xmlString = readFile("testFiles/invalid/antisense_rna4.xml"); - antisenseRnaParser.parseXmlElement(xmlString); - fail("Exception expected"); - } catch (InvalidXmlSchemaException e) { - assertTrue(e.getMessage().contains("Unknown element of celldesigner:region")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String xmlString = readFile("testFiles/invalid/antisense_rna4.xml"); + antisenseRnaParser.parseXmlElement(xmlString); } @Test public void testToXml() throws Exception { - try { - String xmlString = readFile(testAntisenseRnaFile); - Pair<String, CellDesignerAntisenseRna> result = antisenseRnaParser.parseXmlElement(xmlString); - CellDesignerAntisenseRna antisenseRna = result.getRight(); - - String transformedXml = antisenseRnaParser.toXml(antisenseRna.createModelElement()); - DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); - DocumentBuilder builder = factory.newDocumentBuilder(); - InputSource is = new InputSource(new StringReader(transformedXml)); - Document doc = builder.parse(is); - NodeList root = doc.getChildNodes(); - assertEquals("celldesigner:AntisenseRNA", root.item(0).getNodeName()); - - Pair<String, CellDesignerAntisenseRna> result2 = antisenseRnaParser.parseXmlElement(xmlString); - CellDesignerAntisenseRna antisenseRna2 = result2.getRight(); - assertEquals(result.getLeft(), result2.getLeft()); - assertEquals(antisenseRna.getName(), antisenseRna2.getName()); - assertEquals(antisenseRna.getNotes().trim(), antisenseRna2.getNotes().trim()); - - assertEquals(1, antisenseRna2.getRegions().size()); - CellDesignerModificationResidue region = antisenseRna.getRegions().get(0); - CellDesignerModificationResidue region2 = antisenseRna2.getRegions().get(0); - assertEquals(region.getIdModificationResidue(), region2.getIdModificationResidue()); - assertEquals(region.getName(), region2.getName()); - assertEquals(region.getSize(), region2.getSize(), 1e-6); - assertEquals(region.getPos(), region2.getPos(), 1e-6); - assertEquals(region.getModificationType(), region2.getModificationType()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String xmlString = readFile(testAntisenseRnaFile); + Pair<String, CellDesignerAntisenseRna> result = antisenseRnaParser.parseXmlElement(xmlString); + CellDesignerAntisenseRna antisenseRna = result.getRight(); + + String transformedXml = antisenseRnaParser.toXml(antisenseRna.createModelElement()); + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + DocumentBuilder builder = factory.newDocumentBuilder(); + InputSource is = new InputSource(new StringReader(transformedXml)); + Document doc = builder.parse(is); + NodeList root = doc.getChildNodes(); + assertEquals("celldesigner:AntisenseRNA", root.item(0).getNodeName()); + + Pair<String, CellDesignerAntisenseRna> result2 = antisenseRnaParser.parseXmlElement(xmlString); + CellDesignerAntisenseRna antisenseRna2 = result2.getRight(); + assertEquals(result.getLeft(), result2.getLeft()); + assertEquals(antisenseRna.getName(), antisenseRna2.getName()); + assertEquals(antisenseRna.getNotes().trim(), antisenseRna2.getNotes().trim()); + + assertEquals(1, antisenseRna2.getRegions().size()); + CellDesignerModificationResidue region = antisenseRna.getRegions().get(0); + CellDesignerModificationResidue region2 = antisenseRna2.getRegions().get(0); + assertEquals(region.getIdModificationResidue(), region2.getIdModificationResidue()); + assertEquals(region.getName(), region2.getName()); + assertEquals(region.getSize(), region2.getSize(), 1e-6); + assertEquals(region.getPos(), region2.getPos(), 1e-6); + assertEquals(region.getModificationType(), region2.getModificationType()); } } diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/species/ComplexParserTest.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/species/ComplexParserTest.java index b4eac9820746375d87c182e0db155670a2c63a62..9385be4dfbc62733ce3f88df9492d6c5f47085d5 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/species/ComplexParserTest.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/species/ComplexParserTest.java @@ -1,352 +1,249 @@ package lcsb.mapviewer.converter.model.celldesigner.species; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; -import static org.mockito.Mockito.when; +import static org.junit.Assert.*; +import static org.mockito.Mockito.*; import java.util.ArrayList; import java.util.List; -import org.apache.logging.log4j.*; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.junit.*; import org.mockito.Mockito; -import lcsb.mapviewer.common.exception.InvalidArgumentException; -import lcsb.mapviewer.common.exception.InvalidXmlSchemaException; -import lcsb.mapviewer.common.exception.NotImplementedException; +import lcsb.mapviewer.common.exception.*; import lcsb.mapviewer.converter.model.celldesigner.CellDesignerElementCollection; import lcsb.mapviewer.converter.model.celldesigner.CellDesignerTestFunctions; import lcsb.mapviewer.converter.model.celldesigner.alias.ComplexAliasXmlParser; import lcsb.mapviewer.converter.model.celldesigner.structure.CellDesignerComplexSpecies; import lcsb.mapviewer.model.map.compartment.Compartment; -import lcsb.mapviewer.model.map.model.Model; -import lcsb.mapviewer.model.map.model.ModelData; -import lcsb.mapviewer.model.map.model.ModelFullIndexed; +import lcsb.mapviewer.model.map.model.*; import lcsb.mapviewer.model.map.species.Complex; public class ComplexParserTest extends CellDesignerTestFunctions { - Logger logger = LogManager.getLogger(ComplexParserTest.class); - - String testSpeciesId = "s3"; - String testAliasId = "sa3"; - String testCompartmentAliasId = "ca3"; - String testCompartmentId = "c3"; - String testCompartmentAliasId2 = "ca4"; - String testCompartmentId2 = "c4"; - - CellDesignerElementCollection elements; - - @Before - public void setUp() throws Exception { - elements = new CellDesignerElementCollection(); - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testComplexState() throws Exception { - try { - Model model = getModelForFile("testFiles/problematic/complex_with_state.xml"); - Complex complex = (Complex) model.getElementByElementId("csa1"); - assertEquals("test state", complex.getStructuralState()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testParseInvalidInputNode() throws Exception { - try { - Model model = new ModelFullIndexed(null); - ComplexAliasXmlParser parser = new ComplexAliasXmlParser(elements, model); - - parser.parseXmlAlias(readFile("testFiles/invalid/invalid_complex_alias.xml")); - fail("Exceptione expected"); - - } catch (InvalidXmlSchemaException e) { - assertTrue(e.getMessage().contains("No species")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testParseInvalidInputNode2() throws Exception { - try { - Model model = new ModelFullIndexed(null); - CellDesignerComplexSpecies element = new CellDesignerComplexSpecies(); - element.setElementId("s3"); - elements.addElement(element); - ComplexAliasXmlParser parser = new ComplexAliasXmlParser(elements, model); - - parser.parseXmlAlias(readFile("testFiles/invalid/invalid_complex_alias2.xml")); - fail("Exceptione expected"); - - } catch (InvalidXmlSchemaException e) { - assertTrue(e.getMessage().contains("celldesigner:bla")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testParseInvalidInputNode3() throws Exception { - try { - Model model = new ModelFullIndexed(null); - CellDesignerComplexSpecies element = new CellDesignerComplexSpecies(); - element.setElementId("s3"); - elements.addElement(element); - ComplexAliasXmlParser parser = new ComplexAliasXmlParser(elements, model); - - parser.parseXmlAlias(readFile("testFiles/invalid/invalid_complex_alias3.xml")); - fail("Exceptione expected"); - - } catch (InvalidXmlSchemaException e) { - assertTrue(e.getMessage().contains("unusual")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testParseInvalidInputNode4() throws Exception { - try { - Model model = new ModelFullIndexed(null); - CellDesignerComplexSpecies element = new CellDesignerComplexSpecies(); - element.setElementId("s3"); - elements.addElement(element); - ComplexAliasXmlParser parser = new ComplexAliasXmlParser(elements, model); - - parser.parseXmlAlias(readFile("testFiles/invalid/invalid_complex_alias4.xml")); - fail("Exceptione expected"); - - } catch (NotImplementedException e) { - assertTrue(e.getMessage().contains("unkown state")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testParseInvalidInputNode5() throws Exception { - try { - Model model = new ModelFullIndexed(null); - CellDesignerComplexSpecies element = new CellDesignerComplexSpecies(); - element.setElementId("s3"); - elements.addElement(element); - ComplexAliasXmlParser parser = new ComplexAliasXmlParser(elements, model); - - parser.parseXmlAlias(readFile("testFiles/invalid/invalid_complex_alias5.xml")); - fail("Exceptione expected"); - - } catch (InvalidXmlSchemaException e) { - assertTrue(e.getMessage().contains("CompartmentAlias does not exist")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testToXmlWithParent() throws Exception { - try { - Model model = new ModelFullIndexed(null); - - Compartment compartment = new Compartment(testCompartmentAliasId); - - Complex alias = new Complex(testAliasId); - - alias.setCompartment(compartment); - - model.addElement(alias); - ComplexAliasXmlParser parser = new ComplexAliasXmlParser(elements, model); - - String xml = parser.toXml(alias); - - assertTrue(xml.contains(testAliasId)); - assertTrue(xml.contains(testCompartmentAliasId)); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testToXmlWithCompartment() throws Exception { - try { - Model model = new ModelFullIndexed(null); - - Compartment ca = new Compartment(testCompartmentAliasId); - - Complex alias = new Complex(testAliasId); - - alias.setCompartment(ca); - - model.addElement(alias); - ComplexAliasXmlParser parser = new ComplexAliasXmlParser(elements, model); - - String xml = parser.toXml(alias); - - assertTrue(xml.contains(testAliasId)); - assertTrue(xml.contains(testCompartmentAliasId)); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testToXmlWithUnknownCompartment() throws Exception { - try { - Model model = Mockito.mock(ModelFullIndexed.class); - ModelData md = new ModelData(); - md.setModel(model); + Logger logger = LogManager.getLogger(ComplexParserTest.class); + + String testSpeciesId = "s3"; + String testAliasId = "sa3"; + String testCompartmentAliasId = "ca3"; + String testCompartmentId = "c3"; + String testCompartmentAliasId2 = "ca4"; + String testCompartmentId2 = "c4"; - Compartment ca2 = new Compartment(testCompartmentAliasId2); - ca2.setX(6); - ca2.setY(6); - ca2.setWidth(190); - ca2.setHeight(190); + CellDesignerElementCollection elements; - Compartment ca = new Compartment(testCompartmentAliasId); - ca.setX(5); - ca.setY(5); - ca.setWidth(200); - ca.setHeight(200); + @Before + public void setUp() throws Exception { + elements = new CellDesignerElementCollection(); + } - List<Compartment> list = new ArrayList<>(); - list.add(ca); - list.add(ca2); + @After + public void tearDown() throws Exception { + } - // ensure that we return list (firts bigger compartment, then smaller) - when(model.getCompartments()).thenReturn(list); - when(model.getModelData()).thenReturn(md); + @Test + public void testComplexState() throws Exception { + Model model = getModelForFile("testFiles/problematic/complex_with_state.xml"); + Complex complex = (Complex) model.getElementByElementId("csa1"); + assertEquals("test state", complex.getStructuralState()); + } - Complex alias = new Complex(testAliasId); - alias.setX(10); - alias.setY(10); - alias.setWidth(100); - alias.setHeight(100); - alias.setModel(model); + @Test(expected = InvalidXmlSchemaException.class) + public void testParseInvalidInputNode() throws Exception { + Model model = new ModelFullIndexed(null); + ComplexAliasXmlParser parser = new ComplexAliasXmlParser(elements, model); + + parser.parseXmlAlias(readFile("testFiles/invalid/invalid_complex_alias.xml")); + } - model.addElement(alias); - ComplexAliasXmlParser parser = new ComplexAliasXmlParser(elements, model); + @Test(expected = InvalidXmlSchemaException.class) + public void testParseInvalidInputNode2() throws Exception { + Model model = new ModelFullIndexed(null); + CellDesignerComplexSpecies element = new CellDesignerComplexSpecies(); + element.setElementId("s3"); + elements.addElement(element); + ComplexAliasXmlParser parser = new ComplexAliasXmlParser(elements, model); - String xml = parser.toXml(alias); + parser.parseXmlAlias(readFile("testFiles/invalid/invalid_complex_alias2.xml")); + } + + @Test(expected = InvalidXmlSchemaException.class) + public void testParseInvalidInputNode3() throws Exception { + Model model = new ModelFullIndexed(null); + CellDesignerComplexSpecies element = new CellDesignerComplexSpecies(); + element.setElementId("s3"); + elements.addElement(element); + ComplexAliasXmlParser parser = new ComplexAliasXmlParser(elements, model); + + parser.parseXmlAlias(readFile("testFiles/invalid/invalid_complex_alias3.xml")); + } + + @Test(expected = NotImplementedException.class) + public void testParseInvalidInputNode4() throws Exception { + Model model = new ModelFullIndexed(null); + CellDesignerComplexSpecies element = new CellDesignerComplexSpecies(); + element.setElementId("s3"); + elements.addElement(element); + ComplexAliasXmlParser parser = new ComplexAliasXmlParser(elements, model); - assertTrue(xml.contains(testAliasId)); - assertTrue(xml.contains(testCompartmentAliasId2)); + parser.parseXmlAlias(readFile("testFiles/invalid/invalid_complex_alias4.xml")); + } - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } + @Test(expected = InvalidXmlSchemaException.class) + public void testParseInvalidInputNode5() throws Exception { + Model model = new ModelFullIndexed(null); + CellDesignerComplexSpecies element = new CellDesignerComplexSpecies(); + element.setElementId("s3"); + elements.addElement(element); + ComplexAliasXmlParser parser = new ComplexAliasXmlParser(elements, model); - @Test - public void testToXmlWithComplexParent() throws Exception { - try { - Model model = new ModelFullIndexed(null); + parser.parseXmlAlias(readFile("testFiles/invalid/invalid_complex_alias5.xml")); + } - Complex complex = new Complex(testCompartmentAliasId); + @Test + public void testToXmlWithParent() throws Exception { + Model model = new ModelFullIndexed(null); - Complex alias = new Complex(testAliasId); + Compartment compartment = new Compartment(testCompartmentAliasId); - alias.setComplex(complex); + Complex alias = new Complex(testAliasId); - model.addElement(alias); - ComplexAliasXmlParser parser = new ComplexAliasXmlParser(elements, model); + alias.setCompartment(compartment); - String xml = parser.toXml(alias); + model.addElement(alias); + ComplexAliasXmlParser parser = new ComplexAliasXmlParser(elements, model); - assertTrue(xml.contains(testAliasId)); - assertTrue(xml.contains(testCompartmentAliasId)); + String xml = parser.toXml(alias); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } + assertTrue(xml.contains(testAliasId)); + assertTrue(xml.contains(testCompartmentAliasId)); + } - @Test - public void testToXmlWithActiveComplex() throws Exception { - try { - Model model = new ModelFullIndexed(null); + @Test + public void testToXmlWithCompartment() throws Exception { + Model model = new ModelFullIndexed(null); - Complex alias = new Complex(testAliasId); + Compartment ca = new Compartment(testCompartmentAliasId); - alias.setActivity(true); + Complex alias = new Complex(testAliasId); - model.addElement(alias); - ComplexAliasXmlParser parser = new ComplexAliasXmlParser(elements, model); + alias.setCompartment(ca); - String xml = parser.toXml(alias); + model.addElement(alias); + ComplexAliasXmlParser parser = new ComplexAliasXmlParser(elements, model); - assertTrue(xml.contains(testAliasId)); - assertTrue(xml.contains("<celldesigner:activity>active</celldesigner:activity>")); + String xml = parser.toXml(alias); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testAddInvalidReference() throws Exception { - try { - Model model = new ModelFullIndexed(null); - CellDesignerComplexSpecies element = new CellDesignerComplexSpecies(); - element.setElementId("s2"); - elements.addElement(element); + assertTrue(xml.contains(testAliasId)); + assertTrue(xml.contains(testCompartmentAliasId)); + } - ComplexAliasXmlParser parser = new ComplexAliasXmlParser(elements, model); + @Test + public void testToXmlWithUnknownCompartment() throws Exception { + Model model = Mockito.mock(ModelFullIndexed.class); + ModelData md = new ModelData(); + md.setModel(model); - Complex child = parser.parseXmlAlias(readFile("testFiles/xmlNodeTestExamples/cd_complex_alias_with_parent.xml")); + Compartment ca2 = new Compartment(testCompartmentAliasId2); + ca2.setX(6); + ca2.setY(6); + ca2.setWidth(190); + ca2.setHeight(190); - parser.addReference(child); - fail("Exception expected"); + Compartment ca = new Compartment(testCompartmentAliasId); + ca.setX(5); + ca.setY(5); + ca.setWidth(200); + ca.setHeight(200); - } catch (InvalidArgumentException e) { - assertTrue(e.getMessage().contains("Parent complex alias does not exist")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } + List<Compartment> list = new ArrayList<>(); + list.add(ca); + list.add(ca2); - @Test - public void testParseWithEmptyState() throws Exception { - try { - Model model = new ModelFullIndexed(null); - CellDesignerComplexSpecies element = new CellDesignerComplexSpecies("s2597"); - elements.addElement(element); + // ensure that we return list (firts bigger compartment, then smaller) + when(model.getCompartments()).thenReturn(list); + when(model.getModelData()).thenReturn(md); - ComplexAliasXmlParser parser = new ComplexAliasXmlParser(elements, model); + Complex alias = new Complex(testAliasId); + alias.setX(10); + alias.setY(10); + alias.setWidth(100); + alias.setHeight(100); + alias.setModel(model); - Complex child = parser.parseXmlAlias(readFile("testFiles/xmlNodeTestExamples/cd_complex_alias_with_empty_state.xml")); + model.addElement(alias); + ComplexAliasXmlParser parser = new ComplexAliasXmlParser(elements, model); - assertNotNull(child); - assertNull(child.getStateLabel()); - assertNull(child.getStatePrefix()); + String xml = parser.toXml(alias); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } + assertTrue(xml.contains(testAliasId)); + assertTrue(xml.contains(testCompartmentAliasId2)); + } + + @Test + public void testToXmlWithComplexParent() throws Exception { + Model model = new ModelFullIndexed(null); + + Complex complex = new Complex(testCompartmentAliasId); + + Complex alias = new Complex(testAliasId); + + alias.setComplex(complex); + + model.addElement(alias); + ComplexAliasXmlParser parser = new ComplexAliasXmlParser(elements, model); + + String xml = parser.toXml(alias); + + assertTrue(xml.contains(testAliasId)); + assertTrue(xml.contains(testCompartmentAliasId)); + } + + @Test + public void testToXmlWithActiveComplex() throws Exception { + Model model = new ModelFullIndexed(null); + + Complex alias = new Complex(testAliasId); + + alias.setActivity(true); + + model.addElement(alias); + ComplexAliasXmlParser parser = new ComplexAliasXmlParser(elements, model); + + String xml = parser.toXml(alias); + + assertTrue(xml.contains(testAliasId)); + assertTrue(xml.contains("<celldesigner:activity>active</celldesigner:activity>")); + } + + @Test(expected = InvalidArgumentException.class) + public void testAddInvalidReference() throws Exception { + Model model = new ModelFullIndexed(null); + CellDesignerComplexSpecies element = new CellDesignerComplexSpecies(); + element.setElementId("s2"); + elements.addElement(element); + + ComplexAliasXmlParser parser = new ComplexAliasXmlParser(elements, model); + + Complex child = parser.parseXmlAlias(readFile("testFiles/xmlNodeTestExamples/cd_complex_alias_with_parent.xml")); + + parser.addReference(child); + } + + @Test + public void testParseWithEmptyState() throws Exception { + Model model = new ModelFullIndexed(null); + CellDesignerComplexSpecies element = new CellDesignerComplexSpecies("s2597"); + elements.addElement(element); + + ComplexAliasXmlParser parser = new ComplexAliasXmlParser(elements, model); + + Complex child = parser + .parseXmlAlias(readFile("testFiles/xmlNodeTestExamples/cd_complex_alias_with_empty_state.xml")); + + assertNotNull(child); + assertNull(child.getStateLabel()); + assertNull(child.getStatePrefix()); + } } diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/species/GeneXmlParserTest.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/species/GeneXmlParserTest.java index 1e0aa4171707c207a8d3d28189b4c92595c582dc..7f4a3c4fa8cc2b70b52da7ca882547d07f37d063 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/species/GeneXmlParserTest.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/species/GeneXmlParserTest.java @@ -1,19 +1,15 @@ package lcsb.mapviewer.converter.model.celldesigner.species; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import java.io.StringReader; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; -import org.apache.logging.log4j.*; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.junit.*; import org.w3c.dom.Document; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; @@ -47,100 +43,64 @@ public class GeneXmlParserTest extends CellDesignerTestFunctions { } @Test - public void testParseXmlSpecies() { - try { - String xmlString = readFile(testGeneFile); - Pair<String, CellDesignerGene> result = geneParser.parseXmlElement(xmlString); - CellDesignerGene gene = result.getRight(); - assertEquals("gn3", result.getLeft()); - assertEquals("BCL6", gene.getName()); - assertTrue(gene.getNotes().contains("B-cell CLL/lymphoma 6")); - } catch (Exception e) { - e.printStackTrace(); - fail("Unexpected exception occured"); - } + public void testParseXmlSpecies() throws Exception { + String xmlString = readFile(testGeneFile); + Pair<String, CellDesignerGene> result = geneParser.parseXmlElement(xmlString); + CellDesignerGene gene = result.getRight(); + assertEquals("gn3", result.getLeft()); + assertEquals("BCL6", gene.getName()); + assertTrue(gene.getNotes().contains("B-cell CLL/lymphoma 6")); } @Test public void testToXml() throws Exception { - try { - String xmlString = readFile(testGeneFile); - Pair<String, CellDesignerGene> result = geneParser.parseXmlElement(xmlString); - CellDesignerGene gene = result.getRight(); - String transformedXml = geneParser.toXml(gene.createModelElement()); - DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); - DocumentBuilder builder = factory.newDocumentBuilder(); - InputSource is = new InputSource(new StringReader(transformedXml)); - Document doc = builder.parse(is); - NodeList root = doc.getChildNodes(); - assertEquals("celldesigner:gene", root.item(0).getNodeName()); - - Pair<String, CellDesignerGene> result2 = geneParser.parseXmlElement(geneParser.toXml(gene.createModelElement())); - CellDesignerGene gene2 = result2.getRight(); - assertEquals(gene.getName(), gene2.getName()); - assertTrue(gene2.getNotes().trim().contains(gene.getNotes().trim())); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String xmlString = readFile(testGeneFile); + Pair<String, CellDesignerGene> result = geneParser.parseXmlElement(xmlString); + CellDesignerGene gene = result.getRight(); + String transformedXml = geneParser.toXml(gene.createModelElement()); + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + DocumentBuilder builder = factory.newDocumentBuilder(); + InputSource is = new InputSource(new StringReader(transformedXml)); + Document doc = builder.parse(is); + NodeList root = doc.getChildNodes(); + assertEquals("celldesigner:gene", root.item(0).getNodeName()); + + Pair<String, CellDesignerGene> result2 = geneParser.parseXmlElement(geneParser.toXml(gene.createModelElement())); + CellDesignerGene gene2 = result2.getRight(); + assertEquals(gene.getName(), gene2.getName()); + assertTrue(gene2.getNotes().trim().contains(gene.getNotes().trim())); } @Test public void testParsePhosphorylatedGene() throws Exception { - try { - Model model = getModelForFile("testFiles/problematic/phosphorylated_gene.xml"); - Gene gene = model.getElementByElementId("sa1"); - assertEquals(1, gene.getModificationResidues().size()); - ModificationSite residue = (ModificationSite) gene.getModificationResidues().get(0); - assertEquals(ModificationState.PHOSPHORYLATED, residue.getState()); - assertEquals("some name", residue.getName()); - - // check xml transformation - String xml = geneParser.toXml(gene); - assertNotNull(xml); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Model model = getModelForFile("testFiles/problematic/phosphorylated_gene.xml"); + Gene gene = model.getElementByElementId("sa1"); + assertEquals(1, gene.getModificationResidues().size()); + ModificationSite residue = (ModificationSite) gene.getModificationResidues().get(0); + assertEquals(ModificationState.PHOSPHORYLATED, residue.getState()); + assertEquals("some name", residue.getName()); + + // check xml transformation + String xml = geneParser.toXml(gene); + assertNotNull(xml); } - @Test + @Test(expected = InvalidXmlSchemaException.class) public void testParseInvalidGeneInput() throws Exception { - try { - String xmlString = readFile("testFiles/invalid/invalid_gene_1.xml"); - geneParser.parseXmlElement(xmlString); - fail("Exception expected"); - } catch (InvalidXmlSchemaException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String xmlString = readFile("testFiles/invalid/invalid_gene_1.xml"); + geneParser.parseXmlElement(xmlString); } - @Test + @Test(expected = InvalidXmlSchemaException.class) public void testParseInvalidGeneInput2() throws Exception { - try { - String xmlString = readFile("testFiles/invalid/invalid_gene_2.xml"); - geneParser.parseXmlElement(xmlString); - fail("Exception expected"); - } catch (InvalidXmlSchemaException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String xmlString = readFile("testFiles/invalid/invalid_gene_2.xml"); + geneParser.parseXmlElement(xmlString); } - @Test + @Test(expected = InvalidXmlSchemaException.class) public void testParseInvalidModificationResidue() throws Exception { - try { - String xmlString = readFile("testFiles/invalid/invalid_modification_residue.xml"); - geneParser.getModificationResidue(getNodeFromXmlString(xmlString)); - fail("Exception expected"); - } catch (InvalidXmlSchemaException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String xmlString = readFile("testFiles/invalid/invalid_modification_residue.xml"); + geneParser.getModificationResidue(getNodeFromXmlString(xmlString)); } } diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/species/InternalModelSpeciesDataTest.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/species/InternalModelSpeciesDataTest.java index 495605edbc0353af321f2e00045a719162ddf132..0de7742276128c9743e81fa7a835cbdae575ba7f 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/species/InternalModelSpeciesDataTest.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/species/InternalModelSpeciesDataTest.java @@ -1,51 +1,42 @@ package lcsb.mapviewer.converter.model.celldesigner.species; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import lcsb.mapviewer.common.exception.InvalidArgumentException; +import lcsb.mapviewer.converter.model.celldesigner.CellDesignerTestFunctions; import lcsb.mapviewer.converter.model.celldesigner.structure.CellDesignerSpecies; import lcsb.mapviewer.model.map.species.GenericProtein; -public class InternalModelSpeciesDataTest { - - @AfterClass - public static void tearDownAfterClass() throws Exception { - } - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testGetters() { - InternalModelSpeciesData data = new InternalModelSpeciesData(); - assertNotNull(data.getAll()); - assertNotNull(data.getAntisenseRnas()); - assertNotNull(data.getGenes()); - assertNotNull(data.getProteins()); - assertNotNull(data.getRnas()); - } - - @Test - public void testUpdateUnknownSpecies() { - InternalModelSpeciesData data = new InternalModelSpeciesData(); - try { - data.updateSpecies(new CellDesignerSpecies<GenericProtein>(), null); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - assertTrue(e.getMessage().contains("Unknown species type")); - } - } +public class InternalModelSpeciesDataTest extends CellDesignerTestFunctions { + + @AfterClass + public static void tearDownAfterClass() throws Exception { + } + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testGetters() { + InternalModelSpeciesData data = new InternalModelSpeciesData(); + assertNotNull(data.getAll()); + assertNotNull(data.getAntisenseRnas()); + assertNotNull(data.getGenes()); + assertNotNull(data.getProteins()); + assertNotNull(data.getRnas()); + } + + @Test(expected = InvalidArgumentException.class) + public void testUpdateUnknownSpecies() { + InternalModelSpeciesData data = new InternalModelSpeciesData(); + data.updateSpecies(new CellDesignerSpecies<GenericProtein>(), null); + } } diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/species/ModificationResidueXmlParserTest.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/species/ModificationResidueXmlParserTest.java index c8450837b0a10d60aabdb92356d29d38c3c87bd6..a3b2f730fff63f9201261de05b3a312f1f953957 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/species/ModificationResidueXmlParserTest.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/species/ModificationResidueXmlParserTest.java @@ -1,6 +1,6 @@ package lcsb.mapviewer.converter.model.celldesigner.species; -import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.*; import java.awt.geom.Point2D; @@ -8,10 +8,11 @@ import org.junit.Before; import org.junit.Test; import lcsb.mapviewer.converter.model.celldesigner.CellDesignerElementCollection; +import lcsb.mapviewer.converter.model.celldesigner.CellDesignerTestFunctions; import lcsb.mapviewer.model.map.species.Gene; import lcsb.mapviewer.model.map.species.field.ModificationSite; -public class ModificationResidueXmlParserTest { +public class ModificationResidueXmlParserTest extends CellDesignerTestFunctions { ModificationResidueXmlParser parser; @@ -22,23 +23,18 @@ public class ModificationResidueXmlParserTest { @Test public void testGeneModificationResidueToXml() throws Exception { - try { - Gene protein = new Gene("id"); - protein.setX(10); - protein.setY(10); - protein.setWidth(10); - protein.setHeight(10); - ModificationSite mr = new ModificationSite(); - mr.setIdModificationResidue("i"); - mr.setName("a"); - mr.setPosition(new Point2D.Double(3.0, 2.0)); - mr.setSpecies(protein); - String xmlString = parser.toXml(mr); - assertNotNull(xmlString); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Gene protein = new Gene("id"); + protein.setX(10); + protein.setY(10); + protein.setWidth(10); + protein.setHeight(10); + ModificationSite mr = new ModificationSite(); + mr.setIdModificationResidue("i"); + mr.setName("a"); + mr.setPosition(new Point2D.Double(3.0, 2.0)); + mr.setSpecies(protein); + String xmlString = parser.toXml(mr); + assertNotNull(xmlString); } } diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/species/ProteinMappingTest.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/species/ProteinMappingTest.java index 6951d37c7c5d97a38fd435d02bf8de7b9d61824f..2a6eba764b229b793206eaec64c78bcc1d8bd57b 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/species/ProteinMappingTest.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/species/ProteinMappingTest.java @@ -1,81 +1,74 @@ package lcsb.mapviewer.converter.model.celldesigner.species; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import java.lang.reflect.Field; -import org.apache.logging.log4j.*; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.Test; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.junit.*; import lcsb.mapviewer.common.exception.InvalidStateException; import lcsb.mapviewer.common.exception.NotImplementedException; +import lcsb.mapviewer.converter.model.celldesigner.CellDesignerTestFunctions; import lcsb.mapviewer.converter.model.celldesigner.structure.CellDesignerProtein; import lcsb.mapviewer.model.map.species.TruncatedProtein; -public class ProteinMappingTest { - Logger logger = LogManager.getLogger(ProteinMappingTest.class); - - @AfterClass - public static void tearDownAfterClass() throws Exception { - } - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testAllValues() { - for (ProteinMapping value : ProteinMapping.values()) { - assertNotNull(ProteinMapping.valueOf(value.toString())); - } - } - - @Test - public void testCreateInvalidProteinImpl() throws Exception { - // artificial implementation of Protein that is invalid - class InvalidProtein extends CellDesignerProtein<TruncatedProtein> { - private static final long serialVersionUID = 1L; - - @SuppressWarnings("unused") - public InvalidProtein() { - throw new NotImplementedException(); - } - } - - // mopdify one of the elements of ProteinMapping so it will have invalid - // implementation - ProteinMapping typeToModify = ProteinMapping.GENERIC_PROTEIN; - Class<? extends CellDesignerProtein<?>> clazz = typeToModify.getCellDesignerClazz(); - - try { - Field field = typeToModify.getClass().getDeclaredField("cellDesignerClazz"); - field.setAccessible(true); - field.set(typeToModify, InvalidProtein.class); - - // and check if we catch properly information about problematic - // implementation - typeToModify.createProtein(); - fail("Exception expected"); - } catch (InvalidStateException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } finally { - // restore correct values for the modified type (if not then other test - // might fail...) - Field field = typeToModify.getClass().getDeclaredField("cellDesignerClazz"); - field.setAccessible(true); - field.set(typeToModify, clazz); - } - - } +public class ProteinMappingTest extends CellDesignerTestFunctions { + Logger logger = LogManager.getLogger(ProteinMappingTest.class); + + @AfterClass + public static void tearDownAfterClass() throws Exception { + } + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testAllValues() { + for (ProteinMapping value : ProteinMapping.values()) { + assertNotNull(ProteinMapping.valueOf(value.toString())); + } + } + + @Test(expected = InvalidStateException.class) + public void testCreateInvalidProteinImpl() throws Exception { + // artificial implementation of Protein that is invalid + class InvalidProtein extends CellDesignerProtein<TruncatedProtein> { + private static final long serialVersionUID = 1L; + + @SuppressWarnings("unused") + public InvalidProtein() { + throw new NotImplementedException(); + } + } + + // mopdify one of the elements of ProteinMapping so it will have invalid + // implementation + ProteinMapping typeToModify = ProteinMapping.GENERIC_PROTEIN; + Class<? extends CellDesignerProtein<?>> clazz = typeToModify.getCellDesignerClazz(); + + try { + Field field = typeToModify.getClass().getDeclaredField("cellDesignerClazz"); + field.setAccessible(true); + field.set(typeToModify, InvalidProtein.class); + + // and check if we catch properly information about problematic + // implementation + typeToModify.createProtein(); + } finally { + // restore correct values for the modified type (if not then other test + // might fail...) + Field field = typeToModify.getClass().getDeclaredField("cellDesignerClazz"); + field.setAccessible(true); + field.set(typeToModify, clazz); + } + + } } diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/species/ProteinXmlParserTest.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/species/ProteinXmlParserTest.java index 49c7adde8aad97248037f49a20a734d6c97a9ce7..b85fd90d02864dbaf8a7a90600e5ac03e2e6a1dd 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/species/ProteinXmlParserTest.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/species/ProteinXmlParserTest.java @@ -1,18 +1,15 @@ package lcsb.mapviewer.converter.model.celldesigner.species; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import java.io.StringReader; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; -import org.apache.logging.log4j.*; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.junit.*; import org.mockito.Mockito; import org.w3c.dom.Document; import org.w3c.dom.NodeList; @@ -47,136 +44,82 @@ public class ProteinXmlParserTest extends CellDesignerTestFunctions { @Test public void testParseXmlSpecies() throws Exception { - try { - String xmlString = readFile(testProteinFile); - Pair<String, CellDesignerProtein<?>> result = proteinParser.parseXmlElement(xmlString); - CellDesignerProtein<?> protein = result.getRight(); - assertEquals("pr23", result.getLeft()); - assertEquals("SDHA", protein.getName()); - assertTrue(protein instanceof CellDesignerGenericProtein); - assertEquals(1, protein.getModificationResidues().size()); - assertEquals("rs1", protein.getModificationResidues().get(0).getIdModificationResidue()); - assertEquals("S176 bla bla", protein.getModificationResidues().get(0).getName()); - assertEquals("Difference to big", 3.141592653589793, protein.getModificationResidues().get(0).getAngle(), 1e-6); - assertEquals("none", protein.getModificationResidues().get(0).getSide()); - assertTrue(protein.getNotes().contains("UniProtKB P31040 SDHA GO:0005749 GO_REF:0000024")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String xmlString = readFile(testProteinFile); + Pair<String, CellDesignerProtein<?>> result = proteinParser.parseXmlElement(xmlString); + CellDesignerProtein<?> protein = result.getRight(); + assertEquals("pr23", result.getLeft()); + assertEquals("SDHA", protein.getName()); + assertTrue(protein instanceof CellDesignerGenericProtein); + assertEquals(1, protein.getModificationResidues().size()); + assertEquals("rs1", protein.getModificationResidues().get(0).getIdModificationResidue()); + assertEquals("S176 bla bla", protein.getModificationResidues().get(0).getName()); + assertEquals("Difference to big", 3.141592653589793, protein.getModificationResidues().get(0).getAngle(), 1e-6); + assertEquals("none", protein.getModificationResidues().get(0).getSide()); + assertTrue(protein.getNotes().contains("UniProtKB P31040 SDHA GO:0005749 GO_REF:0000024")); } @Test public void testToXml() throws Exception { - try { - String xmlString = readFile(testProteinFile); - - Pair<String, CellDesignerProtein<?>> result = proteinParser.parseXmlElement(xmlString); - CellDesignerProtein<?> protein = result.getRight(); - String transformedXml = proteinParser.toXml(protein.createModelElement("id")); - DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); - DocumentBuilder builder = factory.newDocumentBuilder(); - InputSource is = new InputSource(new StringReader(transformedXml)); - Document doc = builder.parse(is); - NodeList root = doc.getChildNodes(); - assertEquals("celldesigner:protein", root.item(0).getNodeName()); - - elements = new CellDesignerElementCollection(); - proteinParser = new ProteinXmlParser(elements); - Protein proteinWithLayout = protein.createModelElement("id"); - proteinWithLayout.setWidth(10); - proteinWithLayout.setHeight(10); - protein.updateModelElementAfterLayoutAdded(proteinWithLayout); - Pair<String, CellDesignerProtein<?>> result2 = proteinParser - .parseXmlElement(proteinParser.toXml(proteinWithLayout)); - - CellDesignerProtein<?> protein2 = result2.getRight(); - assertEquals(protein.getName(), protein2.getName()); - assertEquals(protein.getClass(), protein2.getClass()); - assertEquals(protein.getModificationResidues().size(), protein2.getModificationResidues().size()); - assertEquals(protein.getModificationResidues().get(0).getIdModificationResidue(), - protein2.getModificationResidues().get(0).getIdModificationResidue()); - assertEquals(protein.getModificationResidues().get(0).getName(), - protein2.getModificationResidues().get(0).getName()); - assertEquals("Difference to big", protein.getModificationResidues().get(0).getAngle(), - protein2.getModificationResidues().get(0).getAngle(), 1e-6); - - // proteins won't have notes because it makes the xml messy (everything - // will be in species notes) - // assertEquals(protein.getNotes().trim(), protein2.getNotes().trim()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String xmlString = readFile(testProteinFile); + + Pair<String, CellDesignerProtein<?>> result = proteinParser.parseXmlElement(xmlString); + CellDesignerProtein<?> protein = result.getRight(); + String transformedXml = proteinParser.toXml(protein.createModelElement("id")); + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + DocumentBuilder builder = factory.newDocumentBuilder(); + InputSource is = new InputSource(new StringReader(transformedXml)); + Document doc = builder.parse(is); + NodeList root = doc.getChildNodes(); + assertEquals("celldesigner:protein", root.item(0).getNodeName()); + + elements = new CellDesignerElementCollection(); + proteinParser = new ProteinXmlParser(elements); + Protein proteinWithLayout = protein.createModelElement("id"); + proteinWithLayout.setWidth(10); + proteinWithLayout.setHeight(10); + protein.updateModelElementAfterLayoutAdded(proteinWithLayout); + Pair<String, CellDesignerProtein<?>> result2 = proteinParser + .parseXmlElement(proteinParser.toXml(proteinWithLayout)); + + CellDesignerProtein<?> protein2 = result2.getRight(); + assertEquals(protein.getName(), protein2.getName()); + assertEquals(protein.getClass(), protein2.getClass()); + assertEquals(protein.getModificationResidues().size(), protein2.getModificationResidues().size()); + assertEquals(protein.getModificationResidues().get(0).getIdModificationResidue(), + protein2.getModificationResidues().get(0).getIdModificationResidue()); + assertEquals(protein.getModificationResidues().get(0).getName(), + protein2.getModificationResidues().get(0).getName()); + assertEquals("Difference to big", protein.getModificationResidues().get(0).getAngle(), + protein2.getModificationResidues().get(0).getAngle(), 1e-6); } - @Test + @Test(expected = InvalidXmlSchemaException.class) public void testParseInvalidXml() throws Exception { - try { - String xmlString = readFile("testFiles/invalid/protein.xml"); - proteinParser.parseXmlElement(xmlString); - fail("Exception expected"); - } catch (InvalidXmlSchemaException e) { - assertTrue(e.getMessage().contains("Protein node in Sbml model is of unknown type")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String xmlString = readFile("testFiles/invalid/protein.xml"); + proteinParser.parseXmlElement(xmlString); } - @Test + @Test(expected = InvalidXmlSchemaException.class) public void testParseInvalidXml2() throws Exception { - try { - String xmlString = readFile("testFiles/invalid/protein2.xml"); - proteinParser.parseXmlElement(xmlString); - fail("Exception expected"); - } catch (InvalidXmlSchemaException e) { - assertTrue(e.getMessage().contains("Unknown element of celldesigner:listOfModificationResidues")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String xmlString = readFile("testFiles/invalid/protein2.xml"); + proteinParser.parseXmlElement(xmlString); } - @Test + @Test(expected = InvalidXmlSchemaException.class) public void testParseInvalidXml3() throws Exception { - try { - String xmlString = readFile("testFiles/invalid/protein3.xml"); - proteinParser.parseXmlElement(xmlString); - fail("Exception expected"); - } catch (InvalidXmlSchemaException e) { - assertTrue(e.getMessage().contains("Unknown element of celldesigner:protein")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String xmlString = readFile("testFiles/invalid/protein3.xml"); + proteinParser.parseXmlElement(xmlString); } - @Test + @Test(expected = InvalidXmlSchemaException.class) public void testParseInvalidXml4() throws Exception { - try { - String xmlString = readFile("testFiles/invalid/protein4.xml"); - proteinParser.parseXmlElement(xmlString); - fail("Exception expected"); - } catch (InvalidXmlSchemaException e) { - assertTrue(e.getMessage().contains("Unknown element of celldesigner:modificationResidue")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String xmlString = readFile("testFiles/invalid/protein4.xml"); + proteinParser.parseXmlElement(xmlString); } - @Test + @Test(expected = InvalidArgumentException.class) public void testInvalidProteinToXml() throws Exception { - try { - proteinParser.toXml(Mockito.mock(Protein.class)); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - assertTrue(e.getMessage().contains("Invalid protein class type")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + proteinParser.toXml(Mockito.mock(Protein.class)); } } diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/species/RnaXmlParserTest.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/species/RnaXmlParserTest.java index be62befe513bec6d90ce1be0e91b65c2685ab393..25932ad1eb2af61194b98e74eb8ff8a844898185 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/species/RnaXmlParserTest.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/species/RnaXmlParserTest.java @@ -1,19 +1,15 @@ package lcsb.mapviewer.converter.model.celldesigner.species; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import java.io.StringReader; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; -import org.apache.logging.log4j.*; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.junit.*; import org.w3c.dom.Document; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; @@ -45,100 +41,61 @@ public class RnaXmlParserTest extends CellDesignerTestFunctions { @Test public void testParseXmlSpecies() throws Exception { - try { - String xmlString = readFile(testRnaFile); - Pair<String, CellDesignerRna> result = rnaParser.parseXmlElement(xmlString); - CellDesignerRna rna = result.getRight(); - assertEquals("rn36", result.getLeft()); - assertEquals("BCL6", rna.getName()); - assertTrue(rna.getNotes().contains("B-cell CLL/lymphoma ")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String xmlString = readFile(testRnaFile); + Pair<String, CellDesignerRna> result = rnaParser.parseXmlElement(xmlString); + CellDesignerRna rna = result.getRight(); + assertEquals("rn36", result.getLeft()); + assertEquals("BCL6", rna.getName()); + assertTrue(rna.getNotes().contains("B-cell CLL/lymphoma ")); } @Test public void testParseXmlSpeciesWithRegion() throws Exception { - try { - String xmlString = readFile(testRnaFile2); - Pair<String, CellDesignerRna> result = rnaParser.parseXmlElement(xmlString); - CellDesignerRna rna = result.getRight(); - assertNotNull(rna); - assertNotNull(rna.getRegions()); - assertEquals(1, rna.getRegions().size()); - assertEquals("tr1", rna.getRegions().get(0).getIdModificationResidue()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String xmlString = readFile(testRnaFile2); + Pair<String, CellDesignerRna> result = rnaParser.parseXmlElement(xmlString); + CellDesignerRna rna = result.getRight(); + assertNotNull(rna); + assertNotNull(rna.getRegions()); + assertEquals(1, rna.getRegions().size()); + assertEquals("tr1", rna.getRegions().get(0).getIdModificationResidue()); } @Test public void testToXml() throws Exception { - try { - String xmlString = readFile(testRnaFile); - Pair<String, CellDesignerRna> result = rnaParser.parseXmlElement(xmlString); - CellDesignerRna rna = result.getRight(); - - String transformedXml = rnaParser.toXml(rna.createModelElement("id")); - DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); - DocumentBuilder builder = factory.newDocumentBuilder(); - InputSource is = new InputSource(new StringReader(transformedXml)); - Document doc = builder.parse(is); - NodeList root = doc.getChildNodes(); - assertEquals("celldesigner:RNA", root.item(0).getNodeName()); - - Pair<String, CellDesignerRna> result2 = rnaParser.parseXmlElement(rnaParser.toXml(rna.createModelElement("id"))); - CellDesignerRna rna2 = result2.getRight(); - assertEquals(rna.getName(), rna2.getName()); - assertTrue(rna2.getNotes().trim().contains(rna.getNotes().trim())); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String xmlString = readFile(testRnaFile); + Pair<String, CellDesignerRna> result = rnaParser.parseXmlElement(xmlString); + CellDesignerRna rna = result.getRight(); + + String transformedXml = rnaParser.toXml(rna.createModelElement("id")); + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + DocumentBuilder builder = factory.newDocumentBuilder(); + InputSource is = new InputSource(new StringReader(transformedXml)); + Document doc = builder.parse(is); + NodeList root = doc.getChildNodes(); + assertEquals("celldesigner:RNA", root.item(0).getNodeName()); + + Pair<String, CellDesignerRna> result2 = rnaParser.parseXmlElement(rnaParser.toXml(rna.createModelElement("id"))); + CellDesignerRna rna2 = result2.getRight(); + assertEquals(rna.getName(), rna2.getName()); + assertTrue(rna2.getNotes().trim().contains(rna.getNotes().trim())); } - @Test + @Test(expected = InvalidXmlSchemaException.class) public void testParseInvalidXmlSpecies() throws Exception { - try { - String xmlString = readFile("testFiles/invalid/rna.xml"); - rnaParser.parseXmlElement(xmlString); - fail("Exception expected"); - } catch (InvalidXmlSchemaException e) { - assertTrue(e.getMessage().contains("Unknown element of celldesigner:listOfRegions")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String xmlString = readFile("testFiles/invalid/rna.xml"); + rnaParser.parseXmlElement(xmlString); } - @Test + @Test(expected = InvalidXmlSchemaException.class) public void testParseInvalidXmlSpecies2() throws Exception { - try { - String xmlString = readFile("testFiles/invalid/rna2.xml"); - rnaParser.parseXmlElement(xmlString); - fail("Exception expected"); - } catch (InvalidXmlSchemaException e) { - assertTrue(e.getMessage().contains("Unknown element of celldesigner:rna")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String xmlString = readFile("testFiles/invalid/rna2.xml"); + rnaParser.parseXmlElement(xmlString); } - @Test + @Test(expected = InvalidXmlSchemaException.class) public void testParseInvalidXmlSpecies3() throws Exception { - try { - String xmlString = readFile("testFiles/invalid/rna3.xml"); - rnaParser.parseXmlElement(xmlString); - fail("Exception expected"); - } catch (InvalidXmlSchemaException e) { - assertTrue(e.getMessage().contains("Unknown element of celldesigner:region")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String xmlString = readFile("testFiles/invalid/rna3.xml"); + rnaParser.parseXmlElement(xmlString); } } diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/species/SpeciesCollectionTest.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/species/SpeciesCollectionTest.java index f2d49cb9668894f63c365f95781666e7f9cca12d..ffe6b49c3c5ecf3e9604f28b75f6e16743b95297 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/species/SpeciesCollectionTest.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/species/SpeciesCollectionTest.java @@ -1,121 +1,90 @@ package lcsb.mapviewer.converter.model.celldesigner.species; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.Assert.*; -import org.apache.logging.log4j.*; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.junit.*; import lcsb.mapviewer.common.exception.InvalidStateException; import lcsb.mapviewer.common.exception.NotImplementedException; -import lcsb.mapviewer.converter.model.celldesigner.structure.CellDesignerGene; -import lcsb.mapviewer.converter.model.celldesigner.structure.CellDesignerGenericProtein; -import lcsb.mapviewer.converter.model.celldesigner.structure.CellDesignerProtein; -import lcsb.mapviewer.converter.model.celldesigner.structure.CellDesignerSpecies; +import lcsb.mapviewer.converter.model.celldesigner.CellDesignerTestFunctions; +import lcsb.mapviewer.converter.model.celldesigner.structure.*; import lcsb.mapviewer.model.map.species.Species; -public class SpeciesCollectionTest { - Logger logger = LogManager.getLogger(SpeciesCollectionTest.class); - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testAdd() { - try { - SpeciesCollection<CellDesignerGene> coll = new SpeciesCollection<CellDesignerGene>(); - CellDesignerGene g = new CellDesignerGene(); - g.setElementId("general Id"); - coll.add(g, "geneId"); - assertNotNull(coll.getSpeciesListByLocalId("geneId")); - assertEquals(1, coll.getSpeciesListByLocalId("geneId").size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testUpdate() { - try { - SpeciesCollection<CellDesignerProtein<?>> coll = new SpeciesCollection<>(); - CellDesignerProtein<?> protein = new CellDesignerGenericProtein(); - protein.setElementId(""); - coll.add(protein, "prot id"); - - CellDesignerProtein<?> p2 = new CellDesignerGenericProtein(); - p2.setElementId("id2"); - coll.updateSpeciesByLocalId(p2, "prot id"); - assertEquals(1, coll.getSpeciesListByLocalId("prot id").size()); - CellDesignerProtein<?> p3 = coll.getSpeciesListByLocalId("prot id").get(0); - - assertEquals(protein, p3); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testUpdateWithTypeChange() { - try { - SpeciesCollection<CellDesignerProtein<?>> coll = new SpeciesCollection<>(); - CellDesignerProtein<?> p = new CellDesignerProtein<>(); - p.setElementId(""); - coll.add(p, "prot id"); - - CellDesignerGenericProtein p2 = new CellDesignerGenericProtein(); - p2.setElementId("id2"); - coll.updateSpeciesByLocalId(p2, "prot id"); - assertEquals(1, coll.getSpeciesListByLocalId("prot id").size()); - CellDesignerProtein<?> p3 = coll.getSpeciesListByLocalId("prot id").get(0); - - // we don't have generic data anymore but new instance - assertFalse(p3.equals(p)); - assertFalse(p3.equals(p2)); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testCreateNewInstance() { - try { - SpeciesCollection<CellDesignerSpecies<?>> coll = new SpeciesCollection<>(); - class InvalidSpecies extends CellDesignerSpecies<Species> { - private static final long serialVersionUID = 1L; - - public InvalidSpecies() { - } - - @SuppressWarnings("unused") - public InvalidSpecies(final CellDesignerSpecies<?> sp) { - throw new NotImplementedException(); - } - } - - InvalidSpecies p = new InvalidSpecies(); - p.setElementId(""); - - coll.createNewInstance(p.getClass(), p); - - } catch (InvalidStateException e) { - assertTrue(e.getMessage().contains("Problem with creating object")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } +public class SpeciesCollectionTest extends CellDesignerTestFunctions { + Logger logger = LogManager.getLogger(SpeciesCollectionTest.class); + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testAdd() { + SpeciesCollection<CellDesignerGene> coll = new SpeciesCollection<CellDesignerGene>(); + CellDesignerGene g = new CellDesignerGene(); + g.setElementId("general Id"); + coll.add(g, "geneId"); + assertNotNull(coll.getSpeciesListByLocalId("geneId")); + assertEquals(1, coll.getSpeciesListByLocalId("geneId").size()); + } + + @Test + public void testUpdate() { + SpeciesCollection<CellDesignerProtein<?>> coll = new SpeciesCollection<>(); + CellDesignerProtein<?> protein = new CellDesignerGenericProtein(); + protein.setElementId(""); + coll.add(protein, "prot id"); + + CellDesignerProtein<?> p2 = new CellDesignerGenericProtein(); + p2.setElementId("id2"); + coll.updateSpeciesByLocalId(p2, "prot id"); + assertEquals(1, coll.getSpeciesListByLocalId("prot id").size()); + CellDesignerProtein<?> p3 = coll.getSpeciesListByLocalId("prot id").get(0); + + assertEquals(protein, p3); + } + + @Test + public void testUpdateWithTypeChange() { + SpeciesCollection<CellDesignerProtein<?>> coll = new SpeciesCollection<>(); + CellDesignerProtein<?> p = new CellDesignerProtein<>(); + p.setElementId(""); + coll.add(p, "prot id"); + + CellDesignerGenericProtein p2 = new CellDesignerGenericProtein(); + p2.setElementId("id2"); + coll.updateSpeciesByLocalId(p2, "prot id"); + assertEquals(1, coll.getSpeciesListByLocalId("prot id").size()); + CellDesignerProtein<?> p3 = coll.getSpeciesListByLocalId("prot id").get(0); + + // we don't have generic data anymore but new instance + assertFalse(p3.equals(p)); + assertFalse(p3.equals(p2)); + } + + @Test(expected = InvalidStateException.class) + public void testCreateNewInstance() { + SpeciesCollection<CellDesignerSpecies<?>> coll = new SpeciesCollection<>(); + class InvalidSpecies extends CellDesignerSpecies<Species> { + private static final long serialVersionUID = 1L; + + public InvalidSpecies() { + } + + @SuppressWarnings("unused") + public InvalidSpecies(final CellDesignerSpecies<?> sp) { + throw new NotImplementedException(); + } + } + + InvalidSpecies p = new InvalidSpecies(); + p.setElementId(""); + + coll.createNewInstance(p.getClass(), p); + } } diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/species/SpeciesCollectionXmlParserTest.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/species/SpeciesCollectionXmlParserTest.java index 8306520a288243491bb62ab4c2000bf8d6b156b5..8dcfc0e81042f939ad4c66ce8f98fb0c6944d07b 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/species/SpeciesCollectionXmlParserTest.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/species/SpeciesCollectionXmlParserTest.java @@ -1,9 +1,6 @@ package lcsb.mapviewer.converter.model.celldesigner.species; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import java.lang.reflect.Field; import java.util.ArrayList; @@ -11,9 +8,7 @@ import java.util.List; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.w3c.dom.Node; import lcsb.mapviewer.common.Pair; @@ -21,21 +16,11 @@ import lcsb.mapviewer.common.exception.InvalidXmlSchemaException; import lcsb.mapviewer.common.exception.NotImplementedException; import lcsb.mapviewer.converter.model.celldesigner.CellDesignerElementCollection; import lcsb.mapviewer.converter.model.celldesigner.CellDesignerTestFunctions; -import lcsb.mapviewer.converter.model.celldesigner.structure.CellDesignerAntisenseRna; -import lcsb.mapviewer.converter.model.celldesigner.structure.CellDesignerComplexSpecies; -import lcsb.mapviewer.converter.model.celldesigner.structure.CellDesignerGene; -import lcsb.mapviewer.converter.model.celldesigner.structure.CellDesignerGenericProtein; -import lcsb.mapviewer.converter.model.celldesigner.structure.CellDesignerProtein; -import lcsb.mapviewer.converter.model.celldesigner.structure.CellDesignerRna; -import lcsb.mapviewer.converter.model.celldesigner.structure.CellDesignerSpecies; +import lcsb.mapviewer.converter.model.celldesigner.structure.*; import lcsb.mapviewer.model.map.compartment.Compartment; import lcsb.mapviewer.model.map.model.Model; import lcsb.mapviewer.model.map.model.ModelFullIndexed; -import lcsb.mapviewer.model.map.species.AntisenseRna; -import lcsb.mapviewer.model.map.species.Gene; -import lcsb.mapviewer.model.map.species.Protein; -import lcsb.mapviewer.model.map.species.Rna; -import lcsb.mapviewer.model.map.species.Species; +import lcsb.mapviewer.model.map.species.*; public class SpeciesCollectionXmlParserTest extends CellDesignerTestFunctions { static Logger logger = LogManager.getLogger(SpeciesCollectionXmlParserTest.class); @@ -65,391 +50,262 @@ public class SpeciesCollectionXmlParserTest extends CellDesignerTestFunctions { @Test public void testParseXmlRnaCollection() throws Exception { - try { - String xmlString = readFile(testRnaListXmlFile); - Node node = getNodeFromXmlString(xmlString); - List<Pair<String, ? extends CellDesignerSpecies<?>>> list = parser.parseXmlRnaCollection(node); - assertEquals(2, list.size()); - assertTrue(list.get(0).getRight() instanceof CellDesignerRna); - } catch (Exception e) { - throw e; - } + String xmlString = readFile(testRnaListXmlFile); + Node node = getNodeFromXmlString(xmlString); + List<Pair<String, ? extends CellDesignerSpecies<?>>> list = parser.parseXmlRnaCollection(node); + assertEquals(2, list.size()); + assertTrue(list.get(0).getRight() instanceof CellDesignerRna); } - @Test + @Test(expected = InvalidXmlSchemaException.class) public void testParseInvalidXmlRnaCollection() throws Exception { - try { - String xmlString = readFile("testFiles/invalid/rna_collection.xml"); - Node node = getNodeFromXmlString(xmlString); - parser.parseXmlRnaCollection(node); - fail("Exception expected"); - } catch (InvalidXmlSchemaException e) { - assertTrue(e.getMessage().contains("Unknown element of celldesigner:listOfRNAs")); - } catch (Exception e) { - throw e; - } + String xmlString = readFile("testFiles/invalid/rna_collection.xml"); + Node node = getNodeFromXmlString(xmlString); + parser.parseXmlRnaCollection(node); } - @Test + @Test(expected = InvalidXmlSchemaException.class) public void testParseInvalidXmlGeneCollection() throws Exception { - try { - String xmlString = readFile("testFiles/invalid/gene_collection.xml"); - Node node = getNodeFromXmlString(xmlString); - parser.parseXmlGeneCollection(node); - fail("Exception expected"); - } catch (InvalidXmlSchemaException e) { - assertTrue(e.getMessage().contains("Unknown element of celldesigner:listOfGenes")); - } catch (Exception e) { - throw e; - } + String xmlString = readFile("testFiles/invalid/gene_collection.xml"); + Node node = getNodeFromXmlString(xmlString); + parser.parseXmlGeneCollection(node); } - @Test + @Test(expected = InvalidXmlSchemaException.class) public void testParseInvalidXmlAntisenseRnaCollection() throws Exception { - try { - String xmlString = readFile("testFiles/invalid/antisense_rna_collection.xml"); - Node node = getNodeFromXmlString(xmlString); - parser.parseXmlAntisenseRnaCollection(node); - fail("Exception expected"); - } catch (InvalidXmlSchemaException e) { - assertTrue(e.getMessage().contains("Unknown element of celldesigner:listOfAntisenseRNAs")); - } catch (Exception e) { - throw e; - } + String xmlString = readFile("testFiles/invalid/antisense_rna_collection.xml"); + Node node = getNodeFromXmlString(xmlString); + parser.parseXmlAntisenseRnaCollection(node); } - @Test + @Test(expected = InvalidXmlSchemaException.class) public void testParseInvalidXmlPRoteinCollection() throws Exception { - try { - String xmlString = readFile("testFiles/invalid/protein_collection.xml"); - Node node = getNodeFromXmlString(xmlString); - parser.parseXmlProteinCollection(node); - fail("Exception expected"); - } catch (InvalidXmlSchemaException e) { - assertTrue(e.getMessage().contains("Unknown element of celldesigner:listOfProteins")); - } catch (Exception e) { - throw e; - } + String xmlString = readFile("testFiles/invalid/protein_collection.xml"); + Node node = getNodeFromXmlString(xmlString); + parser.parseXmlProteinCollection(node); } @Test public void testToXmlStringRnaCollection() throws Exception { - try { - String xmlString = readFile(testRnaListXmlFile); - Node node = getNodeFromXmlString(xmlString); - List<Pair<String, ? extends CellDesignerSpecies<?>>> list = parser.parseXmlRnaCollection(node); - List<Rna> arList = new ArrayList<>(); - for (Pair<String, ? extends CellDesignerSpecies<?>> pair : list) { - arList.add((Rna) pair.getRight().createModelElement("" + (idCounter++))); - } - String convertedString = parser.rnaCollectionToXmlString(arList); - assertNotNull(convertedString); - node = getNodeFromXmlString(convertedString); - assertEquals("celldesigner:listOfRNAs", node.getNodeName()); - List<Pair<String, ? extends CellDesignerSpecies<?>>> list2 = parser.parseXmlRnaCollection(node); - assertNotNull(list2); - assertEquals(list.size(), list2.size()); - assertEquals(list.get(0).getClass().getName(), list2.get(0).getClass().getName()); - } catch (Exception e) { - throw e; + String xmlString = readFile(testRnaListXmlFile); + Node node = getNodeFromXmlString(xmlString); + List<Pair<String, ? extends CellDesignerSpecies<?>>> list = parser.parseXmlRnaCollection(node); + List<Rna> arList = new ArrayList<>(); + for (Pair<String, ? extends CellDesignerSpecies<?>> pair : list) { + arList.add((Rna) pair.getRight().createModelElement("" + (idCounter++))); } + String convertedString = parser.rnaCollectionToXmlString(arList); + assertNotNull(convertedString); + node = getNodeFromXmlString(convertedString); + assertEquals("celldesigner:listOfRNAs", node.getNodeName()); + List<Pair<String, ? extends CellDesignerSpecies<?>>> list2 = parser.parseXmlRnaCollection(node); + assertNotNull(list2); + assertEquals(list.size(), list2.size()); + assertEquals(list.get(0).getClass().getName(), list2.get(0).getClass().getName()); } @Test public void testParseXmlGeneCollection() throws Exception { - try { - String xmlString = readFile(testGeneListXmlFile); - Node node = getNodeFromXmlString(xmlString); - List<Pair<String, ? extends CellDesignerSpecies<?>>> list = parser.parseXmlGeneCollection(node); - assertEquals(2, list.size()); - assertTrue(list.get(0).getRight() instanceof CellDesignerGene); - } catch (Exception exception) { - throw exception; - } + String xmlString = readFile(testGeneListXmlFile); + Node node = getNodeFromXmlString(xmlString); + List<Pair<String, ? extends CellDesignerSpecies<?>>> list = parser.parseXmlGeneCollection(node); + assertEquals(2, list.size()); + assertTrue(list.get(0).getRight() instanceof CellDesignerGene); } @Test public void testToXmlStringGeneCollection() throws Exception { - try { - String xmlString = readFile(testGeneListXmlFile); - Node node = getNodeFromXmlString(xmlString); - List<Pair<String, ? extends CellDesignerSpecies<?>>> list = parser.parseXmlGeneCollection(node); - List<Gene> arList = new ArrayList<>(); - for (Pair<String, ? extends CellDesignerSpecies<?>> pair : list) { - arList.add((Gene) pair.getRight().createModelElement("" + (idCounter++))); - } - String convertedString = parser.geneCollectionToXmlString(arList); - assertNotNull(convertedString); - node = getNodeFromXmlString(convertedString); - assertEquals("celldesigner:listOfGenes", node.getNodeName()); - List<Pair<String, ? extends CellDesignerSpecies<?>>> list2 = parser.parseXmlGeneCollection(node); - assertNotNull(list2); - assertEquals(list.size(), list2.size()); - assertEquals(list.get(0).getClass().getName(), list2.get(0).getClass().getName()); - } catch (Exception exception) { - throw exception; + String xmlString = readFile(testGeneListXmlFile); + Node node = getNodeFromXmlString(xmlString); + List<Pair<String, ? extends CellDesignerSpecies<?>>> list = parser.parseXmlGeneCollection(node); + List<Gene> arList = new ArrayList<>(); + for (Pair<String, ? extends CellDesignerSpecies<?>> pair : list) { + arList.add((Gene) pair.getRight().createModelElement("" + (idCounter++))); } + String convertedString = parser.geneCollectionToXmlString(arList); + assertNotNull(convertedString); + node = getNodeFromXmlString(convertedString); + assertEquals("celldesigner:listOfGenes", node.getNodeName()); + List<Pair<String, ? extends CellDesignerSpecies<?>>> list2 = parser.parseXmlGeneCollection(node); + assertNotNull(list2); + assertEquals(list.size(), list2.size()); + assertEquals(list.get(0).getClass().getName(), list2.get(0).getClass().getName()); } @Test public void testParseXmlProteinCollection() throws Exception { - try { - String xmlString = readFile(testProteinListXmlFile); - Node node = getNodeFromXmlString(xmlString); - List<Pair<String, ? extends CellDesignerSpecies<?>>> list = parser.parseXmlProteinCollection(node); - assertEquals(4, list.size()); - assertTrue(list.get(0).getRight() instanceof CellDesignerProtein); - } catch (Exception exception) { - throw exception; - } + String xmlString = readFile(testProteinListXmlFile); + Node node = getNodeFromXmlString(xmlString); + List<Pair<String, ? extends CellDesignerSpecies<?>>> list = parser.parseXmlProteinCollection(node); + assertEquals(4, list.size()); + assertTrue(list.get(0).getRight() instanceof CellDesignerProtein); } @Test public void testToXmlStringProteinCollection() throws Exception { - try { - String xmlString = readFile(testProteinListXmlFile); - Node node = getNodeFromXmlString(xmlString); - List<Pair<String, ? extends CellDesignerSpecies<?>>> list = parser.parseXmlProteinCollection(node); - List<Protein> arList = new ArrayList<>(); - for (Pair<String, ? extends CellDesignerSpecies<?>> pair : list) { - arList.add((Protein) pair.getRight().createModelElement("" + idCounter++)); - } - String convertedString = parser.proteinCollectionToXmlString(arList); - assertNotNull(convertedString); - node = getNodeFromXmlString(convertedString); - assertEquals("celldesigner:listOfProteins", node.getNodeName()); - List<Pair<String, ? extends CellDesignerSpecies<?>>> list2 = parser.parseXmlProteinCollection(node); - assertNotNull(list2); - assertEquals(list.size(), list2.size()); - assertEquals(list.get(0).getClass().getName(), list2.get(0).getClass().getName()); - } catch (Exception e) { - e.printStackTrace(); - throw e; + String xmlString = readFile(testProteinListXmlFile); + Node node = getNodeFromXmlString(xmlString); + List<Pair<String, ? extends CellDesignerSpecies<?>>> list = parser.parseXmlProteinCollection(node); + List<Protein> arList = new ArrayList<>(); + for (Pair<String, ? extends CellDesignerSpecies<?>> pair : list) { + arList.add((Protein) pair.getRight().createModelElement("" + idCounter++)); } + String convertedString = parser.proteinCollectionToXmlString(arList); + assertNotNull(convertedString); + node = getNodeFromXmlString(convertedString); + assertEquals("celldesigner:listOfProteins", node.getNodeName()); + List<Pair<String, ? extends CellDesignerSpecies<?>>> list2 = parser.parseXmlProteinCollection(node); + assertNotNull(list2); + assertEquals(list.size(), list2.size()); + assertEquals(list.get(0).getClass().getName(), list2.get(0).getClass().getName()); } @Test - public void testParseXmlAntisenseRnaCollection() { - try { - String xmlString = readFile(testAntisenseRnaListXmlFile); - Node node = getNodeFromXmlString(xmlString); - List<Pair<String, ? extends CellDesignerSpecies<?>>> list = parser.parseXmlAntisenseRnaCollection(node); - assertEquals(2, list.size()); - assertTrue(list.get(0).getRight() instanceof CellDesignerAntisenseRna); - } catch (Exception exception) { - fail("Unexpected exception occurred"); - } + public void testParseXmlAntisenseRnaCollection() throws Exception { + String xmlString = readFile(testAntisenseRnaListXmlFile); + Node node = getNodeFromXmlString(xmlString); + List<Pair<String, ? extends CellDesignerSpecies<?>>> list = parser.parseXmlAntisenseRnaCollection(node); + assertEquals(2, list.size()); + assertTrue(list.get(0).getRight() instanceof CellDesignerAntisenseRna); } @Test public void testToXmlStringAntisenseRnaCollection() throws Exception { - try { - String xmlString = readFile(testAntisenseRnaListXmlFile); - Node node = getNodeFromXmlString(xmlString); - List<Pair<String, ? extends CellDesignerSpecies<?>>> list = parser.parseXmlAntisenseRnaCollection(node); - List<AntisenseRna> arList = new ArrayList<>(); - for (Pair<String, ? extends CellDesignerSpecies<?>> pair : list) { - arList.add((AntisenseRna) pair.getRight().createModelElement("" + (idCounter++))); - } - String convertedString = parser.antisenseRnaCollectionToXmlString(arList); - assertNotNull(convertedString); - node = getNodeFromXmlString(convertedString); - assertEquals("celldesigner:listOfAntisenseRNAs", node.getNodeName()); - List<Pair<String, ? extends CellDesignerSpecies<?>>> list2 = parser.parseXmlAntisenseRnaCollection(node); - assertNotNull(list2); - assertEquals(list.size(), list2.size()); - assertEquals(list.get(0).getClass().getName(), list2.get(0).getClass().getName()); - } catch (Exception e) { - e.printStackTrace(); - throw e; + String xmlString = readFile(testAntisenseRnaListXmlFile); + Node node = getNodeFromXmlString(xmlString); + List<Pair<String, ? extends CellDesignerSpecies<?>>> list = parser.parseXmlAntisenseRnaCollection(node); + List<AntisenseRna> arList = new ArrayList<>(); + for (Pair<String, ? extends CellDesignerSpecies<?>> pair : list) { + arList.add((AntisenseRna) pair.getRight().createModelElement("" + (idCounter++))); } + String convertedString = parser.antisenseRnaCollectionToXmlString(arList); + assertNotNull(convertedString); + node = getNodeFromXmlString(convertedString); + assertEquals("celldesigner:listOfAntisenseRNAs", node.getNodeName()); + List<Pair<String, ? extends CellDesignerSpecies<?>>> list2 = parser.parseXmlAntisenseRnaCollection(node); + assertNotNull(list2); + assertEquals(list.size(), list2.size()); + assertEquals(list.get(0).getClass().getName(), list2.get(0).getClass().getName()); } @Test public void testParseSbmlSpeciesCollection() throws Exception { - try { - String xmlString = readFile(testSbmlListXmlFile); - Node node = getNodeFromXmlString(xmlString); - List<Pair<String, ? extends CellDesignerSpecies<?>>> list = parser.parseSbmlSpeciesCollection(node); - assertEquals(9, list.size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String xmlString = readFile(testSbmlListXmlFile); + Node node = getNodeFromXmlString(xmlString); + List<Pair<String, ? extends CellDesignerSpecies<?>>> list = parser.parseSbmlSpeciesCollection(node); + assertEquals(9, list.size()); } - @Test + @Test(expected = InvalidXmlSchemaException.class) public void testParseInvalidSbmlSpeciesCollection() throws Exception { - try { - String xmlString = readFile("testFiles/invalid/sbml_collection.xml"); - Node node = getNodeFromXmlString(xmlString); - parser.parseSbmlSpeciesCollection(node); - } catch (InvalidXmlSchemaException e) { - assertTrue(e.getMessage().contains("Unknown element of listOfSpecies")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String xmlString = readFile("testFiles/invalid/sbml_collection.xml"); + Node node = getNodeFromXmlString(xmlString); + parser.parseSbmlSpeciesCollection(node); } @Test public void testToSbmlStringSpeciesCollection() throws Exception { - try { - String xmlString = readFile(testSbmlListXmlFile); - Node node = getNodeFromXmlString(xmlString); - List<Pair<String, ? extends CellDesignerSpecies<?>>> list = parser.parseSbmlSpeciesCollection(node); - Model model = new ModelFullIndexed(null); - int x = 0; - List<Species> speciesList = new ArrayList<>(); - for (Pair<String, ? extends CellDesignerSpecies<?>> el : list) { - CellDesignerSpecies<?> species = el.getRight(); - if (species.getClass() == CellDesignerProtein.class) { - species = new CellDesignerGenericProtein(species); - } - - Species alias = species.createModelElement("alias" + (x++)); - model.addElement(alias); - speciesList.add(alias); + String xmlString = readFile(testSbmlListXmlFile); + Node node = getNodeFromXmlString(xmlString); + List<Pair<String, ? extends CellDesignerSpecies<?>>> list = parser.parseSbmlSpeciesCollection(node); + Model model = new ModelFullIndexed(null); + int x = 0; + List<Species> speciesList = new ArrayList<>(); + for (Pair<String, ? extends CellDesignerSpecies<?>> el : list) { + CellDesignerSpecies<?> species = el.getRight(); + if (species.getClass() == CellDesignerProtein.class) { + species = new CellDesignerGenericProtein(species); } - model.addElement(new Compartment("default")); - String convertedString = parser.speciesCollectionToSbmlString(speciesList); - assertNotNull(convertedString); - node = getNodeFromXmlString(convertedString); - assertEquals("listOfSpecies", node.getNodeName()); - List<Pair<String, ? extends CellDesignerSpecies<?>>> list2 = parser.parseSbmlSpeciesCollection(node); - assertNotNull(list2); - assertEquals(list.size(), list2.size()); - assertEquals(list.get(0).getClass().getName(), list2.get(0).getClass().getName()); - } catch (Exception exception) { - exception.printStackTrace(); - throw exception; + + Species alias = species.createModelElement("alias" + (x++)); + model.addElement(alias); + speciesList.add(alias); } + model.addElement(new Compartment("default")); + String convertedString = parser.speciesCollectionToSbmlString(speciesList); + assertNotNull(convertedString); + node = getNodeFromXmlString(convertedString); + assertEquals("listOfSpecies", node.getNodeName()); + List<Pair<String, ? extends CellDesignerSpecies<?>>> list2 = parser.parseSbmlSpeciesCollection(node); + assertNotNull(list2); + assertEquals(list.size(), list2.size()); + assertEquals(list.get(0).getClass().getName(), list2.get(0).getClass().getName()); } @Test public void testParseIncludedSpeciesCollection() throws Exception { - try { - String xmlString = readFile(testIncludedListXmlFile); - Node node = getNodeFromXmlString(xmlString); - List<Pair<String, ? extends CellDesignerSpecies<?>>> list = parser.parseIncludedSpeciesCollection(node); - assertEquals(3, list.size()); - int complexes = 0; - int proteins = 0; - for (Pair<String, ? extends CellDesignerSpecies<?>> species : list) { - if (species.getRight() instanceof CellDesignerComplexSpecies) - complexes++; - if (species.getRight() instanceof CellDesignerProtein) - proteins++; - } - assertEquals(1, complexes); - assertEquals(2, proteins); - } catch (Exception exception) { - exception.printStackTrace(); - throw exception; + String xmlString = readFile(testIncludedListXmlFile); + Node node = getNodeFromXmlString(xmlString); + List<Pair<String, ? extends CellDesignerSpecies<?>>> list = parser.parseIncludedSpeciesCollection(node); + assertEquals(3, list.size()); + int complexes = 0; + int proteins = 0; + for (Pair<String, ? extends CellDesignerSpecies<?>> species : list) { + if (species.getRight() instanceof CellDesignerComplexSpecies) + complexes++; + if (species.getRight() instanceof CellDesignerProtein) + proteins++; } + assertEquals(1, complexes); + assertEquals(2, proteins); } - @Test + @Test(expected = InvalidXmlSchemaException.class) public void testParseInvalidIncludedSpeciesCollection() throws Exception { - try { - String xmlString = readFile("testFiles/invalid/included_species_collection.xml"); - Node node = getNodeFromXmlString(xmlString); - parser.parseIncludedSpeciesCollection(node); - fail("Exception expected"); - } catch (InvalidXmlSchemaException exception) { - assertTrue(exception.getMessage().contains("Included species does not contain id")); - } catch (Exception exception) { - exception.printStackTrace(); - throw exception; - } + String xmlString = readFile("testFiles/invalid/included_species_collection.xml"); + Node node = getNodeFromXmlString(xmlString); + parser.parseIncludedSpeciesCollection(node); } - @Test + @Test(expected = InvalidXmlSchemaException.class) public void testParseInvalidIncludedSpeciesCollection2() throws Exception { - try { - String xmlString = readFile("testFiles/invalid/included_species_collection2.xml"); - Node node = getNodeFromXmlString(xmlString); - parser.parseIncludedSpeciesCollection(node); - fail("Exception expected"); - } catch (InvalidXmlSchemaException exception) { - assertTrue(exception.getMessage().contains("Unknown element of celldesigner:species")); - } catch (Exception exception) { - exception.printStackTrace(); - throw exception; - } + String xmlString = readFile("testFiles/invalid/included_species_collection2.xml"); + Node node = getNodeFromXmlString(xmlString); + parser.parseIncludedSpeciesCollection(node); } - @Test + @Test(expected = InvalidXmlSchemaException.class) public void testParseInvalidIncludedSpeciesCollection3() throws Exception { - try { - String xmlString = readFile("testFiles/invalid/included_species_collection3.xml"); - Node node = getNodeFromXmlString(xmlString); - parser.parseIncludedSpeciesCollection(node); - fail("Exception expected"); - } catch (InvalidXmlSchemaException exception) { - assertTrue(exception.getMessage().contains("Included species does not contain annotation node")); - } catch (Exception exception) { - exception.printStackTrace(); - throw exception; - } + String xmlString = readFile("testFiles/invalid/included_species_collection3.xml"); + Node node = getNodeFromXmlString(xmlString); + parser.parseIncludedSpeciesCollection(node); } - @Test + @Test(expected = InvalidXmlSchemaException.class) public void testParseInvalidIncludedSpeciesCollection4() throws Exception { - try { - String xmlString = readFile("testFiles/invalid/included_species_collection4.xml"); - Node node = getNodeFromXmlString(xmlString); - parser.parseIncludedSpeciesCollection(node); - fail("Exception expected"); - } catch (InvalidXmlSchemaException exception) { - assertTrue(exception.getMessage().contains("No celldesigner:speciesIdentity node in included tag")); - } catch (Exception exception) { - exception.printStackTrace(); - throw exception; - } + String xmlString = readFile("testFiles/invalid/included_species_collection4.xml"); + Node node = getNodeFromXmlString(xmlString); + parser.parseIncludedSpeciesCollection(node); } - @Test + @Test(expected = InvalidXmlSchemaException.class) public void testParseInvalidIncludedSpeciesCollection5() throws Exception { - try { - String xmlString = readFile("testFiles/invalid/included_species_collection5.xml"); - Node node = getNodeFromXmlString(xmlString); - parser.parseIncludedSpeciesCollection(node); - fail("Exception expected"); - } catch (InvalidXmlSchemaException exception) { - assertTrue(exception.getMessage().contains("Unknown element of celldesigner:listOfIncludedSpecies")); - } catch (Exception exception) { - exception.printStackTrace(); - throw exception; - } + String xmlString = readFile("testFiles/invalid/included_species_collection5.xml"); + Node node = getNodeFromXmlString(xmlString); + parser.parseIncludedSpeciesCollection(node); } @Test public void artifitialTest() throws Exception { - try { - // tests some parts of the code that should never be called and therefore - // throw exceptions + // tests some parts of the code that should never be called and therefore + // throw exceptions - // this is only for test coverage puropse + // this is only for test coverage purpose - SpeciesCollectionXmlParser parser = new SpeciesCollectionXmlParser(elements); - Field field = SpeciesCollectionXmlParser.class.getDeclaredField("helpParser"); - field.setAccessible(true); - try { - ((AbstractElementXmlParser<?, ?>) field.get(parser)).toXml(null); - fail("Exception expected"); - } catch (NotImplementedException e) { + SpeciesCollectionXmlParser parser = new SpeciesCollectionXmlParser(elements); + Field field = SpeciesCollectionXmlParser.class.getDeclaredField("helpParser"); + field.setAccessible(true); + try { + ((AbstractElementXmlParser<?, ?>) field.get(parser)).toXml(null); + fail("Exception expected"); + } catch (NotImplementedException e) { - } - try { - ((AbstractElementXmlParser<?, ?>) field.get(parser)).parseXmlElement((Node) null); - fail("Exception expected"); - } catch (NotImplementedException e) { + } + try { + ((AbstractElementXmlParser<?, ?>) field.get(parser)).parseXmlElement((Node) null); + fail("Exception expected"); + } catch (NotImplementedException e) { - } - } catch (Exception exception) { - exception.printStackTrace(); - throw exception; } } diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/species/SpeciesMappingTest.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/species/SpeciesMappingTest.java index 75f64f4d76abf842f7a3d3afa7868c910a697715..dfe1e0000680921b5c0f4e7014501dfa5e4a9822 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/species/SpeciesMappingTest.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/species/SpeciesMappingTest.java @@ -1,21 +1,18 @@ package lcsb.mapviewer.converter.model.celldesigner.species; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import java.lang.reflect.Field; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import lcsb.mapviewer.common.exception.InvalidStateException; import lcsb.mapviewer.common.exception.NotImplementedException; +import lcsb.mapviewer.converter.model.celldesigner.CellDesignerTestFunctions; import lcsb.mapviewer.converter.model.celldesigner.structure.CellDesignerSpecies; import lcsb.mapviewer.model.map.species.Protein; -public class SpeciesMappingTest { +public class SpeciesMappingTest extends CellDesignerTestFunctions { @AfterClass public static void tearDownAfterClass() throws Exception { @@ -44,7 +41,7 @@ public class SpeciesMappingTest { assertNotNull(mapping); } - @Test + @Test(expected = InvalidStateException.class) public void testCreateInvalidSpeciesImpl() throws Exception { // artificial implementation of Species that is invalid class InvalidSpecies extends CellDesignerSpecies<Protein> { @@ -69,11 +66,6 @@ public class SpeciesMappingTest { // and check if we catch properly information about problematic // implementation typeToModify.createSpecies(new CellDesignerSpecies<Protein>()); - fail("Exceptione expected"); - } catch (InvalidStateException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; } finally { // restore correct values for the modified type (if not then other test // might fail...) diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/species/SpeciesSbmlParserTest.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/species/SpeciesSbmlParserTest.java index c84c3ee956a772d850e163ad03956cc53a6a33b4..f6dbdcfc63b8da04f2571a6b3de6c74c60391f0f 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/species/SpeciesSbmlParserTest.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/species/SpeciesSbmlParserTest.java @@ -1,10 +1,6 @@ package lcsb.mapviewer.converter.model.celldesigner.species; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import java.io.StringReader; @@ -13,9 +9,7 @@ import javax.xml.parsers.DocumentBuilderFactory; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.mockito.Mockito; import org.w3c.dom.Document; import org.w3c.dom.NodeList; @@ -23,30 +17,14 @@ import org.xml.sax.InputSource; import lcsb.mapviewer.common.Configuration; import lcsb.mapviewer.common.Pair; -import lcsb.mapviewer.common.exception.InvalidArgumentException; -import lcsb.mapviewer.common.exception.InvalidXmlSchemaException; -import lcsb.mapviewer.common.exception.NotImplementedException; +import lcsb.mapviewer.common.exception.*; import lcsb.mapviewer.converter.model.celldesigner.CellDesignerElementCollection; import lcsb.mapviewer.converter.model.celldesigner.CellDesignerTestFunctions; -import lcsb.mapviewer.converter.model.celldesigner.structure.CellDesignerAntisenseRna; -import lcsb.mapviewer.converter.model.celldesigner.structure.CellDesignerComplexSpecies; -import lcsb.mapviewer.converter.model.celldesigner.structure.CellDesignerDegraded; -import lcsb.mapviewer.converter.model.celldesigner.structure.CellDesignerDrug; -import lcsb.mapviewer.converter.model.celldesigner.structure.CellDesignerGene; -import lcsb.mapviewer.converter.model.celldesigner.structure.CellDesignerGenericProtein; -import lcsb.mapviewer.converter.model.celldesigner.structure.CellDesignerIon; -import lcsb.mapviewer.converter.model.celldesigner.structure.CellDesignerPhenotype; -import lcsb.mapviewer.converter.model.celldesigner.structure.CellDesignerProtein; -import lcsb.mapviewer.converter.model.celldesigner.structure.CellDesignerRna; -import lcsb.mapviewer.converter.model.celldesigner.structure.CellDesignerSimpleMolecule; -import lcsb.mapviewer.converter.model.celldesigner.structure.CellDesignerSpecies; -import lcsb.mapviewer.converter.model.celldesigner.structure.CellDesignerUnknown; +import lcsb.mapviewer.converter.model.celldesigner.structure.*; import lcsb.mapviewer.converter.model.celldesigner.structure.fields.CellDesignerModificationResidue; import lcsb.mapviewer.converter.model.celldesigner.structure.fields.SpeciesState; import lcsb.mapviewer.model.map.kinetics.SbmlUnitType; -import lcsb.mapviewer.model.map.species.Gene; -import lcsb.mapviewer.model.map.species.GenericProtein; -import lcsb.mapviewer.model.map.species.Species; +import lcsb.mapviewer.model.map.species.*; public class SpeciesSbmlParserTest extends CellDesignerTestFunctions { @SuppressWarnings("unused") @@ -80,1063 +58,713 @@ public class SpeciesSbmlParserTest extends CellDesignerTestFunctions { @Test public void testParseXmlSpeciesAntisenseRna() throws Exception { - try { - String xmlString = readFile("testFiles/xmlNodeTestExamples/sbml_antisense_rna.xml"); - Pair<String, ? extends CellDesignerSpecies<?>> result = parser.parseXmlElement(xmlString); - CellDesignerAntisenseRna species = (CellDesignerAntisenseRna) result.getRight(); - assertEquals("s2", species.getElementId()); - assertEquals("s3", species.getName()); - assertEquals(2, species.getInitialAmount(), Configuration.EPSILON); - assertEquals(Boolean.TRUE, species.hasOnlySubstanceUnits()); - assertEquals(new Integer(0), species.getCharge()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String xmlString = readFile("testFiles/xmlNodeTestExamples/sbml_antisense_rna.xml"); + Pair<String, ? extends CellDesignerSpecies<?>> result = parser.parseXmlElement(xmlString); + CellDesignerAntisenseRna species = (CellDesignerAntisenseRna) result.getRight(); + assertEquals("s2", species.getElementId()); + assertEquals("s3", species.getName()); + assertEquals(2, species.getInitialAmount(), Configuration.EPSILON); + assertEquals(Boolean.TRUE, species.hasOnlySubstanceUnits()); + assertEquals(new Integer(0), species.getCharge()); } @Test public void testParseXmlSpeciesWithKineticsData() throws Exception { - try { - String xmlString = readFile("testFiles/kinetics/species_with_kinetics_param.xml"); - Pair<String, ? extends CellDesignerSpecies<?>> result = parser.parseXmlElement(xmlString); - CellDesignerProtein<?> species = (CellDesignerProtein<?>) result.getRight(); - assertEquals(3.7, species.getInitialConcentration(), Configuration.EPSILON); - assertEquals(SbmlUnitType.MOLE, species.getSubstanceUnit()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String xmlString = readFile("testFiles/kinetics/species_with_kinetics_param.xml"); + Pair<String, ? extends CellDesignerSpecies<?>> result = parser.parseXmlElement(xmlString); + CellDesignerProtein<?> species = (CellDesignerProtein<?>) result.getRight(); + assertEquals(3.7, species.getInitialConcentration(), Configuration.EPSILON); + assertEquals(SbmlUnitType.MOLE, species.getSubstanceUnit()); } @Test public void testSpeciesUnitsToXml() throws Exception { - try { - GenericProtein protein = new GenericProtein("s1"); - protein.setSubstanceUnits(SbmlUnitType.MOLE); - String xml = parser.toXml(protein); - assertTrue("Cannot find substance unit in xml", xml.indexOf("mole") >= 0); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + GenericProtein protein = new GenericProtein("s1"); + protein.setSubstanceUnits(SbmlUnitType.MOLE); + String xml = parser.toXml(protein); + assertTrue("Cannot find substance unit in xml", xml.indexOf("mole") >= 0); } @Test public void testSpeciesConstantToXml() throws Exception { - try { - GenericProtein protein = new GenericProtein("s1"); - protein.setConstant(true); - String xml = parser.toXml(protein); - assertTrue("Cannot find constant in xml", xml.indexOf("constant") >= 0); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + GenericProtein protein = new GenericProtein("s1"); + protein.setConstant(true); + String xml = parser.toXml(protein); + assertTrue("Cannot find constant in xml", xml.indexOf("constant") >= 0); } @Test public void testSpeciesBoundaryConditionToXml() throws Exception { - try { - GenericProtein protein = new GenericProtein("s1"); - protein.setBoundaryCondition(true); - String xml = parser.toXml(protein); - assertTrue("Cannot find boundary condition in xml", xml.indexOf("boundaryCondition") >= 0); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + GenericProtein protein = new GenericProtein("s1"); + protein.setBoundaryCondition(true); + String xml = parser.toXml(protein); + assertTrue("Cannot find boundary condition in xml", xml.indexOf("boundaryCondition") >= 0); } @Test public void testParseXmlSpeciesWithKineticsData2() throws Exception { - try { - String xmlString = readFile("testFiles/kinetics/species_with_kinetics_param2.xml"); - Pair<String, ? extends CellDesignerSpecies<?>> result = parser.parseXmlElement(xmlString); - CellDesignerProtein<?> species = (CellDesignerProtein<?>) result.getRight(); - assertEquals(2.5, species.getInitialAmount(), Configuration.EPSILON); - assertEquals(SbmlUnitType.GRAM, species.getSubstanceUnit()); - assertEquals(Boolean.TRUE, species.hasOnlySubstanceUnits()); - assertEquals("Boundary condition wasn't parsed", Boolean.TRUE, species.isBoundaryCondition()); - assertEquals("Constant property wasn't parsed", Boolean.TRUE, species.isConstant()); - assertEquals(new Integer(0), species.getCharge()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String xmlString = readFile("testFiles/kinetics/species_with_kinetics_param2.xml"); + Pair<String, ? extends CellDesignerSpecies<?>> result = parser.parseXmlElement(xmlString); + CellDesignerProtein<?> species = (CellDesignerProtein<?>) result.getRight(); + assertEquals(2.5, species.getInitialAmount(), Configuration.EPSILON); + assertEquals(SbmlUnitType.GRAM, species.getSubstanceUnit()); + assertEquals(Boolean.TRUE, species.hasOnlySubstanceUnits()); + assertEquals("Boundary condition wasn't parsed", Boolean.TRUE, species.isBoundaryCondition()); + assertEquals("Constant property wasn't parsed", Boolean.TRUE, species.isConstant()); + assertEquals(new Integer(0), species.getCharge()); } @Test public void testToXmlAntisenseRna() throws Exception { - try { - String xmlString = readFile("testFiles/xmlNodeTestExamples/sbml_antisense_rna.xml"); - Pair<String, ? extends CellDesignerSpecies<?>> result = parser.parseXmlElement(xmlString); - CellDesignerAntisenseRna species = (CellDesignerAntisenseRna) result.getRight(); - - String transformedXml = parser.toXml(species.createModelElement()); - assertNotNull(transformedXml); - DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); - DocumentBuilder builder = factory.newDocumentBuilder(); - InputSource is = new InputSource(new StringReader(transformedXml)); - Document doc = builder.parse(is); - NodeList root = doc.getChildNodes(); - assertEquals("species", root.item(0).getNodeName()); - - Pair<String, ? extends CellDesignerSpecies<?>> result2 = parser - .parseXmlElement(parser.toXml(species.createModelElement())); - CellDesignerAntisenseRna species2 = (CellDesignerAntisenseRna) result2.getRight(); - - assertEquals(species.getName(), species2.getName()); - assertEquals(species.getParent(), species2.getParent()); - assertEquals(species.getInitialAmount(), species2.getInitialAmount()); - assertEquals(species.hasOnlySubstanceUnits(), species2.hasOnlySubstanceUnits()); - assertEquals(species.getCharge(), species2.getCharge()); - assertEquals(species.getPositionToCompartment(), species2.getPositionToCompartment()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String xmlString = readFile("testFiles/xmlNodeTestExamples/sbml_antisense_rna.xml"); + Pair<String, ? extends CellDesignerSpecies<?>> result = parser.parseXmlElement(xmlString); + CellDesignerAntisenseRna species = (CellDesignerAntisenseRna) result.getRight(); + + String transformedXml = parser.toXml(species.createModelElement()); + assertNotNull(transformedXml); + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + DocumentBuilder builder = factory.newDocumentBuilder(); + InputSource is = new InputSource(new StringReader(transformedXml)); + Document doc = builder.parse(is); + NodeList root = doc.getChildNodes(); + assertEquals("species", root.item(0).getNodeName()); + + Pair<String, ? extends CellDesignerSpecies<?>> result2 = parser + .parseXmlElement(parser.toXml(species.createModelElement())); + CellDesignerAntisenseRna species2 = (CellDesignerAntisenseRna) result2.getRight(); + + assertEquals(species.getName(), species2.getName()); + assertEquals(species.getParent(), species2.getParent()); + assertEquals(species.getInitialAmount(), species2.getInitialAmount()); + assertEquals(species.hasOnlySubstanceUnits(), species2.hasOnlySubstanceUnits()); + assertEquals(species.getCharge(), species2.getCharge()); + assertEquals(species.getPositionToCompartment(), species2.getPositionToCompartment()); } @Test public void testParseXmlSpeciesComplex() throws Exception { - try { - String xmlString = readFile("testFiles/xmlNodeTestExamples/sbml_complex.xml"); - Pair<String, ? extends CellDesignerSpecies<?>> result = parser.parseXmlElement(xmlString); - CellDesignerComplexSpecies species = (CellDesignerComplexSpecies) result.getRight(); - assertNotNull(species); - assertEquals("s6549", species.getElementId()); - assertEquals("LC3-II", species.getName()); - assertEquals(0.0, species.getInitialAmount(), Configuration.EPSILON); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String xmlString = readFile("testFiles/xmlNodeTestExamples/sbml_complex.xml"); + Pair<String, ? extends CellDesignerSpecies<?>> result = parser.parseXmlElement(xmlString); + CellDesignerComplexSpecies species = (CellDesignerComplexSpecies) result.getRight(); + assertNotNull(species); + assertEquals("s6549", species.getElementId()); + assertEquals("LC3-II", species.getName()); + assertEquals(0.0, species.getInitialAmount(), Configuration.EPSILON); } @Test public void testToXmlComplex() throws Exception { - try { - String xmlString = readFile("testFiles/xmlNodeTestExamples/sbml_complex.xml"); - Pair<String, ? extends CellDesignerSpecies<?>> result = parser.parseXmlElement(xmlString); - CellDesignerComplexSpecies species = (CellDesignerComplexSpecies) result.getRight(); - - String transformedXml = parser.toXml(species.createModelElement()); - assertNotNull(transformedXml); - DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); - DocumentBuilder builder = factory.newDocumentBuilder(); - InputSource is = new InputSource(new StringReader(transformedXml)); - Document doc = builder.parse(is); - NodeList root = doc.getChildNodes(); - assertEquals("species", root.item(0).getNodeName()); - - Pair<String, ? extends CellDesignerSpecies<?>> result2 = parser - .parseXmlElement(parser.toXml(species.createModelElement())); - CellDesignerComplexSpecies species2 = (CellDesignerComplexSpecies) result2.getRight(); - - assertNotNull(species2); - assertEquals(species.getName(), species2.getName()); - assertEquals(species.getParent(), species2.getParent()); - assertEquals(species.getInitialAmount(), species2.getInitialAmount()); - assertEquals(species.hasOnlySubstanceUnits(), species2.hasOnlySubstanceUnits()); - assertEquals(species.getCharge(), species2.getCharge()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String xmlString = readFile("testFiles/xmlNodeTestExamples/sbml_complex.xml"); + Pair<String, ? extends CellDesignerSpecies<?>> result = parser.parseXmlElement(xmlString); + CellDesignerComplexSpecies species = (CellDesignerComplexSpecies) result.getRight(); + + String transformedXml = parser.toXml(species.createModelElement()); + assertNotNull(transformedXml); + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + DocumentBuilder builder = factory.newDocumentBuilder(); + InputSource is = new InputSource(new StringReader(transformedXml)); + Document doc = builder.parse(is); + NodeList root = doc.getChildNodes(); + assertEquals("species", root.item(0).getNodeName()); + + Pair<String, ? extends CellDesignerSpecies<?>> result2 = parser + .parseXmlElement(parser.toXml(species.createModelElement())); + CellDesignerComplexSpecies species2 = (CellDesignerComplexSpecies) result2.getRight(); + + assertNotNull(species2); + assertEquals(species.getName(), species2.getName()); + assertEquals(species.getParent(), species2.getParent()); + assertEquals(species.getInitialAmount(), species2.getInitialAmount()); + assertEquals(species.hasOnlySubstanceUnits(), species2.hasOnlySubstanceUnits()); + assertEquals(species.getCharge(), species2.getCharge()); } @Test public void testParseXmlSpeciesDegraded() throws Exception { - try { - String xmlString = readFile(testDegradedFile); - Pair<String, ? extends CellDesignerSpecies<?>> result = parser.parseXmlElement(xmlString); - CellDesignerDegraded species = (CellDesignerDegraded) result.getRight(); - assertNotNull(species); - assertEquals("s1275", species.getElementId()); - assertEquals("s1275", species.getName()); - assertEquals(0, species.getInitialAmount(), Configuration.EPSILON); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String xmlString = readFile(testDegradedFile); + Pair<String, ? extends CellDesignerSpecies<?>> result = parser.parseXmlElement(xmlString); + CellDesignerDegraded species = (CellDesignerDegraded) result.getRight(); + assertNotNull(species); + assertEquals("s1275", species.getElementId()); + assertEquals("s1275", species.getName()); + assertEquals(0, species.getInitialAmount(), Configuration.EPSILON); } @Test public void testToXmlDegraded() throws Exception { - try { - String xmlString = readFile(testDegradedFile); - Pair<String, ? extends CellDesignerSpecies<?>> result = parser.parseXmlElement(xmlString); - CellDesignerDegraded species = (CellDesignerDegraded) result.getRight(); - - String transformedXml = parser.toXml(species.createModelElement()); - assertNotNull(transformedXml); - DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); - DocumentBuilder builder = factory.newDocumentBuilder(); - InputSource is = new InputSource(new StringReader(transformedXml)); - Document doc = builder.parse(is); - NodeList root = doc.getChildNodes(); - assertEquals("species", root.item(0).getNodeName()); - - Pair<String, ? extends CellDesignerSpecies<?>> result2 = parser - .parseXmlElement(parser.toXml(species.createModelElement())); - CellDesignerDegraded species2 = (CellDesignerDegraded) result2.getRight(); - - assertNotNull(species2); - assertEquals(species.getName(), species2.getName()); - assertEquals(species.getParent(), species2.getParent()); - assertEquals(species.getInitialAmount(), species2.getInitialAmount()); - assertEquals(species.hasOnlySubstanceUnits(), species2.hasOnlySubstanceUnits()); - assertEquals(species.getCharge(), species2.getCharge()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String xmlString = readFile(testDegradedFile); + Pair<String, ? extends CellDesignerSpecies<?>> result = parser.parseXmlElement(xmlString); + CellDesignerDegraded species = (CellDesignerDegraded) result.getRight(); + + String transformedXml = parser.toXml(species.createModelElement()); + assertNotNull(transformedXml); + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + DocumentBuilder builder = factory.newDocumentBuilder(); + InputSource is = new InputSource(new StringReader(transformedXml)); + Document doc = builder.parse(is); + NodeList root = doc.getChildNodes(); + assertEquals("species", root.item(0).getNodeName()); + + Pair<String, ? extends CellDesignerSpecies<?>> result2 = parser + .parseXmlElement(parser.toXml(species.createModelElement())); + CellDesignerDegraded species2 = (CellDesignerDegraded) result2.getRight(); + + assertNotNull(species2); + assertEquals(species.getName(), species2.getName()); + assertEquals(species.getParent(), species2.getParent()); + assertEquals(species.getInitialAmount(), species2.getInitialAmount()); + assertEquals(species.hasOnlySubstanceUnits(), species2.hasOnlySubstanceUnits()); + assertEquals(species.getCharge(), species2.getCharge()); } @Test public void testParseXmlSpeciesDrug() throws Exception { - try { - String xmlString = readFile(testDrugFile); - Pair<String, ? extends CellDesignerSpecies<?>> result = parser.parseXmlElement(xmlString); - CellDesignerDrug species = (CellDesignerDrug) result.getRight(); - assertEquals("s6104", species.getElementId()); - assertEquals("geldanamycin", species.getName()); - assertEquals(new Integer(0), species.getCharge()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String xmlString = readFile(testDrugFile); + Pair<String, ? extends CellDesignerSpecies<?>> result = parser.parseXmlElement(xmlString); + CellDesignerDrug species = (CellDesignerDrug) result.getRight(); + assertEquals("s6104", species.getElementId()); + assertEquals("geldanamycin", species.getName()); + assertEquals(new Integer(0), species.getCharge()); } @Test public void testToXmlDrug() throws Exception { - try { - String xmlString = readFile(testDrugFile); - Pair<String, ? extends CellDesignerSpecies<?>> result = parser.parseXmlElement(xmlString); - CellDesignerDrug species = (CellDesignerDrug) result.getRight(); - - String transformedXml = parser.toXml(species.createModelElement()); - assertNotNull(transformedXml); - DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); - DocumentBuilder builder = factory.newDocumentBuilder(); - InputSource is = new InputSource(new StringReader(transformedXml)); - Document doc = builder.parse(is); - NodeList root = doc.getChildNodes(); - assertEquals("species", root.item(0).getNodeName()); - - Pair<String, ? extends CellDesignerSpecies<?>> result2 = parser - .parseXmlElement(parser.toXml(species.createModelElement())); - CellDesignerDrug species2 = (CellDesignerDrug) result2.getRight(); - - assertNotNull(species2); - assertEquals(species.getName(), species2.getName()); - assertEquals(species.getParent(), species2.getParent()); - assertEquals(species.getInitialAmount(), species2.getInitialAmount()); - assertEquals(species.hasOnlySubstanceUnits(), species2.hasOnlySubstanceUnits()); - assertEquals(species.getCharge(), species2.getCharge()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String xmlString = readFile(testDrugFile); + Pair<String, ? extends CellDesignerSpecies<?>> result = parser.parseXmlElement(xmlString); + CellDesignerDrug species = (CellDesignerDrug) result.getRight(); + + String transformedXml = parser.toXml(species.createModelElement()); + assertNotNull(transformedXml); + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + DocumentBuilder builder = factory.newDocumentBuilder(); + InputSource is = new InputSource(new StringReader(transformedXml)); + Document doc = builder.parse(is); + NodeList root = doc.getChildNodes(); + assertEquals("species", root.item(0).getNodeName()); + + Pair<String, ? extends CellDesignerSpecies<?>> result2 = parser + .parseXmlElement(parser.toXml(species.createModelElement())); + CellDesignerDrug species2 = (CellDesignerDrug) result2.getRight(); + + assertNotNull(species2); + assertEquals(species.getName(), species2.getName()); + assertEquals(species.getParent(), species2.getParent()); + assertEquals(species.getInitialAmount(), species2.getInitialAmount()); + assertEquals(species.hasOnlySubstanceUnits(), species2.hasOnlySubstanceUnits()); + assertEquals(species.getCharge(), species2.getCharge()); } @Test public void testParseXmlSpeciesGene() throws Exception { - try { - String xmlString = readFile(testGeneFile); - Pair<String, ? extends CellDesignerSpecies<?>> result = parser.parseXmlElement(xmlString); - CellDesignerGene species = (CellDesignerGene) result.getRight(); - - assertEquals("s5916", species.getElementId()); - assertEquals("Ptgr1", species.getName()); - assertEquals(new Integer(0), species.getCharge()); - assertEquals(0, species.getInitialAmount(), Configuration.EPSILON); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String xmlString = readFile(testGeneFile); + Pair<String, ? extends CellDesignerSpecies<?>> result = parser.parseXmlElement(xmlString); + CellDesignerGene species = (CellDesignerGene) result.getRight(); + + assertEquals("s5916", species.getElementId()); + assertEquals("Ptgr1", species.getName()); + assertEquals(new Integer(0), species.getCharge()); + assertEquals(0, species.getInitialAmount(), Configuration.EPSILON); } @Test public void testParseXmlSpeciesGeneWithModelUpdate() throws Exception { - try { - CellDesignerSpecies<?> gene = new CellDesignerGene(); - gene.setElementId("s5916"); - InternalModelSpeciesData modelData = new InternalModelSpeciesData(); - modelData.updateSpecies(gene, ""); - - SpeciesSbmlParser complexParser = new SpeciesSbmlParser(elements); - CellDesignerGene oldGene = new CellDesignerGene(); - oldGene.setElementId("s5916"); - oldGene.setName("Ptgr1"); - modelData.updateSpecies(oldGene, "gn95"); - - String xmlString = readFile(testGeneFile); - Pair<String, ? extends CellDesignerSpecies<?>> result = complexParser.parseXmlElement(xmlString); - CellDesignerGene species = (CellDesignerGene) result.getRight(); - modelData.updateSpecies(species, result.getLeft()); - - assertEquals("s5916", species.getElementId()); - assertEquals("Ptgr1", species.getName()); - assertTrue(species.getNotes().contains("prostaglandin reductase 1")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + CellDesignerSpecies<?> gene = new CellDesignerGene(); + gene.setElementId("s5916"); + InternalModelSpeciesData modelData = new InternalModelSpeciesData(); + modelData.updateSpecies(gene, ""); + + SpeciesSbmlParser complexParser = new SpeciesSbmlParser(elements); + CellDesignerGene oldGene = new CellDesignerGene(); + oldGene.setElementId("s5916"); + oldGene.setName("Ptgr1"); + modelData.updateSpecies(oldGene, "gn95"); + + String xmlString = readFile(testGeneFile); + Pair<String, ? extends CellDesignerSpecies<?>> result = complexParser.parseXmlElement(xmlString); + CellDesignerGene species = (CellDesignerGene) result.getRight(); + modelData.updateSpecies(species, result.getLeft()); + + assertEquals("s5916", species.getElementId()); + assertEquals("Ptgr1", species.getName()); + assertTrue(species.getNotes().contains("prostaglandin reductase 1")); } @Test public void testToXmlGene() throws Exception { - try { - String xmlString = readFile(testGeneFile); - Pair<String, ? extends CellDesignerSpecies<?>> result = parser.parseXmlElement(xmlString); - CellDesignerGene species = (CellDesignerGene) result.getRight(); - - String transformedXml = parser.toXml(species.createModelElement()); - assertNotNull(transformedXml); - DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); - DocumentBuilder builder = factory.newDocumentBuilder(); - InputSource is = new InputSource(new StringReader(transformedXml)); - Document doc = builder.parse(is); - NodeList root = doc.getChildNodes(); - assertEquals("species", root.item(0).getNodeName()); - - Pair<String, ? extends CellDesignerSpecies<?>> result2 = parser - .parseXmlElement(parser.toXml(species.createModelElement())); - CellDesignerGene species2 = (CellDesignerGene) result2.getRight(); - - assertNotNull(species2); - assertEquals(species.getName(), species2.getName()); - assertEquals(species.getParent(), species2.getParent()); - assertEquals(species.getInitialAmount(), species2.getInitialAmount()); - assertEquals(species.hasOnlySubstanceUnits(), species2.hasOnlySubstanceUnits()); - assertEquals(species.getCharge(), species2.getCharge()); - assertTrue(species2.getNotes().trim().contains(species.getNotes().trim())); - assertEquals(species.getMiriamData().size(), species2.getMiriamData().size()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String xmlString = readFile(testGeneFile); + Pair<String, ? extends CellDesignerSpecies<?>> result = parser.parseXmlElement(xmlString); + CellDesignerGene species = (CellDesignerGene) result.getRight(); + + String transformedXml = parser.toXml(species.createModelElement()); + assertNotNull(transformedXml); + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + DocumentBuilder builder = factory.newDocumentBuilder(); + InputSource is = new InputSource(new StringReader(transformedXml)); + Document doc = builder.parse(is); + NodeList root = doc.getChildNodes(); + assertEquals("species", root.item(0).getNodeName()); + + Pair<String, ? extends CellDesignerSpecies<?>> result2 = parser + .parseXmlElement(parser.toXml(species.createModelElement())); + CellDesignerGene species2 = (CellDesignerGene) result2.getRight(); + + assertNotNull(species2); + assertEquals(species.getName(), species2.getName()); + assertEquals(species.getParent(), species2.getParent()); + assertEquals(species.getInitialAmount(), species2.getInitialAmount()); + assertEquals(species.hasOnlySubstanceUnits(), species2.hasOnlySubstanceUnits()); + assertEquals(species.getCharge(), species2.getCharge()); + assertTrue(species2.getNotes().trim().contains(species.getNotes().trim())); + assertEquals(species.getMiriamData().size(), species2.getMiriamData().size()); } @Test public void testParseXmlSpeciesIon() throws Exception { - try { - String xmlString = readFile(testIonFile); - Pair<String, ? extends CellDesignerSpecies<?>> result = parser.parseXmlElement(xmlString); - CellDesignerIon species = (CellDesignerIon) result.getRight(); - - assertEquals("s6029", species.getElementId()); - assertEquals("Pi", species.getName()); - assertEquals(new Integer(0), species.getCharge()); - assertEquals(0, species.getInitialConcentration(), Configuration.EPSILON); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String xmlString = readFile(testIonFile); + Pair<String, ? extends CellDesignerSpecies<?>> result = parser.parseXmlElement(xmlString); + CellDesignerIon species = (CellDesignerIon) result.getRight(); + + assertEquals("s6029", species.getElementId()); + assertEquals("Pi", species.getName()); + assertEquals(new Integer(0), species.getCharge()); + assertEquals(0, species.getInitialConcentration(), Configuration.EPSILON); } @Test public void testToXmlIon() throws Exception { - try { - String xmlString = readFile(testIonFile); - Pair<String, ? extends CellDesignerSpecies<?>> result = parser.parseXmlElement(xmlString); - CellDesignerIon species = (CellDesignerIon) result.getRight(); - - String transformedXml = parser.toXml(species.createModelElement()); - assertNotNull(transformedXml); - DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); - DocumentBuilder builder = factory.newDocumentBuilder(); - InputSource is = new InputSource(new StringReader(transformedXml)); - Document doc = builder.parse(is); - NodeList root = doc.getChildNodes(); - assertEquals("species", root.item(0).getNodeName()); - - Pair<String, ? extends CellDesignerSpecies<?>> result2 = parser.parseXmlElement(xmlString); - CellDesignerIon species2 = (CellDesignerIon) result2.getRight(); - - assertNotNull(species2); - assertEquals(species.getElementId(), species2.getElementId()); - assertEquals(species.getName(), species2.getName()); - assertEquals(species.getParent(), species2.getParent()); - assertEquals(species.getInitialAmount(), species2.getInitialAmount()); - assertEquals(species.hasOnlySubstanceUnits(), species2.hasOnlySubstanceUnits()); - assertEquals(species.getCharge(), species2.getCharge()); - assertEquals(species.getInitialConcentration(), species2.getInitialConcentration()); - assertEquals(species.getNotes().trim(), species2.getNotes().trim()); - assertEquals(species.getMiriamData().size(), species2.getMiriamData().size()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String xmlString = readFile(testIonFile); + Pair<String, ? extends CellDesignerSpecies<?>> result = parser.parseXmlElement(xmlString); + CellDesignerIon species = (CellDesignerIon) result.getRight(); + + String transformedXml = parser.toXml(species.createModelElement()); + assertNotNull(transformedXml); + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + DocumentBuilder builder = factory.newDocumentBuilder(); + InputSource is = new InputSource(new StringReader(transformedXml)); + Document doc = builder.parse(is); + NodeList root = doc.getChildNodes(); + assertEquals("species", root.item(0).getNodeName()); + + Pair<String, ? extends CellDesignerSpecies<?>> result2 = parser.parseXmlElement(xmlString); + CellDesignerIon species2 = (CellDesignerIon) result2.getRight(); + + assertNotNull(species2); + assertEquals(species.getElementId(), species2.getElementId()); + assertEquals(species.getName(), species2.getName()); + assertEquals(species.getParent(), species2.getParent()); + assertEquals(species.getInitialAmount(), species2.getInitialAmount()); + assertEquals(species.hasOnlySubstanceUnits(), species2.hasOnlySubstanceUnits()); + assertEquals(species.getCharge(), species2.getCharge()); + assertEquals(species.getInitialConcentration(), species2.getInitialConcentration()); + assertEquals(species.getNotes().trim(), species2.getNotes().trim()); + assertEquals(species.getMiriamData().size(), species2.getMiriamData().size()); } @Test public void testParseXmlSpeciesPhenotype() throws Exception { - try { - String xmlString = readFile(testPhenotypeFile); - Pair<String, ? extends CellDesignerSpecies<?>> result = parser.parseXmlElement(xmlString); - CellDesignerPhenotype species = (CellDesignerPhenotype) result.getRight(); - - assertEquals("s5462", species.getElementId()); - assertEquals("Neuronal damage and death", species.getName()); - assertEquals(0, species.getInitialAmount(), Configuration.EPSILON); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String xmlString = readFile(testPhenotypeFile); + Pair<String, ? extends CellDesignerSpecies<?>> result = parser.parseXmlElement(xmlString); + CellDesignerPhenotype species = (CellDesignerPhenotype) result.getRight(); + + assertEquals("s5462", species.getElementId()); + assertEquals("Neuronal damage and death", species.getName()); + assertEquals(0, species.getInitialAmount(), Configuration.EPSILON); } @Test public void testToXmlPhenotype() throws Exception { - try { - String xmlString = readFile(testPhenotypeFile); - Pair<String, ? extends CellDesignerSpecies<?>> result = parser.parseXmlElement(xmlString); - CellDesignerPhenotype species = (CellDesignerPhenotype) result.getRight(); - - String transformedXml = parser.toXml(species.createModelElement()); - assertNotNull(transformedXml); - DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); - DocumentBuilder builder = factory.newDocumentBuilder(); - InputSource is = new InputSource(new StringReader(transformedXml)); - Document doc = builder.parse(is); - NodeList root = doc.getChildNodes(); - assertEquals("species", root.item(0).getNodeName()); - - Pair<String, ? extends CellDesignerSpecies<?>> result2 = parser - .parseXmlElement(parser.toXml(species.createModelElement())); - CellDesignerPhenotype species2 = (CellDesignerPhenotype) result2.getRight(); - - assertNotNull(species2); - assertEquals(species.getName(), species2.getName()); - assertEquals(species.getParent(), species2.getParent()); - assertEquals(species.getInitialAmount(), species2.getInitialAmount()); - assertEquals(species.hasOnlySubstanceUnits(), species2.hasOnlySubstanceUnits()); - assertEquals(species.getCharge(), species2.getCharge()); - assertEquals(species.getInitialConcentration(), species2.getInitialConcentration()); - assertEquals(species.getNotes(), species2.getNotes()); - assertEquals(species.getMiriamData().size(), species2.getMiriamData().size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String xmlString = readFile(testPhenotypeFile); + Pair<String, ? extends CellDesignerSpecies<?>> result = parser.parseXmlElement(xmlString); + CellDesignerPhenotype species = (CellDesignerPhenotype) result.getRight(); + + String transformedXml = parser.toXml(species.createModelElement()); + assertNotNull(transformedXml); + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + DocumentBuilder builder = factory.newDocumentBuilder(); + InputSource is = new InputSource(new StringReader(transformedXml)); + Document doc = builder.parse(is); + NodeList root = doc.getChildNodes(); + assertEquals("species", root.item(0).getNodeName()); + + Pair<String, ? extends CellDesignerSpecies<?>> result2 = parser + .parseXmlElement(parser.toXml(species.createModelElement())); + CellDesignerPhenotype species2 = (CellDesignerPhenotype) result2.getRight(); + + assertNotNull(species2); + assertEquals(species.getName(), species2.getName()); + assertEquals(species.getParent(), species2.getParent()); + assertEquals(species.getInitialAmount(), species2.getInitialAmount()); + assertEquals(species.hasOnlySubstanceUnits(), species2.hasOnlySubstanceUnits()); + assertEquals(species.getCharge(), species2.getCharge()); + assertEquals(species.getInitialConcentration(), species2.getInitialConcentration()); + assertEquals(species.getNotes(), species2.getNotes()); + assertEquals(species.getMiriamData().size(), species2.getMiriamData().size()); } @Test public void testParseXmlSpeciesProtein() throws Exception { - try { - String xmlString = readFile(testProteinFile); - Pair<String, ? extends CellDesignerSpecies<?>> result = parser.parseXmlElement(xmlString); - CellDesignerProtein<?> species = (CellDesignerProtein<?>) result.getRight(); - - assertEquals("s5456", species.getElementId()); - assertEquals("PTPRC", species.getName()); - assertEquals(0, species.getInitialAmount(), Configuration.EPSILON); - assertEquals(new Integer(0), species.getCharge()); - assertTrue(species.getNotes().contains("protein tyrosine phosphatase, receptor type, C")); - assertNull(species.getStructuralState()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String xmlString = readFile(testProteinFile); + Pair<String, ? extends CellDesignerSpecies<?>> result = parser.parseXmlElement(xmlString); + CellDesignerProtein<?> species = (CellDesignerProtein<?>) result.getRight(); + + assertEquals("s5456", species.getElementId()); + assertEquals("PTPRC", species.getName()); + assertEquals(0, species.getInitialAmount(), Configuration.EPSILON); + assertEquals(new Integer(0), species.getCharge()); + assertTrue(species.getNotes().contains("protein tyrosine phosphatase, receptor type, C")); + assertNull(species.getStructuralState()); } @Test public void testToXmlProtein() throws Exception { - try { - String xmlString = readFile(testProteinFile); - Pair<String, ? extends CellDesignerSpecies<?>> result = parser.parseXmlElement(xmlString); - CellDesignerGenericProtein species = new CellDesignerGenericProtein(result.getRight()); - - String transformedXml = parser.toXml(species.createModelElement("" + idCounter++)); - assertNotNull(transformedXml); - DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); - DocumentBuilder builder = factory.newDocumentBuilder(); - InputSource is = new InputSource(new StringReader(transformedXml)); - Document doc = builder.parse(is); - NodeList root = doc.getChildNodes(); - assertEquals("species", root.item(0).getNodeName()); - - Pair<String, ? extends CellDesignerSpecies<?>> result2 = parser - .parseXmlElement(parser.toXml(species.createModelElement("" + idCounter++))); - CellDesignerProtein<?> species2 = (CellDesignerProtein<?>) result2.getRight(); - - assertNotNull(species2); - assertEquals(species.getName(), species2.getName()); - assertEquals(species.getParent(), species2.getParent()); - assertEquals(species.getInitialAmount(), species2.getInitialAmount()); - assertEquals(species.hasOnlySubstanceUnits(), species2.hasOnlySubstanceUnits()); - assertEquals(species.getCharge(), species2.getCharge()); - assertEquals(species.getInitialConcentration(), species2.getInitialConcentration()); - assertTrue(species2.getNotes().contains(species.getNotes())); - assertEquals(species.getMiriamData().size(), species2.getMiriamData().size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String xmlString = readFile(testProteinFile); + Pair<String, ? extends CellDesignerSpecies<?>> result = parser.parseXmlElement(xmlString); + CellDesignerGenericProtein species = new CellDesignerGenericProtein(result.getRight()); + + String transformedXml = parser.toXml(species.createModelElement("" + idCounter++)); + assertNotNull(transformedXml); + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + DocumentBuilder builder = factory.newDocumentBuilder(); + InputSource is = new InputSource(new StringReader(transformedXml)); + Document doc = builder.parse(is); + NodeList root = doc.getChildNodes(); + assertEquals("species", root.item(0).getNodeName()); + + Pair<String, ? extends CellDesignerSpecies<?>> result2 = parser + .parseXmlElement(parser.toXml(species.createModelElement("" + idCounter++))); + CellDesignerProtein<?> species2 = (CellDesignerProtein<?>) result2.getRight(); + + assertNotNull(species2); + assertEquals(species.getName(), species2.getName()); + assertEquals(species.getParent(), species2.getParent()); + assertEquals(species.getInitialAmount(), species2.getInitialAmount()); + assertEquals(species.hasOnlySubstanceUnits(), species2.hasOnlySubstanceUnits()); + assertEquals(species.getCharge(), species2.getCharge()); + assertEquals(species.getInitialConcentration(), species2.getInitialConcentration()); + assertTrue(species2.getNotes().contains(species.getNotes())); + assertEquals(species.getMiriamData().size(), species2.getMiriamData().size()); } @Test public void testParseXmlSpeciesRna() throws Exception { - try { - String xmlString = readFile(testRnaFile); - Pair<String, ? extends CellDesignerSpecies<?>> result = parser.parseXmlElement(xmlString); - CellDesignerRna species = (CellDesignerRna) result.getRight(); - - assertEquals("s5914", species.getElementId()); - assertEquals("Fmo3", species.getName()); - assertEquals(0, species.getInitialAmount(), Configuration.EPSILON); - assertEquals(new Integer(0), species.getCharge()); - assertTrue(species.getNotes().contains("Dimethylaniline monooxygenase [N-oxide-forming] 3")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String xmlString = readFile(testRnaFile); + Pair<String, ? extends CellDesignerSpecies<?>> result = parser.parseXmlElement(xmlString); + CellDesignerRna species = (CellDesignerRna) result.getRight(); + + assertEquals("s5914", species.getElementId()); + assertEquals("Fmo3", species.getName()); + assertEquals(0, species.getInitialAmount(), Configuration.EPSILON); + assertEquals(new Integer(0), species.getCharge()); + assertTrue(species.getNotes().contains("Dimethylaniline monooxygenase [N-oxide-forming] 3")); } @Test public void testToXmlRna() throws Exception { - try { - String xmlString = readFile(testRnaFile); - Pair<String, ? extends CellDesignerSpecies<?>> result = parser.parseXmlElement(xmlString); - CellDesignerRna species = (CellDesignerRna) result.getRight(); - - String transformedXml = parser.toXml(species.createModelElement()); - assertNotNull(transformedXml); - DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); - DocumentBuilder builder = factory.newDocumentBuilder(); - InputSource is = new InputSource(new StringReader(transformedXml)); - Document doc = builder.parse(is); - NodeList root = doc.getChildNodes(); - assertEquals("species", root.item(0).getNodeName()); - - Pair<String, ? extends CellDesignerSpecies<?>> result2 = parser - .parseXmlElement(parser.toXml(species.createModelElement())); - CellDesignerRna species2 = (CellDesignerRna) result2.getRight(); - - assertNotNull(species2); - assertEquals(species.getName(), species2.getName()); - assertEquals(species.getParent(), species2.getParent()); - assertEquals(species.getInitialAmount(), species2.getInitialAmount()); - assertEquals(species.hasOnlySubstanceUnits(), species2.hasOnlySubstanceUnits()); - assertEquals(species.getCharge(), species2.getCharge()); - assertEquals(species.getInitialConcentration(), species2.getInitialConcentration()); - assertTrue(species2.getNotes().trim().contains(species.getNotes().trim())); - assertEquals(species.getMiriamData().size(), species2.getMiriamData().size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String xmlString = readFile(testRnaFile); + Pair<String, ? extends CellDesignerSpecies<?>> result = parser.parseXmlElement(xmlString); + CellDesignerRna species = (CellDesignerRna) result.getRight(); + + String transformedXml = parser.toXml(species.createModelElement()); + assertNotNull(transformedXml); + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + DocumentBuilder builder = factory.newDocumentBuilder(); + InputSource is = new InputSource(new StringReader(transformedXml)); + Document doc = builder.parse(is); + NodeList root = doc.getChildNodes(); + assertEquals("species", root.item(0).getNodeName()); + + Pair<String, ? extends CellDesignerSpecies<?>> result2 = parser + .parseXmlElement(parser.toXml(species.createModelElement())); + CellDesignerRna species2 = (CellDesignerRna) result2.getRight(); + + assertNotNull(species2); + assertEquals(species.getName(), species2.getName()); + assertEquals(species.getParent(), species2.getParent()); + assertEquals(species.getInitialAmount(), species2.getInitialAmount()); + assertEquals(species.hasOnlySubstanceUnits(), species2.hasOnlySubstanceUnits()); + assertEquals(species.getCharge(), species2.getCharge()); + assertEquals(species.getInitialConcentration(), species2.getInitialConcentration()); + assertTrue(species2.getNotes().trim().contains(species.getNotes().trim())); + assertEquals(species.getMiriamData().size(), species2.getMiriamData().size()); } @Test public void testParseXmlSpeciesSimpleMolecule() throws Exception { - try { - String xmlString = readFile(testSimpleMoleculeFile); - Pair<String, ? extends CellDesignerSpecies<?>> result = parser.parseXmlElement(xmlString); - CellDesignerSimpleMolecule species = (CellDesignerSimpleMolecule) result.getRight(); - assertEquals("s5463", species.getElementId()); - assertEquals("Peroxides", species.getName()); - assertEquals(0, species.getInitialAmount(), Configuration.EPSILON); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String xmlString = readFile(testSimpleMoleculeFile); + Pair<String, ? extends CellDesignerSpecies<?>> result = parser.parseXmlElement(xmlString); + CellDesignerSimpleMolecule species = (CellDesignerSimpleMolecule) result.getRight(); + assertEquals("s5463", species.getElementId()); + assertEquals("Peroxides", species.getName()); + assertEquals(0, species.getInitialAmount(), Configuration.EPSILON); } @Test public void testToXmlSimpleMolecule() throws Exception { - try { - String xmlString = readFile(testSimpleMoleculeFile); - Pair<String, ? extends CellDesignerSpecies<?>> result = parser.parseXmlElement(xmlString); - CellDesignerSimpleMolecule species = (CellDesignerSimpleMolecule) result.getRight(); - - String transformedXml = parser.toXml(species.createModelElement("" + idCounter++)); - assertNotNull(transformedXml); - DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); - DocumentBuilder builder = factory.newDocumentBuilder(); - InputSource is = new InputSource(new StringReader(transformedXml)); - Document doc = builder.parse(is); - NodeList root = doc.getChildNodes(); - assertEquals("species", root.item(0).getNodeName()); - - Pair<String, ? extends CellDesignerSpecies<?>> result2 = parser - .parseXmlElement(parser.toXml(species.createModelElement("" + idCounter++))); - CellDesignerSimpleMolecule species2 = (CellDesignerSimpleMolecule) result2.getRight(); - - assertNotNull(species2); - assertEquals(species.getName(), species2.getName()); - assertEquals(species.getParent(), species2.getParent()); - assertEquals(species.getInitialAmount(), species2.getInitialAmount()); - assertEquals(species.hasOnlySubstanceUnits(), species2.hasOnlySubstanceUnits()); - assertEquals(species.getCharge(), species2.getCharge()); - assertEquals(species.getInitialConcentration(), species2.getInitialConcentration()); - assertEquals(species.getNotes(), species2.getNotes()); - assertEquals(species.getMiriamData().size(), species2.getMiriamData().size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String xmlString = readFile(testSimpleMoleculeFile); + Pair<String, ? extends CellDesignerSpecies<?>> result = parser.parseXmlElement(xmlString); + CellDesignerSimpleMolecule species = (CellDesignerSimpleMolecule) result.getRight(); + + String transformedXml = parser.toXml(species.createModelElement("" + idCounter++)); + assertNotNull(transformedXml); + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + DocumentBuilder builder = factory.newDocumentBuilder(); + InputSource is = new InputSource(new StringReader(transformedXml)); + Document doc = builder.parse(is); + NodeList root = doc.getChildNodes(); + assertEquals("species", root.item(0).getNodeName()); + + Pair<String, ? extends CellDesignerSpecies<?>> result2 = parser + .parseXmlElement(parser.toXml(species.createModelElement("" + idCounter++))); + CellDesignerSimpleMolecule species2 = (CellDesignerSimpleMolecule) result2.getRight(); + + assertNotNull(species2); + assertEquals(species.getName(), species2.getName()); + assertEquals(species.getParent(), species2.getParent()); + assertEquals(species.getInitialAmount(), species2.getInitialAmount()); + assertEquals(species.hasOnlySubstanceUnits(), species2.hasOnlySubstanceUnits()); + assertEquals(species.getCharge(), species2.getCharge()); + assertEquals(species.getInitialConcentration(), species2.getInitialConcentration()); + assertEquals(species.getNotes(), species2.getNotes()); + assertEquals(species.getMiriamData().size(), species2.getMiriamData().size()); } @Test public void testParseXmlSpeciesUnknown() throws Exception { - try { - String xmlString = readFile(testUnknownFile); - Pair<String, ? extends CellDesignerSpecies<?>> result = parser.parseXmlElement(xmlString); - CellDesignerUnknown species = (CellDesignerUnknown) result.getRight(); - assertEquals("s1356", species.getElementId()); - assertEquals("unidentified caspase acting on Occludin", species.getName()); - assertEquals(0, species.getInitialAmount(), Configuration.EPSILON); - assertEquals(new Integer(0), species.getCharge()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String xmlString = readFile(testUnknownFile); + Pair<String, ? extends CellDesignerSpecies<?>> result = parser.parseXmlElement(xmlString); + CellDesignerUnknown species = (CellDesignerUnknown) result.getRight(); + assertEquals("s1356", species.getElementId()); + assertEquals("unidentified caspase acting on Occludin", species.getName()); + assertEquals(0, species.getInitialAmount(), Configuration.EPSILON); + assertEquals(new Integer(0), species.getCharge()); } @Test public void testToXmlUnknown() throws Exception { - try { - String xmlString = readFile(testUnknownFile); - Pair<String, ? extends CellDesignerSpecies<?>> result = parser.parseXmlElement(xmlString); - CellDesignerUnknown species = (CellDesignerUnknown) result.getRight(); - - String transformedXml = parser.toXml(species.createModelElement()); - assertNotNull(transformedXml); - DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); - DocumentBuilder builder = factory.newDocumentBuilder(); - InputSource is = new InputSource(new StringReader(transformedXml)); - Document doc = builder.parse(is); - NodeList root = doc.getChildNodes(); - assertEquals("species", root.item(0).getNodeName()); - - Pair<String, ? extends CellDesignerSpecies<?>> result2 = parser - .parseXmlElement(parser.toXml(species.createModelElement())); - CellDesignerUnknown species2 = (CellDesignerUnknown) result2.getRight(); - - assertNotNull(species2); - assertEquals(species.getName(), species2.getName()); - assertEquals(species.getParent(), species2.getParent()); - assertEquals(species.getInitialAmount(), species2.getInitialAmount()); - assertEquals(species.hasOnlySubstanceUnits(), species2.hasOnlySubstanceUnits()); - assertEquals(species.getCharge(), species2.getCharge()); - assertEquals(species.getInitialConcentration(), species2.getInitialConcentration()); - assertEquals(species.getNotes(), species2.getNotes()); - assertEquals(species.getMiriamData().size(), species2.getMiriamData().size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test + String xmlString = readFile(testUnknownFile); + Pair<String, ? extends CellDesignerSpecies<?>> result = parser.parseXmlElement(xmlString); + CellDesignerUnknown species = (CellDesignerUnknown) result.getRight(); + + String transformedXml = parser.toXml(species.createModelElement()); + assertNotNull(transformedXml); + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + DocumentBuilder builder = factory.newDocumentBuilder(); + InputSource is = new InputSource(new StringReader(transformedXml)); + Document doc = builder.parse(is); + NodeList root = doc.getChildNodes(); + assertEquals("species", root.item(0).getNodeName()); + + Pair<String, ? extends CellDesignerSpecies<?>> result2 = parser + .parseXmlElement(parser.toXml(species.createModelElement())); + CellDesignerUnknown species2 = (CellDesignerUnknown) result2.getRight(); + + assertNotNull(species2); + assertEquals(species.getName(), species2.getName()); + assertEquals(species.getParent(), species2.getParent()); + assertEquals(species.getInitialAmount(), species2.getInitialAmount()); + assertEquals(species.hasOnlySubstanceUnits(), species2.hasOnlySubstanceUnits()); + assertEquals(species.getCharge(), species2.getCharge()); + assertEquals(species.getInitialConcentration(), species2.getInitialConcentration()); + assertEquals(species.getNotes(), species2.getNotes()); + assertEquals(species.getMiriamData().size(), species2.getMiriamData().size()); + } + + @Test(expected = InvalidXmlSchemaException.class) public void testParseInvalid() throws Exception { - try { - String xmlString = readFile("testFiles/invalid/invalid_sbml_protein.xml"); - parser.parseXmlElement(xmlString); - fail("Exception expected"); - } catch (InvalidXmlSchemaException e) { - assertTrue(e.getMessage().contains("No annotation node")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String xmlString = readFile("testFiles/invalid/invalid_sbml_protein.xml"); + parser.parseXmlElement(xmlString); } - @Test + @Test(expected = InvalidXmlSchemaException.class) public void testParseInvalid2() throws Exception { - try { - String xmlString = readFile("testFiles/invalid/invalid_sbml_protein2.xml"); - parser.parseXmlElement(xmlString); - fail("Exception expected"); - } catch (InvalidXmlSchemaException e) { - assertTrue(e.getMessage().contains("bla")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String xmlString = readFile("testFiles/invalid/invalid_sbml_protein2.xml"); + parser.parseXmlElement(xmlString); } - @Test + @Test(expected = InvalidXmlSchemaException.class) public void testParseInvalid3() throws Exception { - try { - String xmlString = readFile("testFiles/invalid/invalid_sbml_protein3.xml"); - parser.parseXmlElement(xmlString); - fail("Exception expected"); - } catch (InvalidXmlSchemaException e) { - assertTrue(e.getMessage().contains("unk_bla")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String xmlString = readFile("testFiles/invalid/invalid_sbml_protein3.xml"); + parser.parseXmlElement(xmlString); } - @Test + @Test(expected = InvalidXmlSchemaException.class) public void testParseInvalid4() throws Exception { - try { - String xmlString = readFile("testFiles/invalid/invalid_sbml_protein4.xml"); - parser.parseXmlElement(xmlString); - fail("Exception expected"); - } catch (InvalidXmlSchemaException e) { - assertTrue(e.getMessage().contains("No celldesigner:extension")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String xmlString = readFile("testFiles/invalid/invalid_sbml_protein4.xml"); + parser.parseXmlElement(xmlString); } - @Test + @Test(expected = InvalidXmlSchemaException.class) public void testParseInvalid5() throws Exception { - try { - String xmlString = readFile("testFiles/invalid/invalid_sbml_protein5.xml"); - parser.parseXmlElement(xmlString); - fail("Exception expected"); - } catch (InvalidXmlSchemaException e) { - assertTrue(e.getMessage().contains("ann_unk")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String xmlString = readFile("testFiles/invalid/invalid_sbml_protein5.xml"); + parser.parseXmlElement(xmlString); } - @Test + @Test(expected = InvalidXmlSchemaException.class) public void testParseInvalid6() throws Exception { - try { - String xmlString = readFile("testFiles/invalid/invalid_sbml_protein6.xml"); - parser.parseXmlElement(xmlString); - fail("Exception expected"); - } catch (InvalidXmlSchemaException e) { - assertTrue(e.getMessage().contains("No celldesigner:speciesIdentity")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String xmlString = readFile("testFiles/invalid/invalid_sbml_protein6.xml"); + parser.parseXmlElement(xmlString); } - @Test + @Test(expected = InvalidXmlSchemaException.class) public void testParseInvalid7() throws Exception { - try { - String xmlString = readFile("testFiles/invalid/invalid_sbml_protein7.xml"); - parser.parseXmlElement(xmlString); - fail("Exception expected"); - } catch (InvalidXmlSchemaException e) { - assertTrue(e.getMessage().contains("unkPos")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String xmlString = readFile("testFiles/invalid/invalid_sbml_protein7.xml"); + parser.parseXmlElement(xmlString); } - @Test + @Test(expected = InvalidXmlSchemaException.class) public void testParseInvalid8() throws Exception { - try { - String xmlString = readFile("testFiles/invalid/invalid_sbml_protein8.xml"); - parser.parseXmlElement(xmlString); - fail("Exception expected"); - } catch (InvalidXmlSchemaException e) { - assertTrue(e.getMessage().contains("Species node in Sbml model doesn't contain")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String xmlString = readFile("testFiles/invalid/invalid_sbml_protein8.xml"); + parser.parseXmlElement(xmlString); } - @Test + @Test(expected = InvalidXmlSchemaException.class) public void testParseInvalid9() throws Exception { - try { - String xmlString = readFile("testFiles/invalid/invalid_sbml_protein9.xml"); - parser.parseXmlElement(xmlString); - fail("Exception expected"); - } catch (InvalidXmlSchemaException e) { - assertTrue(e.getMessage().contains("unknown_protein_class")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String xmlString = readFile("testFiles/invalid/invalid_sbml_protein9.xml"); + parser.parseXmlElement(xmlString); } - @Test + @Test(expected = InvalidXmlSchemaException.class) public void testParseInvalid10() throws Exception { - try { - String xmlString = readFile("testFiles/invalid/invalid_sbml_protein10.xml"); - parser.parseXmlElement(xmlString); - fail("Exception expected"); - } catch (InvalidXmlSchemaException e) { - assertTrue(e.getMessage().contains("Wrong class type for protein reference")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String xmlString = readFile("testFiles/invalid/invalid_sbml_protein10.xml"); + parser.parseXmlElement(xmlString); } - @Test + @Test(expected = InvalidXmlSchemaException.class) public void testParseInvalid11() throws Exception { - try { - String xmlString = readFile("testFiles/invalid/invalid_sbml_protein11.xml"); - parser.parseXmlElement(xmlString); - fail("Exception expected"); - } catch (InvalidXmlSchemaException e) { - assertTrue(e.getMessage().contains("Wrong class type for gene reference")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String xmlString = readFile("testFiles/invalid/invalid_sbml_protein11.xml"); + parser.parseXmlElement(xmlString); } - @Test + @Test(expected = InvalidXmlSchemaException.class) public void testParseInvalid12() throws Exception { - try { - String xmlString = readFile("testFiles/invalid/invalid_sbml_protein12.xml"); - parser.parseXmlElement(xmlString); - fail("Exception expected"); - } catch (InvalidXmlSchemaException e) { - assertTrue(e.getMessage().contains("Wrong class type for rna reference")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String xmlString = readFile("testFiles/invalid/invalid_sbml_protein12.xml"); + parser.parseXmlElement(xmlString); } - @Test + @Test(expected = InvalidXmlSchemaException.class) public void testParseInvalid13() throws Exception { - try { - String xmlString = readFile("testFiles/invalid/invalid_sbml_protein13.xml"); - parser.parseXmlElement(xmlString); - fail("Exception expected"); - } catch (InvalidXmlSchemaException e) { - assertTrue(e.getMessage().contains("Wrong class type for antisense rna reference")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String xmlString = readFile("testFiles/invalid/invalid_sbml_protein13.xml"); + parser.parseXmlElement(xmlString); } - @Test + @Test(expected = InvalidXmlSchemaException.class) public void testParseInvalid14() throws Exception { - try { - String xmlString = readFile("testFiles/invalid/invalid_sbml_protein14.xml"); - parser.parseXmlElement(xmlString); - fail("Exception expected"); - } catch (InvalidXmlSchemaException e) { - assertTrue(e.getMessage().contains("uknNode")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String xmlString = readFile("testFiles/invalid/invalid_sbml_protein14.xml"); + parser.parseXmlElement(xmlString); } @Test public void testToXmlWithDefaultCompartment() throws Exception { - try { - CellDesignerGenericProtein species = new CellDesignerGenericProtein(); - String xml = parser.toXml(species.createModelElement("EL_ID")); - assertTrue(xml.contains("EL_ID")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + CellDesignerGenericProtein species = new CellDesignerGenericProtein(); + String xml = parser.toXml(species.createModelElement("EL_ID")); + assertTrue(xml.contains("EL_ID")); } - @Test + @Test(expected = InvalidArgumentException.class) public void testInvalidSpeciesIdentityToXml() throws Exception { - try { - Species species = Mockito.mock(Species.class); - parser.speciesIdentityToXml(species); - fail("Excepiton expected"); - } catch (InvalidArgumentException e) { - assertTrue(e.getMessage().contains("Invalid species class")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Species species = Mockito.mock(Species.class); + parser.speciesIdentityToXml(species); } @Test public void testSpeciesIdentityToXml() throws Exception { - try { - GenericProtein species = new GenericProtein("xx"); - species.setHypothetical(true); - String xml = parser.speciesIdentityToXml(species); - assertTrue(xml.contains("<celldesigner:hypothetical>true</celldesigner:hypothetical>")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + GenericProtein species = new GenericProtein("xx"); + species.setHypothetical(true); + String xml = parser.speciesIdentityToXml(species); + assertTrue(xml.contains("<celldesigner:hypothetical>true</celldesigner:hypothetical>")); } @Test public void testSpeciesStateToXml() throws Exception { - try { - SpeciesState state = new SpeciesState(); - state.setHomodimer(2); - state.setStructuralState("xxxState"); - String xml = parser.speciesStateToXml(state); - assertTrue(xml.contains("xxxState")); - assertTrue(xml.contains("celldesigner:homodimer")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + SpeciesState state = new SpeciesState(); + state.setHomodimer(2); + state.setStructuralState("xxxState"); + String xml = parser.speciesStateToXml(state); + assertTrue(xml.contains("xxxState")); + assertTrue(xml.contains("celldesigner:homodimer")); } - @Test + @Test(expected = NotImplementedException.class) public void testProcessInvalidStateDataInSpecies() throws Exception { - try { - SpeciesState state = new SpeciesState(); - state.addModificationResidue(new CellDesignerModificationResidue()); - CellDesignerComplexSpecies species = new CellDesignerComplexSpecies(); - - parser.processStateDataInSpecies(species, state); - fail("Exception expected"); - } catch (NotImplementedException e) { - assertTrue(e.getMessage().contains("Modification not supported in Complex")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + SpeciesState state = new SpeciesState(); + state.addModificationResidue(new CellDesignerModificationResidue()); + CellDesignerComplexSpecies species = new CellDesignerComplexSpecies(); + + parser.processStateDataInSpecies(species, state); } - @Test + @Test(expected = NotImplementedException.class) public void testProcessInvalidStateDataInSpecies2() throws Exception { - try { - SpeciesState state = new SpeciesState(); - state.setStructuralState("state"); - CellDesignerGene species = new CellDesignerGene(); - - parser.processStateDataInSpecies(species, state); - fail("Exception expected"); - } catch (NotImplementedException e) { - assertTrue(e.getMessage().contains("StructuralState not supported in Gene")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + SpeciesState state = new SpeciesState(); + state.setStructuralState("state"); + CellDesignerGene species = new CellDesignerGene(); + + parser.processStateDataInSpecies(species, state); } - @Test + @Test(expected = NotImplementedException.class) public void testProcessInvalidStateDataInSpecies3() throws Exception { - try { - SpeciesState state = new SpeciesState(); - state.setStructuralState("state"); - CellDesignerRna species = new CellDesignerRna(); - - parser.processStateDataInSpecies(species, state); - fail("Exception expected"); - } catch (NotImplementedException e) { - assertTrue(e.getMessage().contains("Structural state not supported in RNA")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + SpeciesState state = new SpeciesState(); + state.setStructuralState("state"); + CellDesignerRna species = new CellDesignerRna(); + + parser.processStateDataInSpecies(species, state); } - @Test + @Test(expected = NotImplementedException.class) public void testProcessInvalidStateDataInSpecies4() throws Exception { - try { - SpeciesState state = new SpeciesState(); - state.addModificationResidue(new CellDesignerModificationResidue()); - CellDesignerSimpleMolecule species = new CellDesignerSimpleMolecule(); - - parser.processStateDataInSpecies(species, state); - fail("Exception expected"); - } catch (NotImplementedException e) { - assertTrue(e.getMessage().contains("Modification not supported in SimpleMolecule")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + SpeciesState state = new SpeciesState(); + state.addModificationResidue(new CellDesignerModificationResidue()); + CellDesignerSimpleMolecule species = new CellDesignerSimpleMolecule(); + + parser.processStateDataInSpecies(species, state); } - @Test + @Test(expected = NotImplementedException.class) public void testProcessInvalidStateDataInSpecies5() throws Exception { - try { - SpeciesState state = new SpeciesState(); - state.setStructuralState("state"); - CellDesignerSimpleMolecule species = new CellDesignerSimpleMolecule(); - - parser.processStateDataInSpecies(species, state); - fail("Exception expected"); - } catch (NotImplementedException e) { - assertTrue(e.getMessage().contains("Structural state not supported in SimpleMolecule")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + SpeciesState state = new SpeciesState(); + state.setStructuralState("state"); + CellDesignerSimpleMolecule species = new CellDesignerSimpleMolecule(); + + parser.processStateDataInSpecies(species, state); } - @Test + @Test(expected = NotImplementedException.class) public void testProcessInvalidStateDataInSpecies6() throws Exception { - try { - SpeciesState state = new SpeciesState(); - state.setStructuralState("state"); - CellDesignerAntisenseRna species = new CellDesignerAntisenseRna(); - - parser.processStateDataInSpecies(species, state); - fail("Exception expected"); - } catch (NotImplementedException e) { - assertTrue(e.getMessage().contains("Structural state not supported in AntisenseRna")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + SpeciesState state = new SpeciesState(); + state.setStructuralState("state"); + CellDesignerAntisenseRna species = new CellDesignerAntisenseRna(); + + parser.processStateDataInSpecies(species, state); } - @Test + @Test(expected = NotImplementedException.class) public void testProcessInvalidStateDataInSpecies7() throws Exception { - try { - SpeciesState state = new SpeciesState(); - state.setStructuralState("state"); - CellDesignerSpecies<?> species = new CellDesignerSpecies<Gene>(); - - parser.processStateDataInSpecies(species, state); - fail("Exception expected"); - } catch (NotImplementedException e) { - assertTrue(e.getMessage().contains("Structural state not supported")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + SpeciesState state = new SpeciesState(); + state.setStructuralState("state"); + CellDesignerSpecies<?> species = new CellDesignerSpecies<Gene>(); + + parser.processStateDataInSpecies(species, state); } - @Test + @Test(expected = NotImplementedException.class) public void testProcessInvalidStateDataInSpecies8() throws Exception { - try { - SpeciesState state = new SpeciesState(); - state.addModificationResidue(new CellDesignerModificationResidue()); - CellDesignerSpecies<?> species = new CellDesignerSpecies<Gene>(); - - parser.processStateDataInSpecies(species, state); - fail("Exception expected"); - } catch (NotImplementedException e) { - assertTrue(e.getMessage().contains("Modification not supported in")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + SpeciesState state = new SpeciesState(); + state.addModificationResidue(new CellDesignerModificationResidue()); + CellDesignerSpecies<?> species = new CellDesignerSpecies<Gene>(); + + parser.processStateDataInSpecies(species, state); } @Test public void testProcessAntisenseRnaStateDataInSpecies() throws Exception { - try { - SpeciesState state = new SpeciesState(); - state.addModificationResidue(new CellDesignerModificationResidue()); - CellDesignerAntisenseRna species = new CellDesignerAntisenseRna(); - - parser.processStateDataInSpecies(species, state); + SpeciesState state = new SpeciesState(); + state.addModificationResidue(new CellDesignerModificationResidue()); + CellDesignerAntisenseRna species = new CellDesignerAntisenseRna(); - assertEquals(1, species.getRegions().size()); + parser.processStateDataInSpecies(species, state); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(1, species.getRegions().size()); } } diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/AntisenseRnaTest.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/AntisenseRnaTest.java index c9cd5cd3f3216ecfe0df7bb2958903555990951e..6afd3ef9050ba56d0c0338a38998e9a3db89103d 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/AntisenseRnaTest.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/AntisenseRnaTest.java @@ -1,25 +1,21 @@ package lcsb.mapviewer.converter.model.celldesigner.structure; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import java.util.ArrayList; import java.util.List; import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.mockito.Mockito; import lcsb.mapviewer.common.exception.NotImplementedException; +import lcsb.mapviewer.converter.model.celldesigner.CellDesignerTestFunctions; import lcsb.mapviewer.converter.model.celldesigner.structure.fields.CellDesignerModificationResidue; import lcsb.mapviewer.model.map.species.AntisenseRna; import lcsb.mapviewer.model.map.species.field.ModificationState; -public class AntisenseRnaTest { +public class AntisenseRnaTest extends CellDesignerTestFunctions { @Before public void setUp() throws Exception { @@ -31,129 +27,92 @@ public class AntisenseRnaTest { @Test public void testSerialization() { - try { - SerializationUtils.serialize(new CellDesignerAntisenseRna()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + SerializationUtils.serialize(new CellDesignerAntisenseRna()); } @Test public void testConstructor1() { - try { - CellDesignerAntisenseRna original = new CellDesignerAntisenseRna(); - original.addRegion(new CellDesignerModificationResidue()); - CellDesignerAntisenseRna aRna = new CellDesignerAntisenseRna(original); - assertNotNull(aRna); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + CellDesignerAntisenseRna original = new CellDesignerAntisenseRna(); + original.addRegion(new CellDesignerModificationResidue()); + CellDesignerAntisenseRna aRna = new CellDesignerAntisenseRna(original); + assertNotNull(aRna); } @Test public void testAddRnaRegion() { - try { - CellDesignerAntisenseRna original = new CellDesignerAntisenseRna(); - CellDesignerModificationResidue region = new CellDesignerModificationResidue(); - region.setIdModificationResidue("id1"); - original.addRegion(region); - - CellDesignerModificationResidue region2 = new CellDesignerModificationResidue(); - region2.setIdModificationResidue("id1"); - region2.setName("nam"); - original.addRegion(region2); - - assertEquals(1, original.getRegions().size()); - - assertEquals("nam", original.getRegions().get(0).getName()); - - CellDesignerModificationResidue region3 = new CellDesignerModificationResidue(); - region3.setIdModificationResidue("id2"); - region3.setName("nam"); - original.addRegion(region3); - - assertEquals(2, original.getRegions().size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + CellDesignerAntisenseRna original = new CellDesignerAntisenseRna(); + CellDesignerModificationResidue region = new CellDesignerModificationResidue(); + region.setIdModificationResidue("id1"); + original.addRegion(region); + + CellDesignerModificationResidue region2 = new CellDesignerModificationResidue(); + region2.setIdModificationResidue("id1"); + region2.setName("nam"); + original.addRegion(region2); + + assertEquals(1, original.getRegions().size()); + + assertEquals("nam", original.getRegions().get(0).getName()); + + CellDesignerModificationResidue region3 = new CellDesignerModificationResidue(); + region3.setIdModificationResidue("id2"); + region3.setName("nam"); + original.addRegion(region3); + + assertEquals(2, original.getRegions().size()); } @Test public void testUpdate() { - try { - CellDesignerAntisenseRna original = new CellDesignerAntisenseRna(); - CellDesignerModificationResidue region2 = new CellDesignerModificationResidue(); - region2.setIdModificationResidue("id1"); - region2.setName("nam"); - original.addRegion(region2); - CellDesignerModificationResidue region3 = new CellDesignerModificationResidue(); - region3.setIdModificationResidue("id2"); - region3.setName("nam"); - original.addRegion(region3); - - CellDesignerAntisenseRna copy = new CellDesignerAntisenseRna(original); - copy.addRegion(new CellDesignerModificationResidue()); - copy.getRegions().get(0).setState(ModificationState.ACETYLATED); - - original.update(copy); - - boolean acetylatedFound = false; - for (CellDesignerModificationResidue region : copy.getRegions()) { - if (ModificationState.ACETYLATED.equals(region.getState())) { - acetylatedFound = true; - } + CellDesignerAntisenseRna original = new CellDesignerAntisenseRna(); + CellDesignerModificationResidue region2 = new CellDesignerModificationResidue(); + region2.setIdModificationResidue("id1"); + region2.setName("nam"); + original.addRegion(region2); + CellDesignerModificationResidue region3 = new CellDesignerModificationResidue(); + region3.setIdModificationResidue("id2"); + region3.setName("nam"); + original.addRegion(region3); + + CellDesignerAntisenseRna copy = new CellDesignerAntisenseRna(original); + copy.addRegion(new CellDesignerModificationResidue()); + copy.getRegions().get(0).setState(ModificationState.ACETYLATED); + + original.update(copy); + + boolean acetylatedFound = false; + for (CellDesignerModificationResidue region : copy.getRegions()) { + if (ModificationState.ACETYLATED.equals(region.getState())) { + acetylatedFound = true; } - assertTrue(acetylatedFound); - assertEquals(3, copy.getRegions().size()); - - original.update(new CellDesignerGenericProtein()); - } catch (Exception e) { - e.printStackTrace(); - throw e; } + assertTrue(acetylatedFound); + assertEquals(3, copy.getRegions().size()); + + original.update(new CellDesignerGenericProtein()); } @Test public void testGetters() { - try { - CellDesignerAntisenseRna aRna = new CellDesignerAntisenseRna(new CellDesignerSpecies<AntisenseRna>()); + CellDesignerAntisenseRna aRna = new CellDesignerAntisenseRna(new CellDesignerSpecies<AntisenseRna>()); - List<CellDesignerModificationResidue> regions = new ArrayList<>(); + List<CellDesignerModificationResidue> regions = new ArrayList<>(); - aRna.setRegions(regions); + aRna.setRegions(regions); - assertEquals(regions, aRna.getRegions()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(regions, aRna.getRegions()); } @Test public void testCopy() { - try { - CellDesignerAntisenseRna aRna = new CellDesignerAntisenseRna().copy(); - assertNotNull(aRna); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + CellDesignerAntisenseRna aRna = new CellDesignerAntisenseRna().copy(); + assertNotNull(aRna); } - @Test + @Test(expected = NotImplementedException.class) public void testInvalidCopy() { - try { - CellDesignerAntisenseRna antisenseRna = Mockito.spy(CellDesignerAntisenseRna.class); - antisenseRna.copy(); - fail("Exception expected"); - } catch (NotImplementedException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + CellDesignerAntisenseRna antisenseRna = Mockito.spy(CellDesignerAntisenseRna.class); + antisenseRna.copy(); } } diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/CompartmentTest.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/CompartmentTest.java index 73935853142201a0a1e33bbb93c3132d12e898ca..d3449a237eb6d7555f831db14785a8c473f4ca81 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/CompartmentTest.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/CompartmentTest.java @@ -1,172 +1,115 @@ package lcsb.mapviewer.converter.model.celldesigner.structure; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.mockito.Mockito; import lcsb.mapviewer.common.exception.NotImplementedException; +import lcsb.mapviewer.converter.model.celldesigner.CellDesignerTestFunctions; -public class CompartmentTest { - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testSerialization() { - try { - SerializationUtils.serialize(new CellDesignerCompartment()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testConstructor1() { - try { - CellDesignerCompartment original = new CellDesignerCompartment(); - original.addElement(new CellDesignerGenericProtein()); - CellDesignerCompartment compartment = new CellDesignerCompartment(original); - assertNotNull(compartment); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testEquals() { - try { - CellDesignerCompartment original = new CellDesignerCompartment(); - original.setName("anme"); - CellDesignerCompartment compartment = new CellDesignerCompartment(original); - CellDesignerCompartment compartment2 = new CellDesignerCompartment(); - - CellDesignerCompartment compartment3 = new CellDesignerCompartment(); - compartment3.setElementId("q"); - - assertEquals(0, compartment.compareTo(original)); - assertTrue(compartment.equals(original)); - - assertEquals(0, compartment.compareTo(compartment)); - assertTrue(compartment.equals(compartment)); - assertTrue(compartment.compareTo(compartment2) != 0); - assertFalse(compartment.equals(compartment2)); - - assertTrue(compartment.compareTo(compartment3) != 0); - - assertFalse(compartment.equals(new Object())); - - assertTrue(compartment.compareTo(null) != 0); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testCopy() { - try { - CellDesignerCompartment compartment = new CellDesignerCompartment().copy(); - assertNotNull(compartment); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testGetters() { - try { - String elementId = "id"; - - CellDesignerCompartment compartment = new CellDesignerCompartment(); - - compartment.setElementId(elementId); - assertEquals(elementId, compartment.getElementId()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testAddElements() { - try { - CellDesignerGenericProtein protein = new CellDesignerGenericProtein(); - - CellDesignerCompartment compartment = new CellDesignerCompartment(); - - assertEquals(0, compartment.getElements().size()); - compartment.addElement(protein); - assertEquals(1, compartment.getElements().size()); - compartment.addElement(protein); - assertEquals(1, compartment.getElements().size()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testHashCode() { - try { - CellDesignerCompartment compartment = new CellDesignerCompartment(); - compartment.setName("name"); - - int code = compartment.hashCode(); - compartment.setName("name2"); - int code2 = compartment.hashCode(); - - assertTrue(code != code2); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testInvalidCopy() { - try { - CellDesignerCompartment compartment = Mockito.spy(CellDesignerCompartment.class); - compartment.copy(); - fail("Exception expected"); - } catch (NotImplementedException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testCreateModelElementWithProblems() { - try { - CellDesignerCompartment compartment = new CellDesignerCompartment(); - compartment.addElement(new CellDesignerAntisenseRna()); - compartment.createModelElement(); - fail("Exception expected"); - } catch (NotImplementedException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } +public class CompartmentTest extends CellDesignerTestFunctions { + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testSerialization() { + SerializationUtils.serialize(new CellDesignerCompartment()); + } + + @Test + public void testConstructor1() { + CellDesignerCompartment original = new CellDesignerCompartment(); + original.addElement(new CellDesignerGenericProtein()); + CellDesignerCompartment compartment = new CellDesignerCompartment(original); + assertNotNull(compartment); + } + + @Test + public void testEquals() { + CellDesignerCompartment original = new CellDesignerCompartment(); + original.setName("anme"); + CellDesignerCompartment compartment = new CellDesignerCompartment(original); + CellDesignerCompartment compartment2 = new CellDesignerCompartment(); + + CellDesignerCompartment compartment3 = new CellDesignerCompartment(); + compartment3.setElementId("q"); + + assertEquals(0, compartment.compareTo(original)); + assertTrue(compartment.equals(original)); + + assertEquals(0, compartment.compareTo(compartment)); + assertTrue(compartment.equals(compartment)); + assertTrue(compartment.compareTo(compartment2) != 0); + assertFalse(compartment.equals(compartment2)); + + assertTrue(compartment.compareTo(compartment3) != 0); + + assertFalse(compartment.equals(new Object())); + + assertTrue(compartment.compareTo(null) != 0); + } + + @Test + public void testCopy() { + CellDesignerCompartment compartment = new CellDesignerCompartment().copy(); + assertNotNull(compartment); + } + + @Test + public void testGetters() { + String elementId = "id"; + + CellDesignerCompartment compartment = new CellDesignerCompartment(); + + compartment.setElementId(elementId); + assertEquals(elementId, compartment.getElementId()); + } + + @Test + public void testAddElements() { + CellDesignerGenericProtein protein = new CellDesignerGenericProtein(); + + CellDesignerCompartment compartment = new CellDesignerCompartment(); + + assertEquals(0, compartment.getElements().size()); + compartment.addElement(protein); + assertEquals(1, compartment.getElements().size()); + compartment.addElement(protein); + assertEquals(1, compartment.getElements().size()); + } + + @Test + public void testHashCode() { + CellDesignerCompartment compartment = new CellDesignerCompartment(); + compartment.setName("name"); + + int code = compartment.hashCode(); + compartment.setName("name2"); + int code2 = compartment.hashCode(); + + assertTrue(code != code2); + + } + + @Test(expected = NotImplementedException.class) + public void testInvalidCopy() { + CellDesignerCompartment compartment = Mockito.spy(CellDesignerCompartment.class); + compartment.copy(); + } + + @Test(expected = NotImplementedException.class) + public void testCreateModelElementWithProblems() { + CellDesignerCompartment compartment = new CellDesignerCompartment(); + compartment.addElement(new CellDesignerAntisenseRna()); + compartment.createModelElement(); + } } diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/ComplexSpeciesTest.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/ComplexSpeciesTest.java index 43b18cfa931343b8bf707eebf61fabddfbc8c9d4..2add8eea61975f4f0a78bdea10b87e69367d112f 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/ComplexSpeciesTest.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/ComplexSpeciesTest.java @@ -1,148 +1,94 @@ package lcsb.mapviewer.converter.model.celldesigner.structure; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import java.util.HashSet; import java.util.Set; import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.mockito.Mockito; import lcsb.mapviewer.common.exception.InvalidArgumentException; import lcsb.mapviewer.common.exception.NotImplementedException; +import lcsb.mapviewer.converter.model.celldesigner.CellDesignerTestFunctions; import lcsb.mapviewer.model.map.species.AntisenseRna; -public class ComplexSpeciesTest { - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testSerialization() { - try { - SerializationUtils.serialize(new CellDesignerComplexSpecies()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testConstructor1() { - try { - CellDesignerComplexSpecies degraded = new CellDesignerComplexSpecies(new CellDesignerSpecies<AntisenseRna>()); - assertNotNull(degraded); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testGetters() { - try { - CellDesignerComplexSpecies species = new CellDesignerComplexSpecies(); - species.addElement(new CellDesignerSpecies<AntisenseRna>()); - CellDesignerComplexSpecies complex = new CellDesignerComplexSpecies(species); - - Set<CellDesignerElement<?>> elements = new HashSet<>(); - complex.setElements(elements); - assertEquals(elements, complex.getElements()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testAddElement() { - try { - CellDesignerComplexSpecies species = new CellDesignerComplexSpecies(); - species.addElement(new CellDesignerSpecies<AntisenseRna>()); - species.addElement(new CellDesignerSpecies<AntisenseRna>()); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testSetStructuralState() { - try { - CellDesignerComplexSpecies species = new CellDesignerComplexSpecies(); - species.setStructuralState("a"); - species.setStructuralState("b"); - assertEquals("b", species.getStructuralState()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testGetAllSimpleChildren() { - try { - CellDesignerComplexSpecies species = new CellDesignerComplexSpecies(); - species.addElement(new CellDesignerSpecies<AntisenseRna>()); - CellDesignerComplexSpecies complex = new CellDesignerComplexSpecies("a"); - complex.addElement(new CellDesignerSpecies<AntisenseRna>("s")); - complex.addElement(new CellDesignerSpecies<AntisenseRna>("d")); - species.addElement(complex); - assertEquals(3, species.getAllSimpleChildren().size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testCopy() { - try { - CellDesignerComplexSpecies degraded = new CellDesignerComplexSpecies().copy(); - assertNotNull(degraded); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testInvalidCopy() { - try { - CellDesignerComplexSpecies complex = Mockito.spy(CellDesignerComplexSpecies.class); - complex.copy(); - fail("Exception expected"); - } catch (NotImplementedException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testCreateInvalidElement() { - try { - CellDesignerComplexSpecies complex = new CellDesignerComplexSpecies(); - complex.addElement(new CellDesignerGene()); - complex.createModelElement(); - fail("Exception expected"); - } catch (NotImplementedException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } +public class ComplexSpeciesTest extends CellDesignerTestFunctions { + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testSerialization() { + SerializationUtils.serialize(new CellDesignerComplexSpecies()); + } + + @Test + public void testConstructor1() { + CellDesignerComplexSpecies degraded = new CellDesignerComplexSpecies(new CellDesignerSpecies<AntisenseRna>()); + assertNotNull(degraded); + } + + @Test + public void testGetters() { + CellDesignerComplexSpecies species = new CellDesignerComplexSpecies(); + species.addElement(new CellDesignerSpecies<AntisenseRna>()); + CellDesignerComplexSpecies complex = new CellDesignerComplexSpecies(species); + + Set<CellDesignerElement<?>> elements = new HashSet<>(); + complex.setElements(elements); + assertEquals(elements, complex.getElements()); + } + + @Test(expected = InvalidArgumentException.class) + public void testAddElement() { + CellDesignerComplexSpecies species = new CellDesignerComplexSpecies(); + species.addElement(new CellDesignerSpecies<AntisenseRna>()); + species.addElement(new CellDesignerSpecies<AntisenseRna>()); + } + + @Test + public void testSetStructuralState() { + CellDesignerComplexSpecies species = new CellDesignerComplexSpecies(); + species.setStructuralState("a"); + species.setStructuralState("b"); + assertEquals("b", species.getStructuralState()); + } + + @Test + public void testGetAllSimpleChildren() { + CellDesignerComplexSpecies species = new CellDesignerComplexSpecies(); + species.addElement(new CellDesignerSpecies<AntisenseRna>()); + CellDesignerComplexSpecies complex = new CellDesignerComplexSpecies("a"); + complex.addElement(new CellDesignerSpecies<AntisenseRna>("s")); + complex.addElement(new CellDesignerSpecies<AntisenseRna>("d")); + species.addElement(complex); + assertEquals(3, species.getAllSimpleChildren().size()); + } + + @Test + public void testCopy() { + CellDesignerComplexSpecies degraded = new CellDesignerComplexSpecies().copy(); + assertNotNull(degraded); + } + + @Test(expected = NotImplementedException.class) + public void testInvalidCopy() { + CellDesignerComplexSpecies complex = Mockito.spy(CellDesignerComplexSpecies.class); + complex.copy(); + } + + @Test(expected = NotImplementedException.class) + public void testCreateInvalidElement() { + CellDesignerComplexSpecies complex = new CellDesignerComplexSpecies(); + complex.addElement(new CellDesignerGene()); + complex.createModelElement(); + } } diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/DegradedTest.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/DegradedTest.java index c9575803d2574403f004629a3922b47e285ab403..4c3af94067d762bcbd36f21096d06eda76ef42e9 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/DegradedTest.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/DegradedTest.java @@ -1,70 +1,46 @@ package lcsb.mapviewer.converter.model.celldesigner.structure; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.mockito.Mockito; import lcsb.mapviewer.common.exception.NotImplementedException; +import lcsb.mapviewer.converter.model.celldesigner.CellDesignerTestFunctions; import lcsb.mapviewer.model.map.species.Degraded; -public class DegradedTest { - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testSerialization() { - try { - SerializationUtils.serialize(new CellDesignerDegraded()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testConstructor1() { - try { - CellDesignerDegraded degraded = new CellDesignerDegraded(new CellDesignerSpecies<Degraded>()); - assertNotNull(degraded); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testCopy() { - try { - CellDesignerDegraded degraded = new CellDesignerDegraded().copy(); - assertNotNull(degraded); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testInvalidCopy() { - try { - CellDesignerDegraded degraded = Mockito.spy(CellDesignerDegraded.class); - degraded.copy(); - fail("Exception expected"); - } catch (NotImplementedException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } +public class DegradedTest extends CellDesignerTestFunctions { + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testSerialization() { + SerializationUtils.serialize(new CellDesignerDegraded()); + } + + @Test + public void testConstructor1() { + CellDesignerDegraded degraded = new CellDesignerDegraded(new CellDesignerSpecies<Degraded>()); + assertNotNull(degraded); + } + + @Test + public void testCopy() { + CellDesignerDegraded degraded = new CellDesignerDegraded().copy(); + assertNotNull(degraded); + } + + @Test(expected = NotImplementedException.class) + public void testInvalidCopy() { + CellDesignerDegraded degraded = Mockito.spy(CellDesignerDegraded.class); + degraded.copy(); + } } diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/DrugTest.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/DrugTest.java index 322c4ab05167309462d1e23d8907bc2f60bc4d3d..1a2f20201de0aa20a0ccc2f7934fd53c6476cd9e 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/DrugTest.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/DrugTest.java @@ -1,70 +1,46 @@ package lcsb.mapviewer.converter.model.celldesigner.structure; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.mockito.Mockito; import lcsb.mapviewer.common.exception.NotImplementedException; +import lcsb.mapviewer.converter.model.celldesigner.CellDesignerTestFunctions; import lcsb.mapviewer.model.map.species.Drug; -public class DrugTest { - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testSerialization() { - try { - SerializationUtils.serialize(new CellDesignerDrug()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testConstructor1() { - try { - CellDesignerDrug degraded = new CellDesignerDrug(new CellDesignerSpecies<Drug>()); - assertNotNull(degraded); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testCopy() { - try { - CellDesignerDrug degraded = new CellDesignerDrug().copy(); - assertNotNull(degraded); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testInvalidCopy() { - try { - CellDesignerDrug drug = Mockito.spy(CellDesignerDrug.class); - drug.copy(); - fail("Exception expected"); - } catch (NotImplementedException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } +public class DrugTest extends CellDesignerTestFunctions { + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testSerialization() { + SerializationUtils.serialize(new CellDesignerDrug()); + } + + @Test + public void testConstructor1() { + CellDesignerDrug degraded = new CellDesignerDrug(new CellDesignerSpecies<Drug>()); + assertNotNull(degraded); + } + + @Test + public void testCopy() { + CellDesignerDrug degraded = new CellDesignerDrug().copy(); + assertNotNull(degraded); + } + + @Test(expected = NotImplementedException.class) + public void testInvalidCopy() { + CellDesignerDrug drug = Mockito.spy(CellDesignerDrug.class); + drug.copy(); + } } diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/ElementTest.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/ElementTest.java index 6efd14fc708f9a54e98466b821e59c0698315113..b6ffb0069bd1a8788db1767f64f3a8347d74e2e9 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/ElementTest.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/ElementTest.java @@ -1,17 +1,13 @@ package lcsb.mapviewer.converter.model.celldesigner.structure; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import java.util.ArrayList; import java.util.List; -import org.apache.logging.log4j.*; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.junit.*; import org.mockito.Mockito; import lcsb.mapviewer.common.exception.InvalidArgumentException; @@ -20,110 +16,82 @@ import lcsb.mapviewer.model.map.MiriamData; import lcsb.mapviewer.model.map.MiriamType; public class ElementTest extends CellDesignerTestFunctions { - Logger logger = LogManager.getLogger(ElementTest.class); - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testConstructor() { - try { - CellDesignerSpecies<?> element = Mockito.spy(CellDesignerSpecies.class); - element.addMiriamData(new MiriamData()); - CellDesignerElement<?> copy = new CellDesignerGenericProtein(element); - assertNotNull(copy); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testAddMiriamCollection() { - try { - List<MiriamData> list = new ArrayList<>(); - list.add(new MiriamData(MiriamType.CAS, "1")); - list.add(new MiriamData(MiriamType.CAS, "1")); - CellDesignerElement<?> element = Mockito.spy(CellDesignerElement.class); - element.addMiriamData(list); - assertEquals(1, element.getMiriamData().size()); - assertEquals(1, getWarnings().size()); - - element.addMiriamData(list); - assertEquals(3, getWarnings().size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testSetNotes() { - try { - CellDesignerElement<?> element = Mockito.spy(CellDesignerElement.class); - element.setNotes("</html>"); - fail("Exception epxected"); - } catch (InvalidArgumentException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testAddSynonym() { - try { - CellDesignerElement<?> element = Mockito.spy(CellDesignerElement.class); - List<String> synonyms = new ArrayList<>(); - synonyms.add("syn"); - element.addSynonyms(synonyms); - assertEquals("syn", element.getSynonyms().get(0)); - StringBuilder sb = new StringBuilder(); - for (int i = 0; i < 300; i++) { - sb.append("a"); - } - String syn = sb.toString(); - synonyms = new ArrayList<>(); - synonyms.add(syn); - element.addSynonyms(synonyms); - assertFalse(syn.equals(element.getSynonyms().get(1))); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testGetters() { - try { - CellDesignerElement<?> element = Mockito.spy(CellDesignerElement.class); - List<String> synonyms = new ArrayList<>(); - List<String> formerSymbols = new ArrayList<>(); - CellDesignerComplexSpecies complex = new CellDesignerComplexSpecies(); - String formula = "str"; - String abbreviation = "abr"; - - element.setSynonyms(synonyms); - element.setFormerSymbols(formerSymbols); - element.setComplex(complex); - element.setFormula(formula); - element.setAbbreviation(abbreviation); - - assertEquals(synonyms, element.getSynonyms()); - assertEquals(formerSymbols, element.getFormerSymbols()); - assertEquals(complex, element.getComplex()); - assertEquals(formula, element.getFormula()); - assertEquals(abbreviation, element.getAbbreviation()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } + Logger logger = LogManager.getLogger(ElementTest.class); + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testConstructor() { + CellDesignerSpecies<?> element = Mockito.spy(CellDesignerSpecies.class); + element.addMiriamData(new MiriamData()); + CellDesignerElement<?> copy = new CellDesignerGenericProtein(element); + assertNotNull(copy); + } + + @Test + public void testAddMiriamCollection() { + List<MiriamData> list = new ArrayList<>(); + list.add(new MiriamData(MiriamType.CAS, "1")); + list.add(new MiriamData(MiriamType.CAS, "1")); + CellDesignerElement<?> element = Mockito.spy(CellDesignerElement.class); + element.addMiriamData(list); + assertEquals(1, element.getMiriamData().size()); + assertEquals(1, getWarnings().size()); + + element.addMiriamData(list); + assertEquals(3, getWarnings().size()); + } + + @Test(expected = InvalidArgumentException.class) + public void testSetNotes() { + CellDesignerElement<?> element = Mockito.spy(CellDesignerElement.class); + element.setNotes("</html>"); + } + + @Test + public void testAddSynonym() { + CellDesignerElement<?> element = Mockito.spy(CellDesignerElement.class); + List<String> synonyms = new ArrayList<>(); + synonyms.add("syn"); + element.addSynonyms(synonyms); + assertEquals("syn", element.getSynonyms().get(0)); + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < 300; i++) { + sb.append("a"); + } + String syn = sb.toString(); + synonyms = new ArrayList<>(); + synonyms.add(syn); + element.addSynonyms(synonyms); + assertFalse(syn.equals(element.getSynonyms().get(1))); + } + + @Test + public void testGetters() { + CellDesignerElement<?> element = Mockito.spy(CellDesignerElement.class); + List<String> synonyms = new ArrayList<>(); + List<String> formerSymbols = new ArrayList<>(); + CellDesignerComplexSpecies complex = new CellDesignerComplexSpecies(); + String formula = "str"; + String abbreviation = "abr"; + + element.setSynonyms(synonyms); + element.setFormerSymbols(formerSymbols); + element.setComplex(complex); + element.setFormula(formula); + element.setAbbreviation(abbreviation); + + assertEquals(synonyms, element.getSynonyms()); + assertEquals(formerSymbols, element.getFormerSymbols()); + assertEquals(complex, element.getComplex()); + assertEquals(formula, element.getFormula()); + assertEquals(abbreviation, element.getAbbreviation()); + } } diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/GeneTest.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/GeneTest.java index 766eeb156ebd85cf1b1c9eca3e0f3bd553a61428..266c2bdf3ae4b5004714f8b259d400421c1c5896 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/GeneTest.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/GeneTest.java @@ -1,22 +1,19 @@ package lcsb.mapviewer.converter.model.celldesigner.structure; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import java.util.ArrayList; import java.util.List; import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.mockito.Mockito; import lcsb.mapviewer.common.exception.NotImplementedException; +import lcsb.mapviewer.converter.model.celldesigner.CellDesignerTestFunctions; import lcsb.mapviewer.converter.model.celldesigner.structure.fields.CellDesignerModificationResidue; -public class GeneTest { +public class GeneTest extends CellDesignerTestFunctions { @Before public void setUp() throws Exception { @@ -28,100 +25,63 @@ public class GeneTest { @Test public void testSerialization() { - try { - SerializationUtils.serialize(new CellDesignerGene()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + SerializationUtils.serialize(new CellDesignerGene()); } @Test public void testConstructor1() { - try { - CellDesignerGene original = new CellDesignerGene(); - original.addModificationResidue(new CellDesignerModificationResidue()); - CellDesignerGene gene = new CellDesignerGene(original); - assertNotNull(gene); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + CellDesignerGene original = new CellDesignerGene(); + original.addModificationResidue(new CellDesignerModificationResidue()); + CellDesignerGene gene = new CellDesignerGene(original); + assertNotNull(gene); } @Test public void testGetters() { - try { - List<CellDesignerModificationResidue> modificationResidues = new ArrayList<>(); - CellDesignerGene gene = new CellDesignerGene(new CellDesignerSpecies<>()); - gene.setModificationResidues(modificationResidues); - assertEquals(modificationResidues, gene.getModificationResidues()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + List<CellDesignerModificationResidue> modificationResidues = new ArrayList<>(); + CellDesignerGene gene = new CellDesignerGene(new CellDesignerSpecies<>()); + gene.setModificationResidues(modificationResidues); + assertEquals(modificationResidues, gene.getModificationResidues()); } @Test public void testCopy() { - try { - CellDesignerGene degraded = new CellDesignerGene().copy(); - assertNotNull(degraded); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + CellDesignerGene degraded = new CellDesignerGene().copy(); + assertNotNull(degraded); } - @Test + @Test(expected = NotImplementedException.class) public void testInvalidCopy() { - try { - CellDesignerGene gene = Mockito.spy(CellDesignerGene.class); - gene.copy(); - fail("Exception expected"); - } catch (NotImplementedException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + CellDesignerGene gene = Mockito.spy(CellDesignerGene.class); + gene.copy(); } @Test public void testUpdate() { - try { - CellDesignerGene gene = new CellDesignerGene(); - CellDesignerGene gene2 = new CellDesignerGene(); - List<CellDesignerModificationResidue> residues = new ArrayList<>(); - residues.add(new CellDesignerModificationResidue()); - - gene2.setModificationResidues(residues); - - gene.update(gene2); - assertEquals(1, gene.getModificationResidues().size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + CellDesignerGene gene = new CellDesignerGene(); + CellDesignerGene gene2 = new CellDesignerGene(); + List<CellDesignerModificationResidue> residues = new ArrayList<>(); + residues.add(new CellDesignerModificationResidue()); + + gene2.setModificationResidues(residues); + + gene.update(gene2); + assertEquals(1, gene.getModificationResidues().size()); } @Test public void testAddModificationResidue() { - try { - CellDesignerGene gene = new CellDesignerGene(); - CellDesignerModificationResidue mr = new CellDesignerModificationResidue("id1"); - CellDesignerModificationResidue mr2 = new CellDesignerModificationResidue("id1"); - CellDesignerModificationResidue mr3 = new CellDesignerModificationResidue("id2"); - - gene.addModificationResidue(mr); - assertEquals(1, gene.getModificationResidues().size()); - gene.addModificationResidue(mr2); - assertEquals(1, gene.getModificationResidues().size()); - gene.addModificationResidue(mr3); - assertEquals(2, gene.getModificationResidues().size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + CellDesignerGene gene = new CellDesignerGene(); + CellDesignerModificationResidue mr = new CellDesignerModificationResidue("id1"); + CellDesignerModificationResidue mr2 = new CellDesignerModificationResidue("id1"); + CellDesignerModificationResidue mr3 = new CellDesignerModificationResidue("id2"); + + gene.addModificationResidue(mr); + assertEquals(1, gene.getModificationResidues().size()); + gene.addModificationResidue(mr2); + assertEquals(1, gene.getModificationResidues().size()); + gene.addModificationResidue(mr3); + assertEquals(2, gene.getModificationResidues().size()); } } diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/GenericProteinTest.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/GenericProteinTest.java index 1fdf0313a1a97396ebc1ec0270a8ff9cd2b64d31..73e83739e789218c5719eec411657bc80e08e967 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/GenericProteinTest.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/GenericProteinTest.java @@ -1,69 +1,46 @@ package lcsb.mapviewer.converter.model.celldesigner.structure; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.mockito.Mockito; import lcsb.mapviewer.common.exception.NotImplementedException; +import lcsb.mapviewer.converter.model.celldesigner.CellDesignerTestFunctions; import lcsb.mapviewer.model.map.species.GenericProtein; -public class GenericProteinTest { - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testSerialization() { - try { - SerializationUtils.serialize(new CellDesignerGenericProtein()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testConstructor() { - try { - CellDesignerGenericProtein species = new CellDesignerGenericProtein(new CellDesignerSpecies<GenericProtein>()); - assertNotNull(species); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testCopy1() { - try { - CellDesignerGenericProtein species = new CellDesignerGenericProtein(new CellDesignerSpecies<GenericProtein>()).copy(); - assertNotNull(species); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testCopy2() { - try { - CellDesignerGenericProtein protein = Mockito.spy(CellDesignerGenericProtein.class); - protein.copy(); - fail("Exception expected"); - } catch (NotImplementedException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } +public class GenericProteinTest extends CellDesignerTestFunctions { + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testSerialization() { + SerializationUtils.serialize(new CellDesignerGenericProtein()); + } + + @Test + public void testConstructor() { + CellDesignerGenericProtein species = new CellDesignerGenericProtein(new CellDesignerSpecies<GenericProtein>()); + assertNotNull(species); + } + + @Test + public void testCopy1() { + CellDesignerGenericProtein species = new CellDesignerGenericProtein(new CellDesignerSpecies<GenericProtein>()) + .copy(); + assertNotNull(species); + } + + @Test(expected = NotImplementedException.class) + public void testCopy2() { + CellDesignerGenericProtein protein = Mockito.spy(CellDesignerGenericProtein.class); + protein.copy(); + } } diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/IonChannelProteinTest.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/IonChannelProteinTest.java index 3751fa3540df2650ddd6ed8b9501f327f11d7488..9a9e856d673ae65ad2b837f04040581ccc336292 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/IonChannelProteinTest.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/IonChannelProteinTest.java @@ -1,70 +1,48 @@ package lcsb.mapviewer.converter.model.celldesigner.structure; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.mockito.Mockito; import lcsb.mapviewer.common.exception.NotImplementedException; +import lcsb.mapviewer.converter.model.celldesigner.CellDesignerTestFunctions; import lcsb.mapviewer.model.map.species.IonChannelProtein; -public class IonChannelProteinTest { - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testSerialization() { - try { - SerializationUtils.serialize(new CellDesignerIonChannelProtein()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testConstructor() { - try { - CellDesignerIonChannelProtein species = new CellDesignerIonChannelProtein(new CellDesignerSpecies<IonChannelProtein>()); - assertNotNull(species); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testCopy1() { - try { - CellDesignerIonChannelProtein species = new CellDesignerIonChannelProtein(new CellDesignerSpecies<IonChannelProtein>()).copy(); - assertNotNull(species); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testCopy2() { - try { - CellDesignerIonChannelProtein protein = Mockito.spy(CellDesignerIonChannelProtein.class); - protein.copy(); - fail("Exception expected"); - } catch (NotImplementedException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } +public class IonChannelProteinTest extends CellDesignerTestFunctions { + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testSerialization() { + SerializationUtils.serialize(new CellDesignerIonChannelProtein()); + } + + @Test + public void testConstructor() { + CellDesignerIonChannelProtein species = new CellDesignerIonChannelProtein( + new CellDesignerSpecies<IonChannelProtein>()); + assertNotNull(species); + } + + @Test + public void testCopy1() { + CellDesignerIonChannelProtein species = new CellDesignerIonChannelProtein( + new CellDesignerSpecies<IonChannelProtein>()).copy(); + assertNotNull(species); + } + + @Test(expected = NotImplementedException.class) + public void testCopy2() { + CellDesignerIonChannelProtein protein = Mockito.spy(CellDesignerIonChannelProtein.class); + protein.copy(); + } } diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/IonTest.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/IonTest.java index ac1641c2acc9101eb05eeee34f6f5d72afe3c926..ec56e6bf4c936411bbd5f8bcbd3f706b3fe2f119 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/IonTest.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/IonTest.java @@ -1,18 +1,16 @@ package lcsb.mapviewer.converter.model.celldesigner.structure; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.mockito.Mockito; import lcsb.mapviewer.common.exception.NotImplementedException; +import lcsb.mapviewer.converter.model.celldesigner.CellDesignerTestFunctions; import lcsb.mapviewer.model.map.species.IonChannelProtein; -public class IonTest { +public class IonTest extends CellDesignerTestFunctions { @Before public void setUp() throws Exception { @@ -24,47 +22,25 @@ public class IonTest { @Test public void testSerialization() { - try { - SerializationUtils.serialize(new CellDesignerIon()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + SerializationUtils.serialize(new CellDesignerIon()); } @Test public void testConstructor1() { - try { - CellDesignerIon degraded = new CellDesignerIon(new CellDesignerSpecies<IonChannelProtein>()); - assertNotNull(degraded); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + CellDesignerIon degraded = new CellDesignerIon(new CellDesignerSpecies<IonChannelProtein>()); + assertNotNull(degraded); } @Test public void testCopy() { - try { - CellDesignerIon degraded = new CellDesignerIon().copy(); - assertNotNull(degraded); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + CellDesignerIon degraded = new CellDesignerIon().copy(); + assertNotNull(degraded); } - @Test + @Test(expected = NotImplementedException.class) public void testInvalidCopy() { - try { - CellDesignerIon ion = Mockito.spy(CellDesignerIon.class); - ion.copy(); - fail("Exception expected"); - } catch (NotImplementedException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + CellDesignerIon ion = Mockito.spy(CellDesignerIon.class); + ion.copy(); } } diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/ModificationResidueTest.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/ModificationResidueTest.java index 4bddfd25667e70d721cacb1d5596161e49c15289..d03f41128bd61cb8608c5447d46af4f0e76a98f7 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/ModificationResidueTest.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/ModificationResidueTest.java @@ -1,153 +1,112 @@ package lcsb.mapviewer.converter.model.celldesigner.structure; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; +import org.mockito.Mockito; import lcsb.mapviewer.common.Configuration; import lcsb.mapviewer.common.exception.InvalidArgumentException; import lcsb.mapviewer.common.exception.NotImplementedException; +import lcsb.mapviewer.converter.model.celldesigner.CellDesignerTestFunctions; import lcsb.mapviewer.converter.model.celldesigner.structure.fields.CellDesignerModificationResidue; import lcsb.mapviewer.model.map.species.IonChannelProtein; import lcsb.mapviewer.model.map.species.field.ModificationState; -public class ModificationResidueTest { - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testSerialization() { - try { - SerializationUtils.serialize(new CellDesignerModificationResidue()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testConstructor() { - try { - CellDesignerModificationResidue original = new CellDesignerModificationResidue(); - CellDesignerModificationResidue copy = new CellDesignerModificationResidue(original); - assertNotNull(copy); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testUpdate() { - try { - CellDesignerModificationResidue original = new CellDesignerModificationResidue(); - CellDesignerModificationResidue update = new CellDesignerModificationResidue(); - - String name = "n"; - String side = "s"; - ModificationState state = ModificationState.ACETYLATED; - Double angle = 3.9; - Double size = 5.0; - - update.setName(name); - update.setSide(side); - update.setAngle(angle); - update.setSize(size); - update.setState(state); - - original.update(update); - - assertEquals(name, original.getName()); - assertEquals(side, original.getSide()); - assertEquals(angle, original.getAngle()); - assertEquals(size, original.getSize()); - assertEquals(state, original.getState()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testGetters() { - try { - CellDesignerModificationResidue original = new CellDesignerModificationResidue(); - - String doubleStr = "2.0"; - String invalidDoubleStr = "a2.0"; - String nullStr = null; - Double angle = 2.0; - CellDesignerSpecies<?> species = new CellDesignerSpecies<IonChannelProtein>(); - - original.setAngle(doubleStr); - assertEquals(angle, original.getAngle(), Configuration.EPSILON); - try { - original.setAngle(invalidDoubleStr); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - } - original.setAngle(nullStr); - assertNull(original.getAngle()); - - original.setSize(doubleStr); - assertEquals(angle, original.getSize(), Configuration.EPSILON); - try { - original.setSize(invalidDoubleStr); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - } - original.setSize(doubleStr); - original.setSize(nullStr); - assertNull(original.getSize()); - - original.setSpecies(species); - assertEquals(species, original.getSpecies()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testCopy() { - try { - CellDesignerModificationResidue degraded = new CellDesignerModificationResidue().copy(); - assertNotNull(degraded); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testInvalidCopy() { - try { - new CellDesignerModificationResidue() { - - /** - * - */ - private static final long serialVersionUID = 1L; - }.copy(); - fail("Exception expected"); - } catch (NotImplementedException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } +public class ModificationResidueTest extends CellDesignerTestFunctions { + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testSerialization() { + SerializationUtils.serialize(new CellDesignerModificationResidue()); + } + + @Test + public void testConstructor() { + CellDesignerModificationResidue original = new CellDesignerModificationResidue(); + CellDesignerModificationResidue copy = new CellDesignerModificationResidue(original); + assertNotNull(copy); + } + + @Test + public void testUpdate() { + CellDesignerModificationResidue original = new CellDesignerModificationResidue(); + CellDesignerModificationResidue update = new CellDesignerModificationResidue(); + + String name = "n"; + String side = "s"; + ModificationState state = ModificationState.ACETYLATED; + Double angle = 3.9; + Double size = 5.0; + + update.setName(name); + update.setSide(side); + update.setAngle(angle); + update.setSize(size); + update.setState(state); + + original.update(update); + + assertEquals(name, original.getName()); + assertEquals(side, original.getSide()); + assertEquals(angle, original.getAngle()); + assertEquals(size, original.getSize()); + assertEquals(state, original.getState()); + } + + @Test(expected = InvalidArgumentException.class) + public void testSetInvalidAngle() { + CellDesignerModificationResidue original = new CellDesignerModificationResidue(); + original.setAngle("a2.0"); + } + + @Test(expected = InvalidArgumentException.class) + public void testSetInvalidSize() { + CellDesignerModificationResidue original = new CellDesignerModificationResidue(); + original.setSize("a2.0"); + } + + @Test + public void testGetters() { + CellDesignerModificationResidue original = new CellDesignerModificationResidue(); + + String doubleStr = "2.0"; + String nullStr = null; + Double angle = 2.0; + CellDesignerSpecies<?> species = new CellDesignerSpecies<IonChannelProtein>(); + + original.setAngle(doubleStr); + assertEquals(angle, original.getAngle(), Configuration.EPSILON); + original.setAngle(nullStr); + assertNull(original.getAngle()); + + original.setSize(doubleStr); + assertEquals(angle, original.getSize(), Configuration.EPSILON); + original.setSize(doubleStr); + original.setSize(nullStr); + assertNull(original.getSize()); + + original.setSpecies(species); + assertEquals(species, original.getSpecies()); + } + + @Test + public void testCopy() { + CellDesignerModificationResidue degraded = new CellDesignerModificationResidue().copy(); + assertNotNull(degraded); + } + + @Test(expected = NotImplementedException.class) + public void testInvalidCopy() { + Mockito.spy(CellDesignerModificationResidue.class).copy(); + } } diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/PhenotypeTest.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/PhenotypeTest.java index dc63317e6aa454cf16ddd0d8c06b43743eb075e2..298b1523adce94cf996748645aa582352e0fbb32 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/PhenotypeTest.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/PhenotypeTest.java @@ -1,70 +1,46 @@ package lcsb.mapviewer.converter.model.celldesigner.structure; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.mockito.Mockito; import lcsb.mapviewer.common.exception.NotImplementedException; - -public class PhenotypeTest { - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testSerialization() { - try { - SerializationUtils.serialize(new CellDesignerPhenotype()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testConstructor1() { - try { - CellDesignerPhenotype original = new CellDesignerPhenotype(); - CellDesignerPhenotype copy = new CellDesignerPhenotype(original); - assertNotNull(copy); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testCopy() { - try { - CellDesignerPhenotype degraded = new CellDesignerPhenotype().copy(); - assertNotNull(degraded); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testInvalidCopy() { - try { - CellDesignerPhenotype phenotype = Mockito.spy(CellDesignerPhenotype.class); - phenotype.copy(); - fail("Exception expected"); - } catch (NotImplementedException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } +import lcsb.mapviewer.converter.model.celldesigner.CellDesignerTestFunctions; + +public class PhenotypeTest extends CellDesignerTestFunctions { + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testSerialization() { + SerializationUtils.serialize(new CellDesignerPhenotype()); + } + + @Test + public void testConstructor1() { + CellDesignerPhenotype original = new CellDesignerPhenotype(); + CellDesignerPhenotype copy = new CellDesignerPhenotype(original); + assertNotNull(copy); + } + + @Test + public void testCopy() { + CellDesignerPhenotype degraded = new CellDesignerPhenotype().copy(); + assertNotNull(degraded); + } + + @Test(expected = NotImplementedException.class) + public void testInvalidCopy() { + CellDesignerPhenotype phenotype = Mockito.spy(CellDesignerPhenotype.class); + phenotype.copy(); + } } diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/ProteinTest.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/ProteinTest.java index be726bf74414a95946e9f9e497be6561d32c4ead..f4736e225ad1b380745f454895941fc4eccce498 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/ProteinTest.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/ProteinTest.java @@ -1,135 +1,95 @@ package lcsb.mapviewer.converter.model.celldesigner.structure; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import java.util.ArrayList; import java.util.List; import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.mockito.Mockito; import lcsb.mapviewer.common.exception.NotImplementedException; +import lcsb.mapviewer.converter.model.celldesigner.CellDesignerTestFunctions; import lcsb.mapviewer.converter.model.celldesigner.structure.fields.CellDesignerModificationResidue; import lcsb.mapviewer.model.map.species.GenericProtein; -public class ProteinTest { - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testSerialization() { - try { - SerializationUtils.serialize(new CellDesignerGenericProtein()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testConstructor1() { - try { - CellDesignerProtein<?> protein = new CellDesignerGenericProtein(); - protein.setStructuralState("srt"); - List<CellDesignerModificationResidue> residues = new ArrayList<>(); - residues.add(new CellDesignerModificationResidue()); - - protein.setModificationResidues(residues); - CellDesignerProtein<?> protein2 = new CellDesignerGenericProtein(protein); - assertNotNull(protein2); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testUpdate() { - try { - CellDesignerProtein<?> protein = new CellDesignerGenericProtein(); - protein.setStructuralState(""); - CellDesignerProtein<?> protein2 = new CellDesignerGenericProtein(); - protein2.setStructuralState("srt"); - List<CellDesignerModificationResidue> residues = new ArrayList<>(); - residues.add(new CellDesignerModificationResidue()); - - protein2.setModificationResidues(residues); - - protein.update(protein2); - assertEquals(protein2.getStructuralState(), protein.getStructuralState()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testAddModificationResidue() { - try { - CellDesignerProtein<?> protein = new CellDesignerGenericProtein(); - CellDesignerModificationResidue mr = new CellDesignerModificationResidue(); - mr.setIdModificationResidue("id1"); - - CellDesignerModificationResidue mr2 = new CellDesignerModificationResidue(); - mr2.setIdModificationResidue("id1"); - - protein.addModificationResidue(mr); - assertEquals(1, protein.getModificationResidues().size()); - protein.addModificationResidue(mr2); - assertEquals(1, protein.getModificationResidues().size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testSetStructuralState() { - try { - CellDesignerProtein<?> protein = new CellDesignerGenericProtein(); - protein.setStructuralState("str"); - protein.setStructuralState("str1"); - - assertEquals("str1", protein.getStructuralState()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testCopy() { - try { - CellDesignerProtein<?> protein = new CellDesignerProtein<GenericProtein>().copy(); - assertNotNull(protein); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testInvalidCopy() { - try { - CellDesignerProtein<?> mock = Mockito.spy(CellDesignerProtein.class); - mock.copy(); - fail("Exception expected"); - } catch (NotImplementedException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } +public class ProteinTest extends CellDesignerTestFunctions { + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testSerialization() { + SerializationUtils.serialize(new CellDesignerGenericProtein()); + } + + @Test + public void testConstructor1() { + CellDesignerProtein<?> protein = new CellDesignerGenericProtein(); + protein.setStructuralState("srt"); + List<CellDesignerModificationResidue> residues = new ArrayList<>(); + residues.add(new CellDesignerModificationResidue()); + + protein.setModificationResidues(residues); + CellDesignerProtein<?> protein2 = new CellDesignerGenericProtein(protein); + assertNotNull(protein2); + } + + @Test + public void testUpdate() { + CellDesignerProtein<?> protein = new CellDesignerGenericProtein(); + protein.setStructuralState(""); + CellDesignerProtein<?> protein2 = new CellDesignerGenericProtein(); + protein2.setStructuralState("srt"); + List<CellDesignerModificationResidue> residues = new ArrayList<>(); + residues.add(new CellDesignerModificationResidue()); + + protein2.setModificationResidues(residues); + + protein.update(protein2); + assertEquals(protein2.getStructuralState(), protein.getStructuralState()); + } + + @Test + public void testAddModificationResidue() { + CellDesignerProtein<?> protein = new CellDesignerGenericProtein(); + CellDesignerModificationResidue mr = new CellDesignerModificationResidue(); + mr.setIdModificationResidue("id1"); + + CellDesignerModificationResidue mr2 = new CellDesignerModificationResidue(); + mr2.setIdModificationResidue("id1"); + + protein.addModificationResidue(mr); + assertEquals(1, protein.getModificationResidues().size()); + protein.addModificationResidue(mr2); + assertEquals(1, protein.getModificationResidues().size()); + } + + @Test + public void testSetStructuralState() { + CellDesignerProtein<?> protein = new CellDesignerGenericProtein(); + protein.setStructuralState("str"); + protein.setStructuralState("str1"); + + assertEquals("str1", protein.getStructuralState()); + } + + @Test + public void testCopy() { + CellDesignerProtein<?> protein = new CellDesignerProtein<GenericProtein>().copy(); + assertNotNull(protein); + } + + @Test(expected = NotImplementedException.class) + public void testInvalidCopy() { + CellDesignerProtein<?> mock = Mockito.spy(CellDesignerProtein.class); + mock.copy(); + } } diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/ReceptorProteinTest.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/ReceptorProteinTest.java index 0ce73dfe6a7266e9756b1b5b89c3787be55b373f..17d0cb16d51b39162856c102eaff9d2bb95ed4a1 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/ReceptorProteinTest.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/ReceptorProteinTest.java @@ -1,70 +1,47 @@ package lcsb.mapviewer.converter.model.celldesigner.structure; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.mockito.Mockito; import lcsb.mapviewer.common.exception.NotImplementedException; +import lcsb.mapviewer.converter.model.celldesigner.CellDesignerTestFunctions; import lcsb.mapviewer.model.map.species.ReceptorProtein; -public class ReceptorProteinTest { - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testSerialization() { - try { - SerializationUtils.serialize(new CellDesignerReceptorProtein()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testConstructor() { - try { - CellDesignerReceptorProtein species = new CellDesignerReceptorProtein(new CellDesignerSpecies<ReceptorProtein>()); - assertNotNull(species); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testCopy1() { - try { - CellDesignerReceptorProtein species = new CellDesignerReceptorProtein(new CellDesignerSpecies<ReceptorProtein>()).copy(); - assertNotNull(species); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testCopy2() { - try { - CellDesignerReceptorProtein protein = Mockito.spy(CellDesignerReceptorProtein.class); - protein.copy(); - fail("Exception expected"); - } catch (NotImplementedException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } +public class ReceptorProteinTest extends CellDesignerTestFunctions { + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testSerialization() { + SerializationUtils.serialize(new CellDesignerReceptorProtein()); + } + + @Test + public void testConstructor() { + CellDesignerReceptorProtein species = new CellDesignerReceptorProtein(new CellDesignerSpecies<ReceptorProtein>()); + assertNotNull(species); + } + + @Test + public void testCopy1() { + CellDesignerReceptorProtein species = new CellDesignerReceptorProtein(new CellDesignerSpecies<ReceptorProtein>()) + .copy(); + assertNotNull(species); + } + + @Test(expected = NotImplementedException.class) + public void testCopy2() { + CellDesignerReceptorProtein protein = Mockito.spy(CellDesignerReceptorProtein.class); + protein.copy(); + } } diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/RnaTest.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/RnaTest.java index ee2eafcb481aaa3d2ab2cd696ba43b3be5e1c23b..ec7d8d72530c136dd703a6b1679818458b5d9b2a 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/RnaTest.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/RnaTest.java @@ -1,26 +1,23 @@ package lcsb.mapviewer.converter.model.celldesigner.structure; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import java.util.ArrayList; import java.util.List; import org.apache.commons.lang3.SerializationUtils; -import org.apache.logging.log4j.*; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.junit.*; import org.mockito.Mockito; import lcsb.mapviewer.common.exception.NotImplementedException; +import lcsb.mapviewer.converter.model.celldesigner.CellDesignerTestFunctions; import lcsb.mapviewer.converter.model.celldesigner.structure.fields.CellDesignerModificationResidue; import lcsb.mapviewer.model.map.species.Rna; import lcsb.mapviewer.model.map.species.field.ModificationState; -public class RnaTest { +public class RnaTest extends CellDesignerTestFunctions { Logger logger = LogManager.getLogger(RnaTest.class); @Before @@ -33,122 +30,85 @@ public class RnaTest { @Test public void testSerialization() { - try { - SerializationUtils.serialize(new CellDesignerRna()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + SerializationUtils.serialize(new CellDesignerRna()); } @Test public void testConstructor1() { - try { - CellDesignerRna rna = new CellDesignerRna(new CellDesignerSpecies<Rna>()); - assertNotNull(rna); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + CellDesignerRna rna = new CellDesignerRna(new CellDesignerSpecies<Rna>()); + assertNotNull(rna); } @Test public void testGetters() { - try { - CellDesignerRna rna = new CellDesignerRna(new CellDesignerSpecies<Rna>()); - List<CellDesignerModificationResidue> regions = new ArrayList<>(); + CellDesignerRna rna = new CellDesignerRna(new CellDesignerSpecies<Rna>()); + List<CellDesignerModificationResidue> regions = new ArrayList<>(); - rna.setRegions(regions); + rna.setRegions(regions); - assertEquals(regions, rna.getRegions()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(regions, rna.getRegions()); } @Test public void testCopy() { - try { - CellDesignerRna rna = new CellDesignerRna().copy(); - assertNotNull(rna); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + CellDesignerRna rna = new CellDesignerRna().copy(); + assertNotNull(rna); } - @Test + @Test(expected = NotImplementedException.class) public void testInvalidCopy() { - try { - CellDesignerRna rna = Mockito.spy(CellDesignerRna.class); - rna.copy(); - fail("Exception expected"); - } catch (NotImplementedException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + CellDesignerRna rna = Mockito.spy(CellDesignerRna.class); + rna.copy(); } @Test public void testAddRnaRegion() { - try { - CellDesignerRna original = new CellDesignerRna(); - CellDesignerModificationResidue region = new CellDesignerModificationResidue("id1"); - original.addRegion(region); + CellDesignerRna original = new CellDesignerRna(); + CellDesignerModificationResidue region = new CellDesignerModificationResidue("id1"); + original.addRegion(region); - CellDesignerModificationResidue region2 = new CellDesignerModificationResidue("id1"); - region2.setName("nam"); - original.addRegion(region2); + CellDesignerModificationResidue region2 = new CellDesignerModificationResidue("id1"); + region2.setName("nam"); + original.addRegion(region2); - assertEquals(1, original.getRegions().size()); + assertEquals(1, original.getRegions().size()); - assertEquals("nam", original.getRegions().get(0).getName()); + assertEquals("nam", original.getRegions().get(0).getName()); - CellDesignerModificationResidue region3 = new CellDesignerModificationResidue("id2"); - region3.setName("nam"); - original.addRegion(region3); + CellDesignerModificationResidue region3 = new CellDesignerModificationResidue("id2"); + region3.setName("nam"); + original.addRegion(region3); - assertEquals(2, original.getRegions().size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(2, original.getRegions().size()); } @Test public void testUpdate() { - try { - CellDesignerRna original = new CellDesignerRna(); - CellDesignerModificationResidue region2 = new CellDesignerModificationResidue("id1"); - region2.setName("nam"); - original.addRegion(region2); - CellDesignerModificationResidue region3 = new CellDesignerModificationResidue("id2"); - region3.setName("nam"); - original.addRegion(region3); - - CellDesignerRna copy = new CellDesignerRna(original); - copy.addRegion(new CellDesignerModificationResidue()); - copy.getRegions().get(0).setState(ModificationState.ACETYLATED); - - original.update(copy); - - boolean acetylatedFound = false; - for (CellDesignerModificationResidue region : copy.getRegions()) { - if (ModificationState.ACETYLATED.equals(region.getState())) { - acetylatedFound = true; - } + CellDesignerRna original = new CellDesignerRna(); + CellDesignerModificationResidue region2 = new CellDesignerModificationResidue("id1"); + region2.setName("nam"); + original.addRegion(region2); + CellDesignerModificationResidue region3 = new CellDesignerModificationResidue("id2"); + region3.setName("nam"); + original.addRegion(region3); + + CellDesignerRna copy = new CellDesignerRna(original); + copy.addRegion(new CellDesignerModificationResidue()); + copy.getRegions().get(0).setState(ModificationState.ACETYLATED); + + original.update(copy); + + boolean acetylatedFound = false; + for (CellDesignerModificationResidue region : copy.getRegions()) { + if (ModificationState.ACETYLATED.equals(region.getState())) { + acetylatedFound = true; } - assertTrue(acetylatedFound); - assertEquals(3, original.getRegions().size()); - assertEquals(3, copy.getRegions().size()); - - original.update(new CellDesignerGenericProtein()); - } catch (Exception e) { - e.printStackTrace(); - throw e; } + assertTrue(acetylatedFound); + assertEquals(3, original.getRegions().size()); + assertEquals(3, copy.getRegions().size()); + + original.update(new CellDesignerGenericProtein()); } } diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/SimpleMoleculeTest.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/SimpleMoleculeTest.java index 39c8e9c01a272729c8d4193fbce8ff4d8f96025e..35c0176da92aca946e7e43d29a92fcf5ee90351a 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/SimpleMoleculeTest.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/SimpleMoleculeTest.java @@ -1,70 +1,46 @@ package lcsb.mapviewer.converter.model.celldesigner.structure; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.mockito.Mockito; import lcsb.mapviewer.common.exception.NotImplementedException; +import lcsb.mapviewer.converter.model.celldesigner.CellDesignerTestFunctions; import lcsb.mapviewer.model.map.species.SimpleMolecule; -public class SimpleMoleculeTest { - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testSerialization() { - try { - SerializationUtils.serialize(new CellDesignerSimpleMolecule()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testConstructor1() { - try { - CellDesignerSimpleMolecule degraded = new CellDesignerSimpleMolecule(new CellDesignerSpecies<SimpleMolecule>()); - assertNotNull(degraded); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testCopy() { - try { - CellDesignerSimpleMolecule degraded = new CellDesignerSimpleMolecule().copy(); - assertNotNull(degraded); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testInvalidCopy() { - try { - CellDesignerSimpleMolecule simpleMolecule = Mockito.spy(CellDesignerSimpleMolecule.class); - simpleMolecule.copy(); - fail("Exception expected"); - } catch (NotImplementedException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } +public class SimpleMoleculeTest extends CellDesignerTestFunctions { + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testSerialization() { + SerializationUtils.serialize(new CellDesignerSimpleMolecule()); + } + + @Test + public void testConstructor1() { + CellDesignerSimpleMolecule degraded = new CellDesignerSimpleMolecule(new CellDesignerSpecies<SimpleMolecule>()); + assertNotNull(degraded); + } + + @Test + public void testCopy() { + CellDesignerSimpleMolecule degraded = new CellDesignerSimpleMolecule().copy(); + assertNotNull(degraded); + } + + @Test(expected = NotImplementedException.class) + public void testInvalidCopy() { + CellDesignerSimpleMolecule simpleMolecule = Mockito.spy(CellDesignerSimpleMolecule.class); + simpleMolecule.copy(); + } } diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/SpeciesStateTest.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/SpeciesStateTest.java index 1c6e9ca880ad90b3979c7287ca06d1cfff6045fa..6f49cb22307550a4027cfcc1256c3a7fe49e5abd 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/SpeciesStateTest.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/SpeciesStateTest.java @@ -1,17 +1,15 @@ package lcsb.mapviewer.converter.model.celldesigner.structure; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import java.awt.geom.Point2D; import java.util.ArrayList; import java.util.List; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import lcsb.mapviewer.common.exception.InvalidArgumentException; +import lcsb.mapviewer.converter.model.celldesigner.CellDesignerTestFunctions; import lcsb.mapviewer.converter.model.celldesigner.structure.fields.CellDesignerModificationResidue; import lcsb.mapviewer.converter.model.celldesigner.structure.fields.SpeciesState; import lcsb.mapviewer.model.map.species.Gene; @@ -19,7 +17,7 @@ import lcsb.mapviewer.model.map.species.Rna; import lcsb.mapviewer.model.map.species.field.CodingRegion; import lcsb.mapviewer.model.map.species.field.ModificationSite; -public class SpeciesStateTest { +public class SpeciesStateTest extends CellDesignerTestFunctions { @Before public void setUp() throws Exception { @@ -37,16 +35,11 @@ public class SpeciesStateTest { assertEquals(modifications, state.getModifications()); } - @Test + @Test(expected = InvalidArgumentException.class) public void testSetHomodimer() { - try { - SpeciesState state = new SpeciesState(); - - state.setHomodimer("inv"); - fail("Exception expected"); - } catch (InvalidArgumentException e) { + SpeciesState state = new SpeciesState(); - } + state.setHomodimer("inv"); } @Test diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/SpeciesTest.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/SpeciesTest.java index 49cd34090f164df7b4149bcf7979757b3a8c4377..12cadc1fafda33897ebb26894f80e2bb4678f401 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/SpeciesTest.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/SpeciesTest.java @@ -1,15 +1,9 @@ package lcsb.mapviewer.converter.model.celldesigner.structure; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import lcsb.mapviewer.common.Configuration; import lcsb.mapviewer.common.exception.InvalidArgumentException; @@ -32,329 +26,227 @@ public class SpeciesTest extends CellDesignerTestFunctions { @Test public void testSerialization() { - try { - SerializationUtils.serialize(new CellDesignerSpecies<GenericProtein>()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + SerializationUtils.serialize(new CellDesignerSpecies<GenericProtein>()); } @Test public void testGetters() { - try { - CellDesignerSpecies<?> species = new CellDesignerSpecies<GenericProtein>(); - String elementId = "51"; - Double initialAmount = 54.0; - Double initialConcentration = 58.0; - Integer charge = 59; - Boolean onlySubstanceUnits = true; + CellDesignerSpecies<?> species = new CellDesignerSpecies<GenericProtein>(); + String elementId = "51"; + Double initialAmount = 54.0; + Double initialConcentration = 58.0; + Integer charge = 59; + Boolean onlySubstanceUnits = true; - String trueStr = "true"; - assertFalse(species.isHypothetical()); - species.setHypothetical(trueStr); - assertTrue(species.isHypothetical()); + String trueStr = "true"; + assertFalse(species.isHypothetical()); + species.setHypothetical(trueStr); + assertTrue(species.isHypothetical()); - species.setElementId(elementId); - assertEquals(elementId, species.getElementId()); + species.setElementId(elementId); + assertEquals(elementId, species.getElementId()); - species.setInitialAmount(initialAmount); - assertEquals(initialAmount, species.getInitialAmount()); + species.setInitialAmount(initialAmount); + assertEquals(initialAmount, species.getInitialAmount()); - species.setOnlySubstanceUnits(onlySubstanceUnits); - assertEquals(onlySubstanceUnits, species.getOnlySubstanceUnits()); + species.setOnlySubstanceUnits(onlySubstanceUnits); + assertEquals(onlySubstanceUnits, species.getOnlySubstanceUnits()); - species.setInitialConcentration(initialConcentration); - assertEquals(initialConcentration, species.getInitialConcentration()); + species.setInitialConcentration(initialConcentration); + assertEquals(initialConcentration, species.getInitialConcentration()); - species.setCharge(charge); + species.setCharge(charge); - assertEquals(charge, species.getCharge()); + assertEquals(charge, species.getCharge()); - species.setElementId(""); - assertEquals("", species.getElementId()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + species.setElementId(""); + assertEquals("", species.getElementId()); } @Test public void testConstructor() { - try { - String id = "as_id"; - CellDesignerSpecies<?> species = new CellDesignerSpecies<GenericProtein>(id); - assertEquals(id, species.getElementId()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String id = "as_id"; + CellDesignerSpecies<?> species = new CellDesignerSpecies<GenericProtein>(id); + assertEquals(id, species.getElementId()); } @Test public void testCopy() { - try { - String id = "as_id"; - CellDesignerSpecies<GenericProtein> species = new CellDesignerSpecies<>(id); - species.setBoundaryCondition(true); - species.setConstant(true); - species.setSubstanceUnits(SbmlUnitType.COULUMB); - CellDesignerSpecies<?> copy = species.copy(); - assertEquals(id, species.getElementId()); - assertEquals(Boolean.TRUE, copy.isBoundaryCondition()); - assertEquals(Boolean.TRUE, copy.isConstant()); - assertEquals(SbmlUnitType.COULUMB, copy.getSubstanceUnit()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test + String id = "as_id"; + CellDesignerSpecies<GenericProtein> species = new CellDesignerSpecies<>(id); + species.setBoundaryCondition(true); + species.setConstant(true); + species.setSubstanceUnits(SbmlUnitType.COULUMB); + CellDesignerSpecies<?> copy = species.copy(); + assertEquals(id, species.getElementId()); + assertEquals(Boolean.TRUE, copy.isBoundaryCondition()); + assertEquals(Boolean.TRUE, copy.isConstant()); + assertEquals(SbmlUnitType.COULUMB, copy.getSubstanceUnit()); + } + + @Test(expected = InvalidArgumentException.class) public void testSetId() { - try { - CellDesignerSpecies<?> species = new CellDesignerSpecies<GenericProtein>(); - species.setElementId(""); - species.setElementId("xx"); - try { - species.setElementId("yy"); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - - } - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + CellDesignerSpecies<?> species = new CellDesignerSpecies<GenericProtein>(); + species.setElementId(""); + species.setElementId("xx"); + species.setElementId("yy"); } @Test public void testUpdate1() { - try { - int warningsCount = getWarnings().size(); - CellDesignerSpecies<?> species = new CellDesignerSpecies<GenericProtein>(); - species.setName("A"); - species.setNotes("XXX"); - CellDesignerSpecies<?> species2 = new CellDesignerSpecies<GenericProtein>(); - species2.setName("B"); - species.update(species2); - int warningsCount2 = getWarnings().size(); - assertEquals(1, warningsCount2 - warningsCount); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + int warningsCount = getWarnings().size(); + CellDesignerSpecies<?> species = new CellDesignerSpecies<GenericProtein>(); + species.setName("A"); + species.setNotes("XXX"); + CellDesignerSpecies<?> species2 = new CellDesignerSpecies<GenericProtein>(); + species2.setName("B"); + species.update(species2); + int warningsCount2 = getWarnings().size(); + assertEquals(1, warningsCount2 - warningsCount); } @Test public void testUpdate2() { - try { - CellDesignerSpecies<?> species = new CellDesignerSpecies<GenericProtein>(); - species.setNotes("XXX"); - CellDesignerSpecies<?> species2 = new CellDesignerSpecies<GenericProtein>(); - species2.addMiriamData(new MiriamData()); - species.update(species2); - int warningsCount = getWarnings().size(); - assertEquals(0, warningsCount); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + CellDesignerSpecies<?> species = new CellDesignerSpecies<GenericProtein>(); + species.setNotes("XXX"); + CellDesignerSpecies<?> species2 = new CellDesignerSpecies<GenericProtein>(); + species2.addMiriamData(new MiriamData()); + species.update(species2); + int warningsCount = getWarnings().size(); + assertEquals(0, warningsCount); } @Test public void testUpdate3() { - try { - CellDesignerSpecies<?> species = new CellDesignerSpecies<GenericProtein>(); - species.setNotes("XXX"); - CellDesignerSpecies<?> species2 = new CellDesignerSpecies<GenericProtein>(); - species2.setNotes("xx"); - species.update(species2); - int warningsCount = getWarnings().size(); - assertEquals(0, warningsCount); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + CellDesignerSpecies<?> species = new CellDesignerSpecies<GenericProtein>(); + species.setNotes("XXX"); + CellDesignerSpecies<?> species2 = new CellDesignerSpecies<GenericProtein>(); + species2.setNotes("xx"); + species.update(species2); + int warningsCount = getWarnings().size(); + assertEquals(0, warningsCount); } @Test public void testUpdate4() { - try { - CellDesignerSpecies<?> species = new CellDesignerSpecies<GenericProtein>(); - species.setNotes("XX"); - CellDesignerSpecies<?> species2 = new CellDesignerSpecies<GenericProtein>(); - species2.setNotes("xxX"); - species.update(species2); - int warningsCount = getWarnings().size(); - assertEquals(0, warningsCount); - assertEquals(3, species.getNotes().length()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + CellDesignerSpecies<?> species = new CellDesignerSpecies<GenericProtein>(); + species.setNotes("XX"); + CellDesignerSpecies<?> species2 = new CellDesignerSpecies<GenericProtein>(); + species2.setNotes("xxX"); + species.update(species2); + int warningsCount = getWarnings().size(); + assertEquals(0, warningsCount); + assertEquals(3, species.getNotes().length()); } @Test public void testUpdate5() { - try { - CellDesignerSpecies<?> species = new CellDesignerSpecies<GenericProtein>(); - species.setNotes("XX"); - CellDesignerSpecies<?> species2 = new CellDesignerSpecies<GenericProtein>(); - species2.setNotes("a as x"); - species2.setHypothetical(true); - species2.setSymbol("sym"); - species2.setHomodimer(2); - species.update(species2); - int warningsCount = getWarnings().size(); - assertEquals(0, warningsCount); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + CellDesignerSpecies<?> species = new CellDesignerSpecies<GenericProtein>(); + species.setNotes("XX"); + CellDesignerSpecies<?> species2 = new CellDesignerSpecies<GenericProtein>(); + species2.setNotes("a as x"); + species2.setHypothetical(true); + species2.setSymbol("sym"); + species2.setHomodimer(2); + species.update(species2); + int warningsCount = getWarnings().size(); + assertEquals(0, warningsCount); } @Test public void testUpdate6() { - try { - CellDesignerSpecies<?> species = new CellDesignerSpecies<GenericProtein>(); - species.setSymbol("sym1"); - species.setFullName("a_sym1"); - CellDesignerSpecies<?> species2 = new CellDesignerSpecies<GenericProtein>(); - species2.setSymbol("sym2"); - species2.setFullName("b_sym1"); - species.update(species2); - int warningsCount = getWarnings().size(); - assertEquals(2, warningsCount); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + CellDesignerSpecies<?> species = new CellDesignerSpecies<GenericProtein>(); + species.setSymbol("sym1"); + species.setFullName("a_sym1"); + CellDesignerSpecies<?> species2 = new CellDesignerSpecies<GenericProtein>(); + species2.setSymbol("sym2"); + species2.setFullName("b_sym1"); + species.update(species2); + int warningsCount = getWarnings().size(); + assertEquals(2, warningsCount); } @Test public void testUpdate7() { - try { - CellDesignerSpecies<?> species = new CellDesignerSpecies<GenericProtein>(); - CellDesignerSpecies<?> species2 = new CellDesignerSpecies<GenericProtein>(); - species2.addSynonym("syn"); - species2.addFormerSymbol("sym"); - species.update(species2); - int warningsCount = getWarnings().size(); - assertEquals(0, warningsCount); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + CellDesignerSpecies<?> species = new CellDesignerSpecies<GenericProtein>(); + CellDesignerSpecies<?> species2 = new CellDesignerSpecies<GenericProtein>(); + species2.addSynonym("syn"); + species2.addFormerSymbol("sym"); + species.update(species2); + int warningsCount = getWarnings().size(); + assertEquals(0, warningsCount); + } + + @Test(expected = InvalidArgumentException.class) + public void testSetInvalidAmount() { + CellDesignerSpecies<?> species = new CellDesignerSpecies<GenericProtein>(); + species.setInitialAmount("a1"); } @Test public void testSetInitialAmount() { - try { - CellDesignerSpecies<?> species = new CellDesignerSpecies<GenericProtein>(); - species.setInitialAmount("1"); - assertEquals(1, species.getInitialAmount(), Configuration.EPSILON); - try { - species.setInitialAmount("a1"); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - } - species.setInitialAmount("1"); - species.setInitialAmount((String) null); - assertNull(species.getInitialAmount()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + CellDesignerSpecies<?> species = new CellDesignerSpecies<GenericProtein>(); + species.setInitialAmount("1"); + assertEquals(1, species.getInitialAmount(), Configuration.EPSILON); + species.setInitialAmount("1"); + species.setInitialAmount((String) null); + assertNull(species.getInitialAmount()); + } + + @Test(expected = InvalidArgumentException.class) + public void testSetInvalidCharge() { + CellDesignerSpecies<?> species = new CellDesignerSpecies<GenericProtein>(); + species.setCharge("a1"); } @Test public void testSetCharge() { - try { - CellDesignerSpecies<?> species = new CellDesignerSpecies<GenericProtein>(); - species.setCharge("1"); - assertEquals((Integer) 1, species.getCharge()); - try { - species.setCharge("a1"); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - } - species.setCharge("1"); - species.setCharge((String) null); - assertNull(species.getCharge()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + CellDesignerSpecies<?> species = new CellDesignerSpecies<GenericProtein>(); + species.setCharge("1"); + assertEquals((Integer) 1, species.getCharge()); + species.setCharge("1"); + species.setCharge((String) null); + assertNull(species.getCharge()); + } + + @Test(expected = InvalidArgumentException.class) + public void testSetInvalidOnlySubstanceUnits() { + CellDesignerSpecies<?> species = new CellDesignerSpecies<GenericProtein>(); + species.setOnlySubstanceUnits("a1"); } @Test public void testSetOnlySubstanceUnits() { - try { - CellDesignerSpecies<?> species = new CellDesignerSpecies<GenericProtein>(); - species.setOnlySubstanceUnits("true"); - assertTrue(species.getOnlySubstanceUnits()); - try { - species.setOnlySubstanceUnits("a1"); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - } - species.setOnlySubstanceUnits("false"); - assertFalse(species.getOnlySubstanceUnits()); - - species.setOnlySubstanceUnits("true"); - species.setOnlySubstanceUnits((String) null); - assertFalse(species.getOnlySubstanceUnits()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + CellDesignerSpecies<?> species = new CellDesignerSpecies<GenericProtein>(); + species.setOnlySubstanceUnits("true"); + assertTrue(species.getOnlySubstanceUnits()); + species.setOnlySubstanceUnits("false"); + assertFalse(species.getOnlySubstanceUnits()); + + species.setOnlySubstanceUnits("true"); + species.setOnlySubstanceUnits((String) null); + assertFalse(species.getOnlySubstanceUnits()); + } + + @Test(expected = InvalidArgumentException.class) + public void testSetInvalidInitialConcentration() { + CellDesignerSpecies<?> species = new CellDesignerSpecies<GenericProtein>(); + species.setInitialConcentration("a1"); } @Test public void testSetInitialConcentration() { - try { - CellDesignerSpecies<?> species = new CellDesignerSpecies<GenericProtein>(); - species.setInitialConcentration("1"); - assertEquals(1, species.getInitialConcentration(), Configuration.EPSILON); - try { - species.setInitialConcentration("a1"); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - } - species.setInitialConcentration("1"); - species.setInitialConcentration((String) null); - assertNull(species.getInitialConcentration()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + CellDesignerSpecies<?> species = new CellDesignerSpecies<GenericProtein>(); + species.setInitialConcentration("1"); + assertEquals(1, species.getInitialConcentration(), Configuration.EPSILON); + species.setInitialConcentration((String) null); + assertNull(species.getInitialConcentration()); } - @Test + @Test(expected = NotImplementedException.class) public void testCreateInvalidElement() { - try { - CellDesignerSpecies<?> complex = new CellDesignerSpecies<Rna>(); - complex.createModelElement("id"); - fail("Exception expected"); - } catch (NotImplementedException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + CellDesignerSpecies<?> complex = new CellDesignerSpecies<Rna>(); + complex.createModelElement("id"); } } diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/TruncatedProteinTest.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/TruncatedProteinTest.java index d7a38ce9f31dc7fab174c138867b86fc614d51cd..ed7f2d903c7746b21b72e29cedb711f6dadf118f 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/TruncatedProteinTest.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/TruncatedProteinTest.java @@ -1,70 +1,48 @@ package lcsb.mapviewer.converter.model.celldesigner.structure; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.mockito.Mockito; import lcsb.mapviewer.common.exception.NotImplementedException; +import lcsb.mapviewer.converter.model.celldesigner.CellDesignerTestFunctions; import lcsb.mapviewer.model.map.species.TruncatedProtein; -public class TruncatedProteinTest { - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testSerialization() { - try { - SerializationUtils.serialize(new CellDesignerTruncatedProtein()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testConstructor() { - try { - CellDesignerTruncatedProtein species = new CellDesignerTruncatedProtein(new CellDesignerSpecies<TruncatedProtein>()); - assertNotNull(species); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testCopy1() { - try { - CellDesignerTruncatedProtein species = new CellDesignerTruncatedProtein(new CellDesignerSpecies<TruncatedProtein>()).copy(); - assertNotNull(species); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testCopy2() { - try { - CellDesignerTruncatedProtein protein = Mockito.spy(CellDesignerTruncatedProtein.class); - protein.copy(); - fail("Exception expected"); - } catch (NotImplementedException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } +public class TruncatedProteinTest extends CellDesignerTestFunctions { + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testSerialization() { + SerializationUtils.serialize(new CellDesignerTruncatedProtein()); + } + + @Test + public void testConstructor() { + CellDesignerTruncatedProtein species = new CellDesignerTruncatedProtein( + new CellDesignerSpecies<TruncatedProtein>()); + assertNotNull(species); + } + + @Test + public void testCopy1() { + CellDesignerTruncatedProtein species = new CellDesignerTruncatedProtein(new CellDesignerSpecies<TruncatedProtein>()) + .copy(); + assertNotNull(species); + } + + @Test(expected = NotImplementedException.class) + public void testCopy2() { + CellDesignerTruncatedProtein protein = Mockito.spy(CellDesignerTruncatedProtein.class); + protein.copy(); + } } diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/UnknownTest.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/UnknownTest.java index bdf5cd4c26dff407ae56c72c9356bb81c8cb1879..0f898b7e363fa09acf5092ee6359348e6a767c1b 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/UnknownTest.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/UnknownTest.java @@ -1,70 +1,46 @@ package lcsb.mapviewer.converter.model.celldesigner.structure; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.mockito.Mockito; import lcsb.mapviewer.common.exception.NotImplementedException; +import lcsb.mapviewer.converter.model.celldesigner.CellDesignerTestFunctions; import lcsb.mapviewer.model.map.species.Unknown; -public class UnknownTest { - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testSerialization() { - try { - SerializationUtils.serialize(new CellDesignerUnknown()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testConstructor1() { - try { - CellDesignerUnknown degraded = new CellDesignerUnknown(new CellDesignerSpecies<Unknown>()); - assertNotNull(degraded); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testCopy() { - try { - CellDesignerUnknown degraded = new CellDesignerUnknown().copy(); - assertNotNull(degraded); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testInvalidCopy() { - try { - CellDesignerUnknown unknown = Mockito.spy(CellDesignerUnknown.class); - unknown.copy(); - fail("Exception expected"); - } catch (NotImplementedException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } +public class UnknownTest extends CellDesignerTestFunctions { + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testSerialization() { + SerializationUtils.serialize(new CellDesignerUnknown()); + } + + @Test + public void testConstructor1() { + CellDesignerUnknown degraded = new CellDesignerUnknown(new CellDesignerSpecies<Unknown>()); + assertNotNull(degraded); + } + + @Test + public void testCopy() { + CellDesignerUnknown degraded = new CellDesignerUnknown().copy(); + assertNotNull(degraded); + } + + @Test(expected = NotImplementedException.class) + public void testInvalidCopy() { + CellDesignerUnknown unknown = Mockito.spy(CellDesignerUnknown.class); + unknown.copy(); + } } diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/types/ModifierTypeUtilsTest.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/types/ModifierTypeUtilsTest.java index e85f044923e92833348fc3c5d4dd539405b92277..7a87b706614692417fbff4e8990e2da63544db0d 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/types/ModifierTypeUtilsTest.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/types/ModifierTypeUtilsTest.java @@ -1,34 +1,22 @@ package lcsb.mapviewer.converter.model.celldesigner.types; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import java.awt.geom.Point2D; import java.lang.reflect.Field; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.mockito.Mockito; -import lcsb.mapviewer.common.exception.InvalidArgumentException; -import lcsb.mapviewer.common.exception.InvalidStateException; -import lcsb.mapviewer.common.exception.NotImplementedException; +import lcsb.mapviewer.common.exception.*; +import lcsb.mapviewer.converter.model.celldesigner.CellDesignerTestFunctions; import lcsb.mapviewer.converter.model.celldesigner.structure.CellDesignerElement; import lcsb.mapviewer.model.graphics.PolylineData; -import lcsb.mapviewer.model.map.reaction.AndOperator; -import lcsb.mapviewer.model.map.reaction.Modifier; -import lcsb.mapviewer.model.map.reaction.NodeOperator; -import lcsb.mapviewer.model.map.reaction.Product; -import lcsb.mapviewer.model.map.reaction.Reactant; -import lcsb.mapviewer.model.map.reaction.Reaction; +import lcsb.mapviewer.model.map.reaction.*; import lcsb.mapviewer.model.map.species.GenericProtein; import lcsb.mapviewer.model.map.species.Species; -public class ModifierTypeUtilsTest { +public class ModifierTypeUtilsTest extends CellDesignerTestFunctions { ModifierTypeUtils utils = new ModifierTypeUtils(); @@ -58,74 +46,36 @@ public class ModifierTypeUtilsTest { assertNull(type); } - @Test + @Test(expected = InvalidArgumentException.class) public void testGetTargetLineIndexByInvalidModifier() { - try { - utils.getTargetLineIndexByModifier(invalidModifier); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - assertTrue(e.getMessage().contains("Unknown modifier class")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - + utils.getTargetLineIndexByModifier(invalidModifier); } - @Test + @Test(expected = InvalidArgumentException.class) public void testGetTargetLineIndexByInvalidModifier2() { - try { - NodeOperator operator = new AndOperator(); - operator.addInput(new Reactant()); - utils.getTargetLineIndexByModifier(operator); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - assertTrue(e.getMessage().contains("Invalid NodeOperator")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + NodeOperator operator = new AndOperator(); + operator.addInput(new Reactant()); + utils.getTargetLineIndexByModifier(operator); } - @Test + @Test(expected = InvalidArgumentException.class) public void testGetTargetLineIndexByInvalidModifier3() { - try { - NodeOperator operator = new AndOperator(); - operator.addInput(invalidModifier); - utils.getTargetLineIndexByModifier(operator); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - assertTrue(e.getMessage().contains("Unknown modifier class")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + NodeOperator operator = new AndOperator(); + operator.addInput(invalidModifier); + utils.getTargetLineIndexByModifier(operator); } @Test public void testGetAnchorPointOnReactionRectByInvalidType() { - try { - Reaction reaction = createDummyReaction(); - Point2D point = utils.getAnchorPointOnReactionRect(reaction, "0,0"); - assertNotNull(point); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Reaction reaction = createDummyReaction(); + Point2D point = utils.getAnchorPointOnReactionRect(reaction, "0,0"); + assertNotNull(point); } - @Test + @Test(expected = InvalidArgumentException.class) public void testGetAnchorPointOnReactionRectByInvalidType2() { - try { - Reaction reaction = createDummyReaction(); - utils.getAnchorPointOnReactionRect(reaction, "0"); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - assertTrue(e.getMessage().contains("Invalid targetLineIndex")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Reaction reaction = createDummyReaction(); + utils.getAnchorPointOnReactionRect(reaction, "0"); } private Reaction createDummyReaction() { @@ -140,66 +90,34 @@ public class ModifierTypeUtilsTest { return reaction; } - @Test + @Test(expected = InvalidArgumentException.class) public void testGetAnchorPointOnReactionRectByInvalidType3() { - try { - Reaction reaction = createDummyReaction(); - utils.getAnchorPointOnReactionRect(reaction, "10,10"); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - assertTrue(e.getMessage().contains("Unknown targetLineIndex")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Reaction reaction = createDummyReaction(); + utils.getAnchorPointOnReactionRect(reaction, "10,10"); } - @Test + @Test(expected = InvalidArgumentException.class) public void testUpdateLineEndPointForInvalidModifier() { - try { - utils.updateLineEndPoint(invalidModifier); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - assertTrue(e.getMessage().contains("Unknown modifier class")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + utils.updateLineEndPoint(invalidModifier); } - @Test + @Test(expected = InvalidArgumentException.class) public void testUpdateLineEndPointForInvalidModifier2() { - try { - NodeOperator operator = new AndOperator(); - operator.addInput(new Product()); - operator.addInput(invalidModifier); - utils.updateLineEndPoint(operator); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - assertTrue(e.getMessage().contains("Unknown modifier class")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + NodeOperator operator = new AndOperator(); + operator.addInput(new Product()); + operator.addInput(invalidModifier); + utils.updateLineEndPoint(operator); } - @Test + @Test(expected = InvalidArgumentException.class) public void testUpdateLineEndPointForInvalidModifier3() { - try { - NodeOperator operator = new AndOperator(); - operator.addInput(new Product()); - operator.addInput(new Product()); - utils.updateLineEndPoint(operator); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - assertTrue(e.getMessage().contains("Operator contains invalid input")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + NodeOperator operator = new AndOperator(); + operator.addInput(new Product()); + operator.addInput(new Product()); + utils.updateLineEndPoint(operator); } - @Test + @Test(expected = InvalidStateException.class) public void testCreateInvalidModifierForStringType2() throws Exception { // artificial implementation of Modifier that is invalid class InvalidModifier extends Modifier { @@ -229,12 +147,6 @@ public class ModifierTypeUtilsTest { // and check if we catch properly information about problematic // implementation utils.createModifierForStringType(typeToModify.getStringName(), new GenericProtein("id")); - fail("Exceptione expected"); - } catch (InvalidStateException e) { - assertTrue(e.getMessage().contains("Problem with instantiation of Modifier class")); - } catch (Exception e) { - e.printStackTrace(); - throw e; } finally { // restore correct values for the modified type (if not then other test // might fail...) @@ -244,14 +156,9 @@ public class ModifierTypeUtilsTest { } } - @Test + @Test(expected = InvalidArgumentException.class) public void testCreateModifierForStringType2() throws Exception { - try { - utils.createModifierForStringType("unjkType", null); - fail("Exceptione expected"); - } catch (InvalidArgumentException e) { - assertTrue(e.getMessage().contains("Unknown modifier type")); - } + utils.createModifierForStringType("unjkType", null); } } diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/types/OperatorTypeUtilsTest.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/types/OperatorTypeUtilsTest.java index 0da1a339e7e44e8c76430f9953eecfa673240e3d..fefc4b51cbbade0d2082b1525a8f84b86060e392 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/types/OperatorTypeUtilsTest.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/types/OperatorTypeUtilsTest.java @@ -1,24 +1,18 @@ package lcsb.mapviewer.converter.model.celldesigner.types; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import java.lang.reflect.Field; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.mockito.Mockito; -import lcsb.mapviewer.common.exception.InvalidArgumentException; -import lcsb.mapviewer.common.exception.InvalidStateException; -import lcsb.mapviewer.common.exception.NotImplementedException; +import lcsb.mapviewer.common.exception.*; +import lcsb.mapviewer.converter.model.celldesigner.CellDesignerTestFunctions; import lcsb.mapviewer.model.map.reaction.Modifier; import lcsb.mapviewer.model.map.reaction.NodeOperator; -public class OperatorTypeUtilsTest { +public class OperatorTypeUtilsTest extends CellDesignerTestFunctions { OperatorTypeUtils utils = new OperatorTypeUtils(); @@ -36,7 +30,6 @@ public class OperatorTypeUtilsTest { @Test public void testGetUnknownOperatorTypeForClazz() { - OperatorType result = utils .getOperatorTypeForClazz(Mockito.mock(NodeOperator.class, Mockito.CALLS_REAL_METHODS).getClass()); @@ -58,17 +51,12 @@ public class OperatorTypeUtilsTest { assertNull(result); } - @Test + @Test(expected = InvalidArgumentException.class) public void testCreateUnknownModifierForStringType() { - try { - utils.createModifierForStringType("blabla"); - fail("Exceptione expected"); - } catch (InvalidArgumentException e) { - assertTrue(e.getMessage().contains("Unknown modifier type")); - } + utils.createModifierForStringType("blabla"); } - @Test + @Test(expected = InvalidStateException.class) public void testCreateInvalidModifierForStringType() throws Exception { // artificial implementation of Modifier that is invalid class InvalidModifier extends Modifier { @@ -93,12 +81,6 @@ public class OperatorTypeUtilsTest { // and check if we catch properly information about problematic // implementation utils.createModifierForStringType(typeToModify.getStringName()); - fail("Exceptione expected"); - } catch (InvalidStateException e) { - assertTrue(e.getMessage().contains("Problem with instantiation of NodeOperator class")); - } catch (Exception e) { - e.printStackTrace(); - throw e; } finally { // restore correct values for the modified type (if not then other test // might fail...) diff --git a/converter-SBGNML/src/test/java/lcsb/mapviewer/converter/model/sbgnml/CellDesigner2SbgnmlConversionTest.java b/converter-SBGNML/src/test/java/lcsb/mapviewer/converter/model/sbgnml/CellDesigner2SbgnmlConversionTest.java index 18ccf33c6c9c39042a09a409d6eab8f5c87d1c18..2fa931de44c4a5842435ef41757c3ddebc0424c1 100644 --- a/converter-SBGNML/src/test/java/lcsb/mapviewer/converter/model/sbgnml/CellDesigner2SbgnmlConversionTest.java +++ b/converter-SBGNML/src/test/java/lcsb/mapviewer/converter/model/sbgnml/CellDesigner2SbgnmlConversionTest.java @@ -3,89 +3,87 @@ package lcsb.mapviewer.converter.model.sbgnml; import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; +import java.nio.file.*; import java.util.ArrayList; import java.util.Collection; import org.apache.commons.io.FileUtils; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; -import lcsb.mapviewer.converter.ConverterParams; import lcsb.mapviewer.converter.Converter; +import lcsb.mapviewer.converter.ConverterParams; import lcsb.mapviewer.converter.model.celldesigner.CellDesignerXmlParser; import lcsb.mapviewer.model.map.model.Model; @RunWith(Parameterized.class) -public class CellDesigner2SbgnmlConversionTest { +public class CellDesigner2SbgnmlConversionTest extends SbgnmlTestFunctions { - private static Logger logger = LogManager.getLogger(CellDesigner2SbgnmlConversionTest.class.getName()); + private static Logger logger = LogManager.getLogger(CellDesigner2SbgnmlConversionTest.class.getName()); - private Path testPath; + private Path testPath; - public CellDesigner2SbgnmlConversionTest(Path testPath) { - this.testPath = testPath; - } + public CellDesigner2SbgnmlConversionTest(Path testPath) { + this.testPath = testPath; + } - @Parameters(name = "{index} : {0}") - public static Collection<Object[]> data() throws IOException { - Collection<Object[]> data = new ArrayList<>(); - Files.walk(Paths.get("../converter-CellDesigner/testFiles")).forEach(fPath -> { - if (Files.isRegularFile(fPath) && fPath.toString().endsWith(".xml")&& fPath.toString().indexOf("invalid")==-1) { - try { - String tempPath = fPath.toString().substring(fPath.toString().indexOf("testFiles") + "testFiles".length() + 1); - if (!tempPath.contains("_full")) { - String content = FileUtils.readFileToString(fPath.toFile(), StandardCharsets.UTF_8); - if (content.indexOf("xmlns:celldesigner") >= 0) { - data.add(new Object[] { fPath }); - } - } - } catch (Exception e) { - throw new RuntimeException(); - } - } - }); - return data; - } + @Parameters(name = "{index} : {0}") + public static Collection<Object[]> data() throws IOException { + Collection<Object[]> data = new ArrayList<>(); + Files.walk(Paths.get("../converter-CellDesigner/testFiles")).forEach(fPath -> { + if (Files.isRegularFile(fPath) && fPath.toString().endsWith(".xml") + && fPath.toString().indexOf("invalid") == -1) { + try { + String tempPath = fPath.toString() + .substring(fPath.toString().indexOf("testFiles") + "testFiles".length() + 1); + if (!tempPath.contains("_full")) { + String content = FileUtils.readFileToString(fPath.toFile(), StandardCharsets.UTF_8); + if (content.indexOf("xmlns:celldesigner") >= 0) { + data.add(new Object[] { fPath }); + } + } + } catch (Exception e) { + throw new RuntimeException(); + } + } + }); + return data; + } - private void parseAndExport(Path testPath) throws Exception { - Converter cellDesignerConverter = new CellDesignerXmlParser(); - Converter sbgnmlConverter = new SbgnmlXmlConverter(); + private void parseAndExport(Path testPath) throws Exception { + Converter cellDesignerConverter = new CellDesignerXmlParser(); + Converter sbgnmlConverter = new SbgnmlXmlConverter(); - String testName = ""; - Path tempPath = testPath; - while (!tempPath.getParent().toString().endsWith("testFiles")) { - // Add parent folder to path - tempPath = tempPath.getParent(); - testName = tempPath.getFileName().toString().concat("/").concat(testName); - } - testName = testName.concat(testPath.getFileName().toString().substring(0, testPath.getFileName().toString().indexOf(".xml"))); - Model model; - try { - model = cellDesignerConverter.createModel(new ConverterParams().filename("../converter-CellDesigner/testFiles/".concat(testName).concat(".xml"))); - } catch (Exception ex) { - logger.warn("Problem encountered when parsing CellDesigner file: " + testName); - return; - } + String testName = ""; + Path tempPath = testPath; + while (!tempPath.getParent().toString().endsWith("testFiles")) { + // Add parent folder to path + tempPath = tempPath.getParent(); + testName = tempPath.getFileName().toString().concat("/").concat(testName); + } + testName = testName + .concat(testPath.getFileName().toString().substring(0, testPath.getFileName().toString().indexOf(".xml"))); + Model model; + try { + model = cellDesignerConverter.createModel( + new ConverterParams().filename("../converter-CellDesigner/testFiles/".concat(testName).concat(".xml"))); + } catch (Exception ex) { + logger.warn("Problem encountered when parsing CellDesigner file: " + testName); + return; + } - String outputFile = "testFiles/sbgnmlExporterTestFiles/fromCellDesigner/".concat(testName).concat(".sbgn"); - sbgnmlConverter.model2File(model, outputFile); - new File(outputFile).delete(); - } + String outputFile = "testFiles/sbgnmlExporterTestFiles/fromCellDesigner/".concat(testName).concat(".sbgn"); + sbgnmlConverter.model2File(model, outputFile); + new File(outputFile).delete(); + } - @Test - public void test() throws Exception { - try { - parseAndExport(testPath); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } + @Test + public void test() throws Exception { + parseAndExport(testPath); + } } diff --git a/converter-SBGNML/src/test/java/lcsb/mapviewer/converter/model/sbgnml/CellDesignerToSbgnTest.java b/converter-SBGNML/src/test/java/lcsb/mapviewer/converter/model/sbgnml/CellDesignerToSbgnTest.java index b2b906eea4777ca54aa48b970f749d9b33f0859c..57144608ea3d1ff298bc1db3ebe6039b506ee3e9 100644 --- a/converter-SBGNML/src/test/java/lcsb/mapviewer/converter/model/sbgnml/CellDesignerToSbgnTest.java +++ b/converter-SBGNML/src/test/java/lcsb/mapviewer/converter/model/sbgnml/CellDesignerToSbgnTest.java @@ -1,19 +1,17 @@ package lcsb.mapviewer.converter.model.sbgnml; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.Assert.*; import java.io.File; import java.io.FileInputStream; import org.apache.commons.io.IOUtils; -import org.apache.logging.log4j.*; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.junit.*; -import lcsb.mapviewer.converter.ConverterParams; import lcsb.mapviewer.converter.Converter; +import lcsb.mapviewer.converter.ConverterParams; import lcsb.mapviewer.converter.model.celldesigner.CellDesignerXmlParser; import lcsb.mapviewer.model.map.compartment.Compartment; import lcsb.mapviewer.model.map.model.Model; @@ -21,7 +19,7 @@ import lcsb.mapviewer.model.map.species.Element; import lcsb.mapviewer.model.map.species.Protein; import lcsb.mapviewer.modelutils.map.ElementUtils; -public class CellDesignerToSbgnTest { +public class CellDesignerToSbgnTest extends SbgnmlTestFunctions { Logger logger = LogManager.getLogger(CellDesignerToSbgnTest.class); ElementUtils eu = new ElementUtils(); @@ -35,103 +33,81 @@ public class CellDesignerToSbgnTest { @Test public void testSample() throws Exception { - try { - Converter converter = new CellDesignerXmlParser(); - Converter converter2 = new SbgnmlXmlConverter(); - - Model model = converter.createModel(new ConverterParams().filename("testFiles/cellDesigner/sample.xml")); + Converter converter = new CellDesignerXmlParser(); + Converter converter2 = new SbgnmlXmlConverter(); - String output = File.createTempFile("temp-sbgn-output", ".sbgn").getAbsolutePath(); - converter2.model2File(model, output); + Model model = converter.createModel(new ConverterParams().filename("testFiles/cellDesigner/sample.xml")); - try (FileInputStream inputStream = new FileInputStream(output)) { - String everything = IOUtils.toString(inputStream, "UTF-8"); - assertTrue("Warnings are not exported into sbgn", everything.contains("Element type is not supported")); - } - converter2.createModel(new ConverterParams().filename(output)); + String output = File.createTempFile("temp-sbgn-output", ".sbgn").getAbsolutePath(); + converter2.model2File(model, output); - new File(output).delete(); - } catch (Exception e) { - e.printStackTrace(); - throw e; + try (FileInputStream inputStream = new FileInputStream(output)) { + String everything = IOUtils.toString(inputStream, "UTF-8"); + assertTrue("Warnings are not exported into sbgn", everything.contains("Element type is not supported")); } + converter2.createModel(new ConverterParams().filename(output)); + new File(output).delete(); } @Test public void testSample2() throws Exception { - try { - Converter converter = new CellDesignerXmlParser(); - Converter converter2 = new SbgnmlXmlConverter(); - - Model model = converter.createModel(new ConverterParams().filename("testFiles/cellDesigner/bubbles.xml")); - - String output = File.createTempFile("temp-sbgn-output", ".sbgn").getAbsolutePath(); - converter2.model2File(model, output); - new File(output).delete(); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Converter converter = new CellDesignerXmlParser(); + Converter converter2 = new SbgnmlXmlConverter(); + + Model model = converter.createModel(new ConverterParams().filename("testFiles/cellDesigner/bubbles.xml")); + + String output = File.createTempFile("temp-sbgn-output", ".sbgn").getAbsolutePath(); + converter2.model2File(model, output); + new File(output).delete(); } @Test public void testCompartmentsExport() throws Exception { - try { - Converter converter = new CellDesignerXmlParser(); - Converter converter2 = new SbgnmlXmlConverter(); + Converter converter = new CellDesignerXmlParser(); + Converter converter2 = new SbgnmlXmlConverter(); - Model model = converter.createModel(new ConverterParams().filename("testFiles/cellDesigner/neuron.xml")); + Model model = converter.createModel(new ConverterParams().filename("testFiles/cellDesigner/neuron.xml")); - String output = File.createTempFile("temp-sbgn-output", ".sbgn").getAbsolutePath(); - converter2.model2File(model, output); + String output = File.createTempFile("temp-sbgn-output", ".sbgn").getAbsolutePath(); + converter2.model2File(model, output); - converter2.createModel(new ConverterParams().filename(output)); + converter2.createModel(new ConverterParams().filename(output)); - String fileContent; - try (FileInputStream inputStream = new FileInputStream(output)) { - fileContent = IOUtils.toString(inputStream, "UTF-8"); - } + String fileContent; + try (FileInputStream inputStream = new FileInputStream(output)) { + fileContent = IOUtils.toString(inputStream, "UTF-8"); + } - for (Element element : model.getElements()) { - if (element instanceof Compartment) { - assertTrue(eu.getElementTag(element) + " comparmtent is not exported", - fileContent.contains(element.getElementId())); - } + for (Element element : model.getElements()) { + if (element instanceof Compartment) { + assertTrue(eu.getElementTag(element) + " comparmtent is not exported", + fileContent.contains(element.getElementId())); } - - new File(output).delete(); - } catch (Exception e) { - e.printStackTrace(); - throw e; } + new File(output).delete(); } @Test public void testProteinState() throws Exception { - try { - Converter converter = new CellDesignerXmlParser(); - Converter converter2 = new SbgnmlXmlConverter(); + Converter converter = new CellDesignerXmlParser(); + Converter converter2 = new SbgnmlXmlConverter(); - Model model = converter.createModel(new ConverterParams().filename("testFiles/cellDesigner/state.xml")); + Model model = converter.createModel(new ConverterParams().filename("testFiles/cellDesigner/state.xml")); - String output = File.createTempFile("temp-sbgn-output", ".sbgn").getAbsolutePath(); - converter2.model2File(model, output); + String output = File.createTempFile("temp-sbgn-output", ".sbgn").getAbsolutePath(); + converter2.model2File(model, output); - Model model2 = converter2.createModel(new ConverterParams().filename(output)); + Model model2 = converter2.createModel(new ConverterParams().filename(output)); - Protein protein1 = model.getElementByElementId("sa1"); - Protein protein2 = model2.getElementByElementId("sa1"); - assertEquals(protein1.getStructuralState(), protein2.getStructuralState()); + Protein protein1 = model.getElementByElementId("sa1"); + Protein protein2 = model2.getElementByElementId("sa1"); + assertEquals(protein1.getStructuralState(), protein2.getStructuralState()); - protein1 = model.getElementByElementId("sa2"); - protein2 = model2.getElementByElementId("sa2"); - assertEquals(protein1.getStructuralState(), protein2.getStructuralState()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + protein1 = model.getElementByElementId("sa2"); + protein2 = model2.getElementByElementId("sa2"); + assertEquals(protein1.getStructuralState(), protein2.getStructuralState()); } } diff --git a/converter-SBGNML/src/test/java/lcsb/mapviewer/converter/model/sbgnml/SbgnmlTestFunctions.java b/converter-SBGNML/src/test/java/lcsb/mapviewer/converter/model/sbgnml/SbgnmlTestFunctions.java index 1631bb0541deebd1f794e7a8de45b33d2d433562..c0d037d571c9b535267b139a3417d44904b97c51 100644 --- a/converter-SBGNML/src/test/java/lcsb/mapviewer/converter/model/sbgnml/SbgnmlTestFunctions.java +++ b/converter-SBGNML/src/test/java/lcsb/mapviewer/converter/model/sbgnml/SbgnmlTestFunctions.java @@ -4,12 +4,17 @@ import java.awt.Desktop; import java.io.File; import java.nio.file.Files; -import lcsb.mapviewer.converter.graphics.AbstractImageGenerator; -import lcsb.mapviewer.converter.graphics.NormalImageGenerator; -import lcsb.mapviewer.converter.graphics.PngImageGenerator; +import org.junit.Rule; + +import lcsb.mapviewer.common.UnitTestFailedWatcher; +import lcsb.mapviewer.converter.graphics.*; import lcsb.mapviewer.model.map.model.Model; public class SbgnmlTestFunctions { + + @Rule + public UnitTestFailedWatcher unitTestFailedWatcher = new UnitTestFailedWatcher(); + protected void showImage(Model model) throws Exception { String dir = Files.createTempDirectory("sbml-temp-images-dir").toFile().getAbsolutePath(); AbstractImageGenerator.Params params = new AbstractImageGenerator.Params().height(model.getHeight()) diff --git a/converter-SBGNML/src/test/java/lcsb/mapviewer/converter/model/sbgnml/SbgnmlXmlExporterTest.java b/converter-SBGNML/src/test/java/lcsb/mapviewer/converter/model/sbgnml/SbgnmlXmlExporterTest.java index 5cc4850be5dbf279a99ccbc162e1beb35b7562b1..6618aa6b875d2537e726727d023248770e913141 100644 --- a/converter-SBGNML/src/test/java/lcsb/mapviewer/converter/model/sbgnml/SbgnmlXmlExporterTest.java +++ b/converter-SBGNML/src/test/java/lcsb/mapviewer/converter/model/sbgnml/SbgnmlXmlExporterTest.java @@ -7,63 +7,52 @@ import java.nio.file.Paths; import java.util.ArrayList; import java.util.Collection; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; -import lcsb.mapviewer.converter.ConverterParams; import lcsb.mapviewer.converter.Converter; +import lcsb.mapviewer.converter.ConverterParams; import lcsb.mapviewer.model.map.model.Model; @RunWith(Parameterized.class) -public class SbgnmlXmlExporterTest { - - Logger logger = LogManager.getLogger(SbgnmlXmlExporterTest.class.getName()); +public class SbgnmlXmlExporterTest extends SbgnmlTestFunctions { - private String testName; + Logger logger = LogManager.getLogger(SbgnmlXmlExporterTest.class.getName()); - public SbgnmlXmlExporterTest(String testName) { - this.testName = testName; - } + private String testName; - @Parameters(name = "{index} : {0}") - public static Collection<Object[]> data() throws IOException { - Collection<Object[]> data = new ArrayList<Object[]>(); - Files.walk(Paths.get("testFiles/sbgnmlParserTestFiles/sbgnmlFiles")).forEach(fPath -> { - if (Files.isRegularFile(fPath) && fPath.toString().endsWith(".sbgn")) { - String tName = fPath.getFileName().toString().substring(0, fPath.getFileName().toString().indexOf(".sbgn")); - data.add(new Object[] { tName }); - } - }); - return data; - } + public SbgnmlXmlExporterTest(String testName) { + this.testName = testName; + } - private void parseAndExport(String testName) throws Exception { - Converter converter = new SbgnmlXmlConverter(); + @Parameters(name = "{index} : {0}") + public static Collection<Object[]> data() throws IOException { + Collection<Object[]> data = new ArrayList<Object[]>(); + Files.walk(Paths.get("testFiles/sbgnmlParserTestFiles/sbgnmlFiles")).forEach(fPath -> { + if (Files.isRegularFile(fPath) && fPath.toString().endsWith(".sbgn")) { + String tName = fPath.getFileName().toString().substring(0, fPath.getFileName().toString().indexOf(".sbgn")); + data.add(new Object[] { tName }); + } + }); + return data; + } - Model model = converter.createModel(new ConverterParams().filename("testFiles/sbgnmlParserTestFiles/sbgnmlFiles/".concat(testName).concat(".sbgn"))); + private void parseAndExport(String testName) throws Exception { + Converter converter = new SbgnmlXmlConverter(); - converter.model2File(model, File.createTempFile("temp-sbgn-output", ".sbgn").getAbsolutePath()); - } + Model model = converter.createModel(new ConverterParams() + .filename("testFiles/sbgnmlParserTestFiles/sbgnmlFiles/".concat(testName).concat(".sbgn"))); - /* - * @Test public void simpleTest() throws JAXBException { - * parseAndExport("simpleTest"); } - * - * @Test public void VANTEDdiagram() throws JAXBException { - * parseAndExport("VANTEDdiagram"); } - */ + converter.model2File(model, File.createTempFile("temp-sbgn-output", ".sbgn").getAbsolutePath()); + } - @Test - public void test() throws Exception { - try { - parseAndExport(testName); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } + @Test + public void test() throws Exception { + parseAndExport(testName); + } } diff --git a/converter-SBGNML/src/test/java/lcsb/mapviewer/converter/model/sbgnml/SbgnmlXmlParserTest.java b/converter-SBGNML/src/test/java/lcsb/mapviewer/converter/model/sbgnml/SbgnmlXmlParserTest.java index 880ee3ec45aa4556e2942845a28165c1210818fd..ea82c2e93f3a7ed97967516c94b1e028ce60f429 100644 --- a/converter-SBGNML/src/test/java/lcsb/mapviewer/converter/model/sbgnml/SbgnmlXmlParserTest.java +++ b/converter-SBGNML/src/test/java/lcsb/mapviewer/converter/model/sbgnml/SbgnmlXmlParserTest.java @@ -1,38 +1,30 @@ package lcsb.mapviewer.converter.model.sbgnml; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - -import java.io.ByteArrayInputStream; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.io.PrintWriter; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; +import static org.junit.Assert.*; + +import java.io.*; +import java.nio.file.*; import java.util.ArrayList; import java.util.Collection; import org.apache.commons.io.FileUtils; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; -import lcsb.mapviewer.converter.ConverterParams; import lcsb.mapviewer.converter.Converter; -import lcsb.mapviewer.converter.graphics.AbstractImageGenerator; -import lcsb.mapviewer.converter.graphics.NormalImageGenerator; -import lcsb.mapviewer.converter.graphics.PngImageGenerator; +import lcsb.mapviewer.converter.ConverterParams; +import lcsb.mapviewer.converter.graphics.*; import lcsb.mapviewer.converter.model.celldesigner.CellDesignerXmlParser; import lcsb.mapviewer.model.map.model.Model; import lcsb.mapviewer.model.map.model.ModelComparator; import lcsb.mapviewer.model.map.reaction.ReactionComparator; @RunWith(Parameterized.class) -public class SbgnmlXmlParserTest { +public class SbgnmlXmlParserTest extends SbgnmlTestFunctions { Logger logger = LogManager.getLogger(SbgnmlXmlParserTest.class.getName()); @@ -56,54 +48,48 @@ public class SbgnmlXmlParserTest { @Test public void createModelTest() throws Exception { - try { - String dir = Files.createTempDirectory("sbgn-temp-images-dir").toFile().getAbsolutePath(); - - Converter converter = new SbgnmlXmlConverter(); - - Model model = converter.createModel(new ConverterParams().filename(filePath.toString())); - - // Create and display image of parsed map - AbstractImageGenerator.Params params = new AbstractImageGenerator.Params().height(model.getHeight()) - .width(model.getWidth()).nested(true).scale(1).level(20).x(0).y(0).model(model); - NormalImageGenerator nig = new PngImageGenerator(params); - String pngFilePath = dir + "/" - .concat(filePath.getFileName().toString().substring(0, filePath.getFileName().toString().indexOf(".sbgn"))) - .concat(".png"); - nig.saveToFile(pngFilePath); - - CellDesignerXmlParser cellDesignerXmlParser = new CellDesignerXmlParser(); - String xmlString = cellDesignerXmlParser.model2String(model); - - String cellDesignerFilePath = dir + "/" - .concat(filePath.getFileName().toString().substring(0, filePath.getFileName().toString().indexOf(".sbgn"))) - .concat(".xml"); - PrintWriter out = new PrintWriter(cellDesignerFilePath); - out.print(xmlString); - out.close(); - - InputStream is = new ByteArrayInputStream(xmlString.getBytes("UTF-8")); - - Model model2 = cellDesignerXmlParser.createModel(new ConverterParams().inputStream(is).sizeAutoAdjust(false)); - - AbstractImageGenerator.Params params2 = new AbstractImageGenerator.Params().height(model2.getHeight()) - .width(model2.getWidth()).nested(true).scale(1).level(20).x(0).y(0).model(model2); - NormalImageGenerator nig2 = new PngImageGenerator(params2); - String pngFilePath2 = dir + "/" - .concat(filePath.getFileName().toString().substring(0, filePath.getFileName().toString().indexOf(".sbgn"))) - .concat("_2.png"); - nig2.saveToFile(pngFilePath2); - - assertNotNull(model2); - ModelComparator comparator = new ModelComparator(1.0); - comparator.getReactionSetComparator().setObjectComparator(new ReactionComparator(1.0, true)); - assertEquals(0, comparator.compare(model, model2)); - FileUtils.deleteDirectory(new File(dir)); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String dir = Files.createTempDirectory("sbgn-temp-images-dir").toFile().getAbsolutePath(); + + Converter converter = new SbgnmlXmlConverter(); + + Model model = converter.createModel(new ConverterParams().filename(filePath.toString())); + + // Create and display image of parsed map + AbstractImageGenerator.Params params = new AbstractImageGenerator.Params().height(model.getHeight()) + .width(model.getWidth()).nested(true).scale(1).level(20).x(0).y(0).model(model); + NormalImageGenerator nig = new PngImageGenerator(params); + String pngFilePath = dir + "/" + .concat(filePath.getFileName().toString().substring(0, filePath.getFileName().toString().indexOf(".sbgn"))) + .concat(".png"); + nig.saveToFile(pngFilePath); + + CellDesignerXmlParser cellDesignerXmlParser = new CellDesignerXmlParser(); + String xmlString = cellDesignerXmlParser.model2String(model); + + String cellDesignerFilePath = dir + "/" + .concat(filePath.getFileName().toString().substring(0, filePath.getFileName().toString().indexOf(".sbgn"))) + .concat(".xml"); + PrintWriter out = new PrintWriter(cellDesignerFilePath); + out.print(xmlString); + out.close(); + + InputStream is = new ByteArrayInputStream(xmlString.getBytes("UTF-8")); + + Model model2 = cellDesignerXmlParser.createModel(new ConverterParams().inputStream(is).sizeAutoAdjust(false)); + + AbstractImageGenerator.Params params2 = new AbstractImageGenerator.Params().height(model2.getHeight()) + .width(model2.getWidth()).nested(true).scale(1).level(20).x(0).y(0).model(model2); + NormalImageGenerator nig2 = new PngImageGenerator(params2); + String pngFilePath2 = dir + "/" + .concat(filePath.getFileName().toString().substring(0, filePath.getFileName().toString().indexOf(".sbgn"))) + .concat("_2.png"); + nig2.saveToFile(pngFilePath2); + + assertNotNull(model2); + ModelComparator comparator = new ModelComparator(1.0); + comparator.getReactionSetComparator().setObjectComparator(new ReactionComparator(1.0, true)); + assertEquals(0, comparator.compare(model, model2)); + FileUtils.deleteDirectory(new File(dir)); } } diff --git a/converter-SBGNML/src/test/java/lcsb/mapviewer/converter/model/sbgnml/SbgnmlXmlParserTest2.java b/converter-SBGNML/src/test/java/lcsb/mapviewer/converter/model/sbgnml/SbgnmlXmlParserTest2.java index 9a2a8695ab38312ec029de6578cd923f0e7eee5d..e7dc097e0c1457b99a62a62573c6d009a883ee68 100644 --- a/converter-SBGNML/src/test/java/lcsb/mapviewer/converter/model/sbgnml/SbgnmlXmlParserTest2.java +++ b/converter-SBGNML/src/test/java/lcsb/mapviewer/converter/model/sbgnml/SbgnmlXmlParserTest2.java @@ -1,9 +1,6 @@ package lcsb.mapviewer.converter.model.sbgnml; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.junit.Assert.*; import java.awt.geom.Point2D; @@ -16,15 +13,12 @@ import lcsb.mapviewer.converter.Converter; import lcsb.mapviewer.converter.ConverterParams; import lcsb.mapviewer.model.map.compartment.Compartment; import lcsb.mapviewer.model.map.model.Model; -import lcsb.mapviewer.model.map.reaction.NodeOperator; -import lcsb.mapviewer.model.map.reaction.Product; -import lcsb.mapviewer.model.map.reaction.Reactant; -import lcsb.mapviewer.model.map.reaction.Reaction; +import lcsb.mapviewer.model.map.reaction.*; import lcsb.mapviewer.model.map.species.Complex; import lcsb.mapviewer.model.map.species.GenericProtein; import lcsb.mapviewer.model.map.species.field.Residue; -public class SbgnmlXmlParserTest2 { +public class SbgnmlXmlParserTest2 extends SbgnmlTestFunctions { Logger logger = LogManager.getLogger(SbgnmlXmlParserTest2.class.getName()); @@ -48,38 +42,28 @@ public class SbgnmlXmlParserTest2 { @Test public void createModelWithCompartmentsTest() throws Exception { - try { - Converter converter = new SbgnmlXmlConverter(); - - Model model = converter - .createModel(new ConverterParams() - .filename("testFiles/sbgnmlParserTestFiles/sbgnmlFiles/elements_inside_compartment.xml")); - Complex complexInsideCompartment = model.getElementByElementId("csa1830"); - assertNotNull("Complex inside compartment has undefined compartment", complexInsideCompartment.getCompartment()); - Complex complexOutsideCompartment = model.getElementByElementId("csa1831"); - assertNull("Complex outside compartment has not null compartment", complexOutsideCompartment.getCompartment()); - Compartment compartment = model.getElementByElementId("ca107"); - assertNull("Top compartment has not null compartment", compartment.getCompartment()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Converter converter = new SbgnmlXmlConverter(); + + Model model = converter + .createModel(new ConverterParams() + .filename("testFiles/sbgnmlParserTestFiles/sbgnmlFiles/elements_inside_compartment.xml")); + Complex complexInsideCompartment = model.getElementByElementId("csa1830"); + assertNotNull("Complex inside compartment has undefined compartment", complexInsideCompartment.getCompartment()); + Complex complexOutsideCompartment = model.getElementByElementId("csa1831"); + assertNull("Complex outside compartment has not null compartment", complexOutsideCompartment.getCompartment()); + Compartment compartment = model.getElementByElementId("ca107"); + assertNull("Top compartment has not null compartment", compartment.getCompartment()); } @Test public void createModelWithZIndex() throws Exception { - try { - Converter converter = new SbgnmlXmlConverter(); - - Model model = converter - .createModel(new ConverterParams() - .filename("testFiles/sbgnmlParserTestFiles/sbgnmlFiles/elements_inside_compartment.xml")); - Complex complex = model.getElementByElementId("csa1830"); - assertNotNull(complex.getZ()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Converter converter = new SbgnmlXmlConverter(); + + Model model = converter + .createModel(new ConverterParams() + .filename("testFiles/sbgnmlParserTestFiles/sbgnmlFiles/elements_inside_compartment.xml")); + Complex complex = model.getElementByElementId("csa1830"); + assertNotNull(complex.getZ()); } @Test @@ -87,18 +71,18 @@ public class SbgnmlXmlParserTest2 { Converter converter = new SbgnmlXmlConverter(); Model model = converter .createModel(new ConverterParams().filename("testFiles/sbgnmlParserTestFiles/sbgnmlFiles/clone-marker.sbgn")); - + Reaction reaction = model.getReactionByReactionId("glyph9"); - + Reactant r1 = reaction.getReactants().get(0); Reactant r2 = reaction.getReactants().get(1); Product p1 = reaction.getProducts().get(0); Product p2 = reaction.getProducts().get(1); - + NodeOperator inputOperator = null; - NodeOperator outputOperator= null; - for (NodeOperator operator: reaction.getOperators()) { + NodeOperator outputOperator = null; + for (NodeOperator operator : reaction.getOperators()) { if (operator.isProductOperator()) { outputOperator = operator; } else { @@ -111,6 +95,6 @@ public class SbgnmlXmlParserTest2 { assertEquals(p1.getLine().getBeginPoint(), outputOperator.getLine().getBeginPoint()); assertEquals(p2.getLine().getBeginPoint(), outputOperator.getLine().getBeginPoint()); -} + } } diff --git a/converter-graphics/src/test/java/lcsb/mapviewer/converter/graphics/ConverterTest.java b/converter-graphics/src/test/java/lcsb/mapviewer/converter/graphics/ConverterTest.java index aafdac383635d2728c9bd1be62ec2814b605fefc..0bf8ed265dd59eeed0afc3cde20742e5efb1dafa 100644 --- a/converter-graphics/src/test/java/lcsb/mapviewer/converter/graphics/ConverterTest.java +++ b/converter-graphics/src/test/java/lcsb/mapviewer/converter/graphics/ConverterTest.java @@ -1,86 +1,73 @@ package lcsb.mapviewer.converter.graphics; -import java.awt.Color; -import java.awt.Desktop; -import java.awt.Graphics2D; +import java.awt.*; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; -import org.junit.After; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; +import org.junit.*; import lcsb.mapviewer.commands.ColorExtractor; import lcsb.mapviewer.converter.graphics.bioEntity.BioEntityConverterImpl; -import lcsb.mapviewer.model.map.compartment.BottomSquareCompartment; -import lcsb.mapviewer.model.map.compartment.LeftSquareCompartment; -import lcsb.mapviewer.model.map.compartment.RightSquareCompartment; -import lcsb.mapviewer.model.map.compartment.TopSquareCompartment; +import lcsb.mapviewer.model.map.compartment.*; -public class ConverterTest { +public class ConverterTest extends GraphicsTestFunctions { - @Before - public void setUp() throws Exception { - } + @Before + public void setUp() throws Exception { + } - @After - public void tearDown() throws Exception { - } + @After + public void tearDown() throws Exception { + } - @Test - public void test() { - try { - ColorExtractor colorExtractor = new ColorExtractor(Color.BLUE, Color.RED, Color.BLUE); - new BioEntityConverterImpl(new BottomSquareCompartment("id1"), colorExtractor); - new BioEntityConverterImpl(new TopSquareCompartment("id2"), colorExtractor); - new BioEntityConverterImpl(new LeftSquareCompartment("id3"), colorExtractor); - new BioEntityConverterImpl(new RightSquareCompartment("id4"), colorExtractor); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } + @Test + public void test() { + ColorExtractor colorExtractor = new ColorExtractor(Color.BLUE, Color.RED, Color.BLUE); + new BioEntityConverterImpl(new BottomSquareCompartment("id1"), colorExtractor); + new BioEntityConverterImpl(new TopSquareCompartment("id2"), colorExtractor); + new BioEntityConverterImpl(new LeftSquareCompartment("id3"), colorExtractor); + new BioEntityConverterImpl(new RightSquareCompartment("id4"), colorExtractor); + } - @Test - @Ignore("it's just code for generating scale") - public void testX() throws IOException { - BufferedImage tmpBI = new BufferedImage(900, 100, BufferedImage.TYPE_INT_ARGB); - Graphics2D tmpGraphics = tmpBI.createGraphics(); - int startX = 10; - int startY = 15; - int stepSize = 40; - int height = 25; - tmpGraphics.setColor(Color.BLACK); - for (int i = 0; i < 21; i++) { - tmpGraphics.drawLine(startX + i * stepSize, height+startY, startX + i * stepSize, height*2); - String str = ""+((double)(i-10))/((double)(10)); - tmpGraphics.drawString(str, startX + i * stepSize, height*2+startY); - } - for (int i = 0; i < 10 * stepSize; i++) { - double ratio = ((double) i) / ((double) (10 * stepSize)); - tmpGraphics.setBackground(getColor(ratio, Color.BLUE, Color.WHITE)); - tmpGraphics.setColor(getColor(ratio, Color.BLUE, Color.WHITE)); - tmpGraphics.drawRect(startX + i, startY , 1, height); - } - for (int i = 0; i < 10 * stepSize; i++) { - double ratio = ((double) i) / ((double) (10 * stepSize)); - tmpGraphics.setBackground(getColor(ratio, Color.WHITE, Color.RED)); - tmpGraphics.setColor(getColor(ratio, Color.WHITE, Color.RED)); - tmpGraphics.drawRect(10 * stepSize + startX + i, startY , 1, height); - } - ImageIO.write(tmpBI, "PNG", new File("tmp.png")); - Desktop.getDesktop().open(new File("tmp.png")); - } + @Test + @Ignore("it's just code for generating scale") + public void testX() throws IOException { + BufferedImage tmpBI = new BufferedImage(900, 100, BufferedImage.TYPE_INT_ARGB); + Graphics2D tmpGraphics = tmpBI.createGraphics(); + int startX = 10; + int startY = 15; + int stepSize = 40; + int height = 25; + tmpGraphics.setColor(Color.BLACK); + for (int i = 0; i < 21; i++) { + tmpGraphics.drawLine(startX + i * stepSize, height + startY, startX + i * stepSize, height * 2); + String str = "" + ((double) (i - 10)) / ((double) (10)); + tmpGraphics.drawString(str, startX + i * stepSize, height * 2 + startY); + } + for (int i = 0; i < 10 * stepSize; i++) { + double ratio = ((double) i) / ((double) (10 * stepSize)); + tmpGraphics.setBackground(getColor(ratio, Color.BLUE, Color.WHITE)); + tmpGraphics.setColor(getColor(ratio, Color.BLUE, Color.WHITE)); + tmpGraphics.drawRect(startX + i, startY, 1, height); + } + for (int i = 0; i < 10 * stepSize; i++) { + double ratio = ((double) i) / ((double) (10 * stepSize)); + tmpGraphics.setBackground(getColor(ratio, Color.WHITE, Color.RED)); + tmpGraphics.setColor(getColor(ratio, Color.WHITE, Color.RED)); + tmpGraphics.drawRect(10 * stepSize + startX + i, startY, 1, height); + } + ImageIO.write(tmpBI, "PNG", new File("tmp.png")); + Desktop.getDesktop().open(new File("tmp.png")); + } - private Color getColor(double d, Color startColor, Color endColor) { + private Color getColor(double d, Color startColor, Color endColor) { - return new Color((int) (startColor.getRed() + d * (endColor.getRed() - startColor.getRed())), - (int) (startColor.getGreen() + d * (endColor.getGreen() - startColor.getGreen())), - (int) (startColor.getBlue() + d * (endColor.getBlue() - startColor.getBlue()))); - } + return new Color((int) (startColor.getRed() + d * (endColor.getRed() - startColor.getRed())), + (int) (startColor.getGreen() + d * (endColor.getGreen() - startColor.getGreen())), + (int) (startColor.getBlue() + d * (endColor.getBlue() - startColor.getBlue()))); + } } diff --git a/converter-graphics/src/test/java/lcsb/mapviewer/converter/graphics/GraphicsTestFunctions.java b/converter-graphics/src/test/java/lcsb/mapviewer/converter/graphics/GraphicsTestFunctions.java index eecb56068e94ebf61ce928faa10fee2d4a388138..7631445290d21f56349e1b4bf64a1869151005fd 100644 --- a/converter-graphics/src/test/java/lcsb/mapviewer/converter/graphics/GraphicsTestFunctions.java +++ b/converter-graphics/src/test/java/lcsb/mapviewer/converter/graphics/GraphicsTestFunctions.java @@ -1,27 +1,27 @@ package lcsb.mapviewer.converter.graphics; -import static org.mockito.ArgumentMatchers.nullable; -import static org.mockito.Mockito.when; +import static org.mockito.ArgumentMatchers.*; +import static org.mockito.Mockito.*; -import java.awt.FontMetrics; -import java.awt.Graphics; -import java.awt.Graphics2D; +import java.awt.*; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; +import org.junit.Rule; import org.mockito.Mockito; +import lcsb.mapviewer.common.UnitTestFailedWatcher; import lcsb.mapviewer.model.graphics.PolylineData; import lcsb.mapviewer.model.map.modifier.Catalysis; -import lcsb.mapviewer.model.map.reaction.Modifier; -import lcsb.mapviewer.model.map.reaction.Product; -import lcsb.mapviewer.model.map.reaction.Reactant; -import lcsb.mapviewer.model.map.reaction.Reaction; +import lcsb.mapviewer.model.map.reaction.*; import lcsb.mapviewer.model.map.species.Complex; import lcsb.mapviewer.model.map.species.GenericProtein; public abstract class GraphicsTestFunctions { + @Rule + public UnitTestFailedWatcher unitTestFailedWatcher = new UnitTestFailedWatcher(); + int elementCounter = 1; protected Graphics2D createGraphicsMock() { @@ -69,7 +69,7 @@ public abstract class GraphicsTestFunctions { } protected Complex createComplex() { - Complex complex = new Complex("c"+elementCounter++); + Complex complex = new Complex("c" + elementCounter++); complex.setName("a"); complex.setX(300); complex.setY(90); diff --git a/converter-graphics/src/test/java/lcsb/mapviewer/converter/graphics/ImageGeneratorsTest.java b/converter-graphics/src/test/java/lcsb/mapviewer/converter/graphics/ImageGeneratorsTest.java index acfa32d3db9dc9136358b71d6adcb078d5cd9591..70ab35b83a9062de32e252fe7496814676a88487 100644 --- a/converter-graphics/src/test/java/lcsb/mapviewer/converter/graphics/ImageGeneratorsTest.java +++ b/converter-graphics/src/test/java/lcsb/mapviewer/converter/graphics/ImageGeneratorsTest.java @@ -1,45 +1,38 @@ package lcsb.mapviewer.converter.graphics; import static org.junit.Assert.*; + +import org.junit.*; + import lcsb.mapviewer.common.Pair; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -public class ImageGeneratorsTest { - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testAvailableGenerators() { - try { - ImageGenerators imageGenerators = new ImageGenerators(); - - boolean pngGenFound = false; - boolean pdfGenFound = false; - for (Pair<String, Class<? extends AbstractImageGenerator>> element : imageGenerators.getAvailableImageGenerators()) { - if (element.getRight().equals(PngImageGenerator.class)) { - pngGenFound = true; - } - if (element.getRight().equals(PdfImageGenerator.class)) { - pdfGenFound = true; - } - } - assertTrue(pngGenFound); - assertTrue(pdfGenFound); -// assertTrue(jpgGenFound); -// assertTrue(svgGenFound); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } +public class ImageGeneratorsTest extends GraphicsTestFunctions { + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testAvailableGenerators() { + ImageGenerators imageGenerators = new ImageGenerators(); + + boolean pngGenFound = false; + boolean pdfGenFound = false; + for (Pair<String, Class<? extends AbstractImageGenerator>> element : imageGenerators + .getAvailableImageGenerators()) { + if (element.getRight().equals(PngImageGenerator.class)) { + pngGenFound = true; + } + if (element.getRight().equals(PdfImageGenerator.class)) { + pdfGenFound = true; + } + } + assertTrue(pngGenFound); + assertTrue(pdfGenFound); + } } diff --git a/converter-graphics/src/test/java/lcsb/mapviewer/converter/graphics/MapGeneratorTest.java b/converter-graphics/src/test/java/lcsb/mapviewer/converter/graphics/MapGeneratorTest.java index 7f888089f6516a48f0153201c811c9c8c8939cd1..691dce81bf9c432a55c0a342f3c752ec2fb281de 100644 --- a/converter-graphics/src/test/java/lcsb/mapviewer/converter/graphics/MapGeneratorTest.java +++ b/converter-graphics/src/test/java/lcsb/mapviewer/converter/graphics/MapGeneratorTest.java @@ -1,11 +1,14 @@ package lcsb.mapviewer.converter.graphics; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import java.io.File; +import org.apache.commons.io.FileUtils; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.junit.*; + import lcsb.mapviewer.converter.graphics.MapGenerator.MapGeneratorParams; import lcsb.mapviewer.model.Project; import lcsb.mapviewer.model.map.layout.DataOverlayImageLayer; @@ -13,80 +16,64 @@ import lcsb.mapviewer.model.map.layout.Layout; import lcsb.mapviewer.model.map.model.Model; import lcsb.mapviewer.model.map.model.ModelFullIndexed; -import org.apache.commons.io.FileUtils; -import org.apache.logging.log4j.*; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -public class MapGeneratorTest { - Logger logger = LogManager.getLogger(MapGeneratorTest.class); - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testGenerateMapImagesModelStringBoolean() { - try { - String dir = "test_images"; - File f = new File(dir); - if (f.exists()) { - FileUtils.deleteDirectory(f); - } - - Model model = createModel(); - MapGenerator generator = new MapGenerator(); - MapGeneratorParams params = generator.new MapGeneratorParams().model(model).directory(dir); - generator.generateMapImages(params); - - File f1 = new File(dir + "/2/0/0.PNG"); - assertTrue(f1.exists()); - File f2 = new File(dir + "/4/1/1.PNG"); - assertTrue(f2.exists()); - - f = new File(dir); - FileUtils.deleteDirectory(f); - } catch (Exception e) { - e.printStackTrace(); - fail("Exception occurred"); - } - } - - private Model createModel() { - Model model = new ModelFullIndexed(null); - model.setWidth(1305.7682370820667); - model.setHeight(473.0); - return model; - } - - @Test - public void testRemoveLayout() throws Exception { - try { - String dir = "test_images"; - File f = new File(dir); - - Model model = createModel(); - Project project = new Project(); - project.addModel(model); - Layout layout =new Layout("a", true); - layout.addDataOverlayImageLayer(new DataOverlayImageLayer(model, dir)); - project.addLayout(layout); - - MapGenerator generator = new MapGenerator(); - MapGeneratorParams params = generator.new MapGeneratorParams().model(model).directory(dir); - generator.generateMapImages(params); - assertTrue(f.exists()); - generator.removeLayout(project.getLayouts().get(0)); - - assertFalse(f.exists()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } +public class MapGeneratorTest extends GraphicsTestFunctions { + Logger logger = LogManager.getLogger(MapGeneratorTest.class); + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testGenerateMapImagesModelStringBoolean() throws Exception { + String dir = "test_images"; + File f = new File(dir); + if (f.exists()) { + FileUtils.deleteDirectory(f); + } + + Model model = createModel(); + MapGenerator generator = new MapGenerator(); + MapGeneratorParams params = generator.new MapGeneratorParams().model(model).directory(dir); + generator.generateMapImages(params); + + File f1 = new File(dir + "/2/0/0.PNG"); + assertTrue(f1.exists()); + File f2 = new File(dir + "/4/1/1.PNG"); + assertTrue(f2.exists()); + + f = new File(dir); + FileUtils.deleteDirectory(f); + } + + private Model createModel() { + Model model = new ModelFullIndexed(null); + model.setWidth(1305.7682370820667); + model.setHeight(473.0); + return model; + } + + @Test + public void testRemoveLayout() throws Exception { + String dir = "test_images"; + File f = new File(dir); + + Model model = createModel(); + Project project = new Project(); + project.addModel(model); + Layout layout = new Layout("a", true); + layout.addDataOverlayImageLayer(new DataOverlayImageLayer(model, dir)); + project.addLayout(layout); + + MapGenerator generator = new MapGenerator(); + MapGeneratorParams params = generator.new MapGeneratorParams().model(model).directory(dir); + generator.generateMapImages(params); + assertTrue(f.exists()); + generator.removeLayout(project.getLayouts().get(0)); + + assertFalse(f.exists()); + } } diff --git a/converter-graphics/src/test/java/lcsb/mapviewer/converter/graphics/NormalImageGeneratorTest.java b/converter-graphics/src/test/java/lcsb/mapviewer/converter/graphics/NormalImageGeneratorTest.java index 3dd15c0c5509d3ef122d6802ee53a207ef8c4234..00307235fce0ec9b47ab152d3b5390dd5b7ce2b8 100644 --- a/converter-graphics/src/test/java/lcsb/mapviewer/converter/graphics/NormalImageGeneratorTest.java +++ b/converter-graphics/src/test/java/lcsb/mapviewer/converter/graphics/NormalImageGeneratorTest.java @@ -4,10 +4,9 @@ import java.awt.Color; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; -import org.apache.logging.log4j.*; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.junit.*; import lcsb.mapviewer.commands.CreateHierarchyCommand; import lcsb.mapviewer.converter.graphics.AbstractImageGenerator.Params; @@ -18,68 +17,61 @@ import lcsb.mapviewer.model.map.model.Model; import lcsb.mapviewer.model.map.model.ModelFullIndexed; import lcsb.mapviewer.model.map.species.Complex; -public class NormalImageGeneratorTest { - static Logger logger = LogManager.getLogger(NormalImageGenerator.class); - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - private Model createCompartmentModel() { - Model model = new ModelFullIndexed(null); - model.setWidth(526); - model.setHeight(346); - - LayerText compAlias = new LayerText(); - compAlias.setX(256.0); - compAlias.setY(79.0); - compAlias.setWidth(233.0); - compAlias.setHeight(188.0); - compAlias.setNotes("asd as"); - compAlias.setColor(Color.BLACK); - Layer layer = new Layer(); - layer.addLayerText(compAlias); - layer.setVisible(true); - model.addLayer(layer); - - layer.addLayerLine(new PolylineData(new Point2D.Double(0, 0), new Point2D.Double(100, 100))); - - Complex alias = new Complex("1"); - alias.setName("a"); - alias.setX(300); - alias.setY(90); - alias.setWidth(100); - alias.setHeight(50); - model.addElement(alias); - - return model; - } - - - @Test - public void testArtifitialInHierarchicalView() throws Exception { - try { - Model model = createCompartmentModel(); - Layer layer = model.getLayers().iterator().next(); - - layer.addLayerText(new LayerText(new Rectangle2D.Double(10, 10, 500, 500), "X asd")); - layer.addLayerText(new LayerText(new Rectangle2D.Double(20, 20, 200, 200), "Y qwe ret")); - layer.addLayerText(new LayerText(new Rectangle2D.Double(100, 100, 199, 220), "Z dgf fsd aaewq ret")); - - new CreateHierarchyCommand(model, 1, 8).execute(); - model.getCompartments().get(1).setTransparencyLevel("2"); - model.getCompartments().get(0).setTransparencyLevel("2"); - model.getCompartments().get(3).setTransparencyLevel("2"); - new PngImageGenerator(new Params().level(2).scale(4).width(600).height(600).model(model).nested(true)); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } +public class NormalImageGeneratorTest extends GraphicsTestFunctions { + static Logger logger = LogManager.getLogger(NormalImageGenerator.class); + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + private Model createCompartmentModel() { + Model model = new ModelFullIndexed(null); + model.setWidth(526); + model.setHeight(346); + + LayerText compAlias = new LayerText(); + compAlias.setX(256.0); + compAlias.setY(79.0); + compAlias.setWidth(233.0); + compAlias.setHeight(188.0); + compAlias.setNotes("asd as"); + compAlias.setColor(Color.BLACK); + Layer layer = new Layer(); + layer.addLayerText(compAlias); + layer.setVisible(true); + model.addLayer(layer); + + layer.addLayerLine(new PolylineData(new Point2D.Double(0, 0), new Point2D.Double(100, 100))); + + Complex alias = new Complex("1"); + alias.setName("a"); + alias.setX(300); + alias.setY(90); + alias.setWidth(100); + alias.setHeight(50); + model.addElement(alias); + + return model; + } + + @Test + public void testArtifitialInHierarchicalView() throws Exception { + Model model = createCompartmentModel(); + Layer layer = model.getLayers().iterator().next(); + + layer.addLayerText(new LayerText(new Rectangle2D.Double(10, 10, 500, 500), "X asd")); + layer.addLayerText(new LayerText(new Rectangle2D.Double(20, 20, 200, 200), "Y qwe ret")); + layer.addLayerText(new LayerText(new Rectangle2D.Double(100, 100, 199, 220), "Z dgf fsd aaewq ret")); + + new CreateHierarchyCommand(model, 1, 8).execute(); + model.getCompartments().get(1).setTransparencyLevel("2"); + model.getCompartments().get(0).setTransparencyLevel("2"); + model.getCompartments().get(3).setTransparencyLevel("2"); + new PngImageGenerator(new Params().level(2).scale(4).width(600).height(600).model(model).nested(true)); + } } diff --git a/converter-graphics/src/test/java/lcsb/mapviewer/converter/graphics/PdfImageGeneratorTest.java b/converter-graphics/src/test/java/lcsb/mapviewer/converter/graphics/PdfImageGeneratorTest.java index ebee061191155f19eb1f417b3be8b17ab24c4026..5d1a0f1d0bf3093dde6b75d63b877e8fc230f465 100644 --- a/converter-graphics/src/test/java/lcsb/mapviewer/converter/graphics/PdfImageGeneratorTest.java +++ b/converter-graphics/src/test/java/lcsb/mapviewer/converter/graphics/PdfImageGeneratorTest.java @@ -1,10 +1,8 @@ package lcsb.mapviewer.converter.graphics; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; +import static org.junit.Assert.*; +import static org.mockito.ArgumentMatchers.*; +import static org.mockito.Mockito.*; import java.awt.Color; import java.awt.Graphics2D; @@ -12,9 +10,7 @@ import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.io.File; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.mockito.Mockito; import lcsb.mapviewer.commands.CreateHierarchyCommand; @@ -39,44 +35,38 @@ public class PdfImageGeneratorTest extends GraphicsTestFunctions { @Test public void testSaveToFile() throws Exception { - try { - String filename = "tmp.pdf"; + String filename = "tmp.pdf"; - File f = new File(filename); - if (f.exists()) { - f.delete(); - } + File f = new File(filename); + if (f.exists()) { + f.delete(); + } - assertFalse(f.exists()); + assertFalse(f.exists()); - Model model = createCompartmentModel(); - Layer layer = model.getLayers().iterator().next(); + Model model = createCompartmentModel(); + Layer layer = model.getLayers().iterator().next(); - layer.addLayerText(new LayerText(new Rectangle2D.Double(10, 10, 500, 500), "X asd")); - layer.addLayerText(new LayerText(new Rectangle2D.Double(20, 20, 200, 200), "Y qwe ret")); - layer.addLayerText(new LayerText(new Rectangle2D.Double(100, 100, 199, 220), "Z dgf fsd aaewq ret")); - - for (LayerText text: layer.getTexts()) { - text.setZ(0); - } + layer.addLayerText(new LayerText(new Rectangle2D.Double(10, 10, 500, 500), "X asd")); + layer.addLayerText(new LayerText(new Rectangle2D.Double(20, 20, 200, 200), "Y qwe ret")); + layer.addLayerText(new LayerText(new Rectangle2D.Double(100, 100, 199, 220), "Z dgf fsd aaewq ret")); - new CreateHierarchyCommand(model, 1, 8).execute(); - model.getCompartments().get(1).setTransparencyLevel("2"); - model.getCompartments().get(0).setTransparencyLevel("2"); - model.getCompartments().get(3).setTransparencyLevel("2"); + for (LayerText text : layer.getTexts()) { + text.setZ(0); + } - PdfImageGenerator pig = createAbstractImageGeneratorMock(model, null); + new CreateHierarchyCommand(model, 1, 8).execute(); + model.getCompartments().get(1).setTransparencyLevel("2"); + model.getCompartments().get(0).setTransparencyLevel("2"); + model.getCompartments().get(3).setTransparencyLevel("2"); - pig.saveToFile("tmp.pdf"); + PdfImageGenerator pig = createAbstractImageGeneratorMock(model, null); - assertTrue(f.exists()); - f.delete(); - assertFalse(f.exists()); + pig.saveToFile("tmp.pdf"); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertTrue(f.exists()); + f.delete(); + assertFalse(f.exists()); } private PdfImageGenerator createAbstractImageGeneratorMock(Model model, Graphics2D graphics) throws DrawingException { @@ -113,28 +103,22 @@ public class PdfImageGeneratorTest extends GraphicsTestFunctions { return model; } - @Test public void testDrawPathwayWithoutNesting() throws Exception { - try { - Graphics2D graphics = createGraphicsMock(); - - Model model = createCompartmentModel(); - - PathwayCompartment pathway = new PathwayCompartment("id"); - pathway.setWidth(100); - pathway.setHeight(100); - model.addElement(pathway); - AbstractImageGenerator gen = createAbstractImageGeneratorMock(model, graphics); - gen.getParams().nested(false); - gen.drawCompartment(pathway); - - // 3 times for proteins and 4 times for reaction - verify(graphics, times(1)).draw(any()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Graphics2D graphics = createGraphicsMock(); + + Model model = createCompartmentModel(); + + PathwayCompartment pathway = new PathwayCompartment("id"); + pathway.setWidth(100); + pathway.setHeight(100); + model.addElement(pathway); + AbstractImageGenerator gen = createAbstractImageGeneratorMock(model, graphics); + gen.getParams().nested(false); + gen.drawCompartment(pathway); + + // 3 times for proteins and 4 times for reaction + verify(graphics, times(1)).draw(any()); } } diff --git a/converter-graphics/src/test/java/lcsb/mapviewer/converter/graphics/SvgImageGeneratorTest.java b/converter-graphics/src/test/java/lcsb/mapviewer/converter/graphics/SvgImageGeneratorTest.java index ffd2eec03dba74dee023562c8cff26b94e0d0800..1557f4b8728cd9c065d146cf086ec73b5b603357 100644 --- a/converter-graphics/src/test/java/lcsb/mapviewer/converter/graphics/SvgImageGeneratorTest.java +++ b/converter-graphics/src/test/java/lcsb/mapviewer/converter/graphics/SvgImageGeneratorTest.java @@ -24,7 +24,6 @@ public class SvgImageGeneratorTest extends GraphicsTestFunctions { @Test public void testSaveToFile() throws Exception { - try { Model model = createCompartmentModel(); SvgImageGenerator sig = new SvgImageGenerator(new AbstractImageGenerator.Params().model(model)); @@ -33,11 +32,6 @@ public class SvgImageGeneratorTest extends GraphicsTestFunctions { sig.saveToOutputStream(output); assertTrue(output.toString().contains("viewBox")); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } } private Model createCompartmentModel() { diff --git a/converter-graphics/src/test/java/lcsb/mapviewer/converter/graphics/bioEntity/element/compartment/PathwayCompartmentConverterTest.java b/converter-graphics/src/test/java/lcsb/mapviewer/converter/graphics/bioEntity/element/compartment/PathwayCompartmentConverterTest.java index 68eb75a367701b57be83d0596c100b89475fe52d..7b04cd3b36e306827c18d3b5f4f48fe6961a6775 100644 --- a/converter-graphics/src/test/java/lcsb/mapviewer/converter/graphics/bioEntity/element/compartment/PathwayCompartmentConverterTest.java +++ b/converter-graphics/src/test/java/lcsb/mapviewer/converter/graphics/bioEntity/element/compartment/PathwayCompartmentConverterTest.java @@ -1,6 +1,6 @@ package lcsb.mapviewer.converter.graphics.bioEntity.element.compartment; -import static org.junit.Assert.assertEquals; +import static org.junit.Assert.*; import java.awt.Color; import java.awt.Graphics2D; @@ -13,11 +13,12 @@ import org.mockito.Mockito; import lcsb.mapviewer.commands.ColorExtractor; import lcsb.mapviewer.common.geometry.ColorParser; import lcsb.mapviewer.converter.graphics.ConverterParams; +import lcsb.mapviewer.converter.graphics.GraphicsTestFunctions; import lcsb.mapviewer.model.map.compartment.PathwayCompartment; import lcsb.mapviewer.model.map.model.Model; import lcsb.mapviewer.model.map.model.ModelFullIndexed; -public class PathwayCompartmentConverterTest { +public class PathwayCompartmentConverterTest extends GraphicsTestFunctions { ColorExtractor colorExtractor = new ColorExtractor(Color.RED, Color.GREEN, Color.BLUE); PathwayCompartmentConverter converter = new PathwayCompartmentConverter(colorExtractor); @@ -25,60 +26,50 @@ public class PathwayCompartmentConverterTest { @Test public void testDrawSolid() throws Exception { int size = 600; - try { - Model model = new ModelFullIndexed(null); - - BufferedImage bi = new BufferedImage(size, size, BufferedImage.TYPE_INT_ARGB); - Graphics2D graphics = Mockito.spy(bi.createGraphics()); - - PathwayCompartment pathway = new PathwayCompartment("id"); - pathway.setX(10); - pathway.setY(10); - pathway.setWidth(100); - pathway.setHeight(200); - pathway.setColor(Color.BLUE); - pathway.setTransparencyLevel("12"); - model.addElement(pathway); - - converter.draw(pathway, graphics, new ConverterParams().nested(true)); - - Mockito.verify(graphics).setColor(Color.BLUE); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Model model = new ModelFullIndexed(null); + + BufferedImage bi = new BufferedImage(size, size, BufferedImage.TYPE_INT_ARGB); + Graphics2D graphics = Mockito.spy(bi.createGraphics()); + + PathwayCompartment pathway = new PathwayCompartment("id"); + pathway.setX(10); + pathway.setY(10); + pathway.setWidth(100); + pathway.setHeight(200); + pathway.setColor(Color.BLUE); + pathway.setTransparencyLevel("12"); + model.addElement(pathway); + + converter.draw(pathway, graphics, new ConverterParams().nested(true)); + + Mockito.verify(graphics).setColor(Color.BLUE); } @Test public void testDrawTransparent() throws Exception { int size = 600; - try { - Model model = new ModelFullIndexed(null); - - BufferedImage bi = new BufferedImage(size, size, BufferedImage.TYPE_INT_ARGB); - Graphics2D graphics = Mockito.spy(bi.createGraphics()); - - PathwayCompartment pathway = new PathwayCompartment("id"); - pathway.setX(10); - pathway.setY(10); - pathway.setWidth(100); - pathway.setHeight(200); - pathway.setColor(Color.BLUE); - model.addElement(pathway); - - converter.draw(pathway, graphics, new ConverterParams().nested(true)); - - ArgumentCaptor<Color> argument = ArgumentCaptor.forClass(Color.class); - Mockito.verify(graphics, Mockito.atLeastOnce()).setColor(argument.capture()); - - //alpha will be different - String blueHtml = new ColorParser().colorToHtml(Color.BLUE); - String usedColorHtml = new ColorParser().colorToHtml(argument.getAllValues().get(0)); - assertEquals(blueHtml, usedColorHtml); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Model model = new ModelFullIndexed(null); + + BufferedImage bi = new BufferedImage(size, size, BufferedImage.TYPE_INT_ARGB); + Graphics2D graphics = Mockito.spy(bi.createGraphics()); + + PathwayCompartment pathway = new PathwayCompartment("id"); + pathway.setX(10); + pathway.setY(10); + pathway.setWidth(100); + pathway.setHeight(200); + pathway.setColor(Color.BLUE); + model.addElement(pathway); + + converter.draw(pathway, graphics, new ConverterParams().nested(true)); + + ArgumentCaptor<Color> argument = ArgumentCaptor.forClass(Color.class); + Mockito.verify(graphics, Mockito.atLeastOnce()).setColor(argument.capture()); + + // alpha will be different + String blueHtml = new ColorParser().colorToHtml(Color.BLUE); + String usedColorHtml = new ColorParser().colorToHtml(argument.getAllValues().get(0)); + assertEquals(blueHtml, usedColorHtml); } } diff --git a/converter-graphics/src/test/java/lcsb/mapviewer/converter/graphics/bioEntity/element/species/ComplexConverterTest.java b/converter-graphics/src/test/java/lcsb/mapviewer/converter/graphics/bioEntity/element/species/ComplexConverterTest.java index cf8a3e54b7e5e12e523ca41228007d1d04ef5bb2..1e97a005a4827eb7b5d08606b7a1364c70211fca 100644 --- a/converter-graphics/src/test/java/lcsb/mapviewer/converter/graphics/bioEntity/element/species/ComplexConverterTest.java +++ b/converter-graphics/src/test/java/lcsb/mapviewer/converter/graphics/bioEntity/element/species/ComplexConverterTest.java @@ -1,22 +1,21 @@ package lcsb.mapviewer.converter.graphics.bioEntity.element.species; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; +import static org.junit.Assert.*; import java.awt.Color; import java.awt.Graphics2D; import java.awt.image.BufferedImage; -import org.apache.logging.log4j.*; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.junit.*; import lcsb.mapviewer.commands.ColorExtractor; import lcsb.mapviewer.converter.graphics.ConverterParams; +import lcsb.mapviewer.converter.graphics.GraphicsTestFunctions; import lcsb.mapviewer.model.map.species.Complex; -public class ComplexConverterTest { +public class ComplexConverterTest extends GraphicsTestFunctions { Logger logger = LogManager.getLogger(ComplexConverterTest.class); ColorExtractor colorExtractor = new ColorExtractor(Color.RED, Color.GREEN, Color.BLUE); @@ -31,54 +30,43 @@ public class ComplexConverterTest { @Test public void testDrawText() throws Exception { - try { - int size = 200; - BufferedImage bi = new BufferedImage(size, size, BufferedImage.TYPE_INT_ARGB); - Graphics2D graphics = bi.createGraphics(); - ComplexConverter rc = new ComplexConverter(colorExtractor); - - Complex alias = createComplex(); - rc.drawText(alias, graphics, new ConverterParams()); - - boolean onlyWhite = true; - for (int x = 0; x < size; x++) { - for (int y = 0; y < size; y++) { - if (bi.getRGB(x, y) != 0) { - onlyWhite = false; - } + int size = 200; + BufferedImage bi = new BufferedImage(size, size, BufferedImage.TYPE_INT_ARGB); + Graphics2D graphics = bi.createGraphics(); + ComplexConverter rc = new ComplexConverter(colorExtractor); + + Complex alias = createComplex(); + rc.drawText(alias, graphics, new ConverterParams()); + + boolean onlyWhite = true; + for (int x = 0; x < size; x++) { + for (int y = 0; y < size; y++) { + if (bi.getRGB(x, y) != 0) { + onlyWhite = false; } } - assertFalse(onlyWhite); - - } catch (Exception e) { - e.printStackTrace(); - throw e; } + assertFalse(onlyWhite); } @Test public void testDrawTooBigText() throws Exception { - try { - int size = 200; - double scale = 100; - BufferedImage bi = new BufferedImage(size, size, BufferedImage.TYPE_INT_ARGB); - Graphics2D graphics = bi.createGraphics(); - Color color = graphics.getColor(); - graphics.scale(1.0 / scale, 1.0 / scale); - ComplexConverter rc = new ComplexConverter(colorExtractor); - - Complex alias = createComplex(); - rc.drawText(alias, graphics, new ConverterParams()); - - assertEquals(color, graphics.getColor()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + int size = 200; + double scale = 100; + BufferedImage bi = new BufferedImage(size, size, BufferedImage.TYPE_INT_ARGB); + Graphics2D graphics = bi.createGraphics(); + Color color = graphics.getColor(); + graphics.scale(1.0 / scale, 1.0 / scale); + ComplexConverter rc = new ComplexConverter(colorExtractor); + + Complex alias = createComplex(); + rc.drawText(alias, graphics, new ConverterParams()); + + assertEquals(color, graphics.getColor()); } - private Complex createComplex() { + @Override + protected Complex createComplex() { Complex protein = new Complex("id"); protein.setName("NAME_OF_THE_ELEMENT"); protein.setX(10); diff --git a/converter-graphics/src/test/java/lcsb/mapviewer/converter/graphics/bioEntity/element/species/SpeciesConverterTest.java b/converter-graphics/src/test/java/lcsb/mapviewer/converter/graphics/bioEntity/element/species/SpeciesConverterTest.java index 7893741dbbfd3933e6955389b38ba5333f7508be..f8cc62d4491b614e3139a29636e36d791e95c056 100644 --- a/converter-graphics/src/test/java/lcsb/mapviewer/converter/graphics/bioEntity/element/species/SpeciesConverterTest.java +++ b/converter-graphics/src/test/java/lcsb/mapviewer/converter/graphics/bioEntity/element/species/SpeciesConverterTest.java @@ -1,19 +1,10 @@ package lcsb.mapviewer.converter.graphics.bioEntity.element.species; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyBoolean; -import static org.mockito.ArgumentMatchers.anyInt; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.ArgumentMatchers.argThat; -import static org.mockito.ArgumentMatchers.nullable; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; - -import java.awt.Color; -import java.awt.Graphics2D; -import java.awt.Image; +import static org.junit.Assert.*; +import static org.mockito.ArgumentMatchers.*; +import static org.mockito.Mockito.*; + +import java.awt.*; import java.awt.geom.Point2D; import java.awt.image.BufferedImage; import java.awt.image.ImageObserver; @@ -24,9 +15,7 @@ import java.util.List; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.mockito.Mockito; import lcsb.mapviewer.commands.ColorExtractor; @@ -39,14 +28,7 @@ import lcsb.mapviewer.model.map.layout.GenericColorSchema; import lcsb.mapviewer.model.map.layout.graphics.Glyph; import lcsb.mapviewer.model.map.species.GenericProtein; import lcsb.mapviewer.model.map.species.Protein; -import lcsb.mapviewer.model.map.species.field.BindingRegion; -import lcsb.mapviewer.model.map.species.field.CodingRegion; -import lcsb.mapviewer.model.map.species.field.ModificationResidue; -import lcsb.mapviewer.model.map.species.field.ModificationSite; -import lcsb.mapviewer.model.map.species.field.ProteinBindingDomain; -import lcsb.mapviewer.model.map.species.field.RegulatoryRegion; -import lcsb.mapviewer.model.map.species.field.Residue; -import lcsb.mapviewer.model.map.species.field.TranscriptionSite; +import lcsb.mapviewer.model.map.species.field.*; public class SpeciesConverterTest extends GraphicsTestFunctions { Logger logger = LogManager.getLogger(SpeciesConverterTest.class); @@ -63,345 +45,271 @@ public class SpeciesConverterTest extends GraphicsTestFunctions { @Test public void testDrawAliasWithLayouts() throws Exception { - try { - BufferedImage bi = new BufferedImage(200, 200, BufferedImage.TYPE_INT_ARGB); - Graphics2D graphics = bi.createGraphics(); - ProteinConverter rc = new ProteinConverter(colorExtractor); - - GenericProtein alias = createProtein(); - rc.draw(alias, graphics, new ConverterParams()); + BufferedImage bi = new BufferedImage(200, 200, BufferedImage.TYPE_INT_ARGB); + Graphics2D graphics = bi.createGraphics(); + ProteinConverter rc = new ProteinConverter(colorExtractor); - int val = bi.getRGB((int) alias.getCenterX(), (int) alias.getCenterY()); + GenericProtein alias = createProtein(); + rc.draw(alias, graphics, new ConverterParams()); - GenericProtein alias2 = createProtein(); + int val = bi.getRGB((int) alias.getCenterX(), (int) alias.getCenterY()); - bi = new BufferedImage(200, 200, BufferedImage.TYPE_INT_ARGB); - graphics = bi.createGraphics(); + GenericProtein alias2 = createProtein(); - ColorSchema schema = new GenericColorSchema(); - schema.setColor(Color.RED); - List<ColorSchema> schemas = new ArrayList<>(); - schemas.add(schema); + bi = new BufferedImage(200, 200, BufferedImage.TYPE_INT_ARGB); + graphics = bi.createGraphics(); - rc.draw(alias2, graphics, new ConverterParams(), schemas); + ColorSchema schema = new GenericColorSchema(); + schema.setColor(Color.RED); + List<ColorSchema> schemas = new ArrayList<>(); + schemas.add(schema); - int val2 = bi.getRGB((int) alias.getCenterX(), (int) alias.getCenterY()); + rc.draw(alias2, graphics, new ConverterParams(), schemas); - assertTrue(val != val2); + int val2 = bi.getRGB((int) alias.getCenterX(), (int) alias.getCenterY()); - } catch (Exception e) { - throw e; - } + assertTrue(val != val2); } @Test public void testDrawAfterDrawingReactionWithLayouts() throws Exception { - try { - BufferedImage bi = new BufferedImage(200, 200, BufferedImage.TYPE_INT_ARGB); - Graphics2D graphics = bi.createGraphics(); - ProteinConverter rc = new ProteinConverter(colorExtractor); - - GenericProtein alias = createProtein(); - rc.draw(alias, graphics, new ConverterParams()); + BufferedImage bi = new BufferedImage(200, 200, BufferedImage.TYPE_INT_ARGB); + Graphics2D graphics = bi.createGraphics(); + ProteinConverter rc = new ProteinConverter(colorExtractor); - int val = bi.getRGB((int) alias.getCenterX(), (int) alias.getCenterY()); + GenericProtein alias = createProtein(); + rc.draw(alias, graphics, new ConverterParams()); - GenericProtein alias2 = createProtein(); + int val = bi.getRGB((int) alias.getCenterX(), (int) alias.getCenterY()); - bi = new BufferedImage(200, 200, BufferedImage.TYPE_INT_ARGB); - graphics = bi.createGraphics(); + GenericProtein alias2 = createProtein(); - ColorSchema schema = new GenericColorSchema(); - schema.setColor(Color.RED); - List<ColorSchema> schemas = new ArrayList<>(); - schemas.add(schema); + bi = new BufferedImage(200, 200, BufferedImage.TYPE_INT_ARGB); + graphics = bi.createGraphics(); - rc.draw(alias2, graphics, new ConverterParams(), schemas); + ColorSchema schema = new GenericColorSchema(); + schema.setColor(Color.RED); + List<ColorSchema> schemas = new ArrayList<>(); + schemas.add(schema); - int val2 = bi.getRGB((int) alias.getCenterX(), (int) alias.getCenterY()); + rc.draw(alias2, graphics, new ConverterParams(), schemas); - bi = new BufferedImage(200, 200, BufferedImage.TYPE_INT_ARGB); - graphics = bi.createGraphics(); + int val2 = bi.getRGB((int) alias.getCenterX(), (int) alias.getCenterY()); - rc.draw(alias2, graphics, new ConverterParams(), new ArrayList<>()); + bi = new BufferedImage(200, 200, BufferedImage.TYPE_INT_ARGB); + graphics = bi.createGraphics(); - int val3 = bi.getRGB((int) alias.getCenterX(), (int) alias.getCenterY()); + rc.draw(alias2, graphics, new ConverterParams(), new ArrayList<>()); - assertTrue(val != val2); - assertEquals(val, val3); + int val3 = bi.getRGB((int) alias.getCenterX(), (int) alias.getCenterY()); - } catch (Exception e) { - throw e; - } + assertTrue(val != val2); + assertEquals(val, val3); } @Test public void testDrawReactionWithFewLayouts() throws Exception { - try { - BufferedImage bi = new BufferedImage(200, 200, BufferedImage.TYPE_INT_ARGB); - Graphics2D graphics = bi.createGraphics(); - ProteinConverter rc = new ProteinConverter(colorExtractor); + BufferedImage bi = new BufferedImage(200, 200, BufferedImage.TYPE_INT_ARGB); + Graphics2D graphics = bi.createGraphics(); + ProteinConverter rc = new ProteinConverter(colorExtractor); - GenericProtein alias = createProtein(); - rc.draw(alias, graphics, new ConverterParams()); + GenericProtein alias = createProtein(); + rc.draw(alias, graphics, new ConverterParams()); - int val = bi.getRGB((int) alias.getCenterX(), (int) alias.getCenterY()); + int val = bi.getRGB((int) alias.getCenterX(), (int) alias.getCenterY()); - GenericProtein alias2 = createProtein(); + GenericProtein alias2 = createProtein(); - bi = new BufferedImage(200, 200, BufferedImage.TYPE_INT_ARGB); - graphics = bi.createGraphics(); + bi = new BufferedImage(200, 200, BufferedImage.TYPE_INT_ARGB); + graphics = bi.createGraphics(); - ColorSchema schema = new GenericColorSchema(); - schema.setColor(Color.RED); - List<ColorSchema> schemas = new ArrayList<>(); - schemas.add(schema); - schemas.add(null); - schema = new GenericColorSchema(); - schema.setColor(Color.BLUE); - schemas.add(schema); + ColorSchema schema = new GenericColorSchema(); + schema.setColor(Color.RED); + List<ColorSchema> schemas = new ArrayList<>(); + schemas.add(schema); + schemas.add(null); + schema = new GenericColorSchema(); + schema.setColor(Color.BLUE); + schemas.add(schema); - rc.draw(alias2, graphics, new ConverterParams(), schemas); + rc.draw(alias2, graphics, new ConverterParams(), schemas); - int val2 = bi.getRGB((int) (alias.getX() + alias.getWidth() / 4), (int) alias.getCenterY()); - int val3 = bi.getRGB((int) (alias.getCenterX()), (int) alias.getCenterY()); - int val4 = bi.getRGB((int) (alias.getX() + 3 * alias.getWidth() / 4), (int) alias.getCenterY()); + int val2 = bi.getRGB((int) (alias.getX() + alias.getWidth() / 4), (int) alias.getCenterY()); + int val3 = bi.getRGB((int) (alias.getCenterX()), (int) alias.getCenterY()); + int val4 = bi.getRGB((int) (alias.getX() + 3 * alias.getWidth() / 4), (int) alias.getCenterY()); - assertTrue(val != val2); - assertEquals(val, val3); - assertTrue(val != val4); - - } catch (Exception e) { - throw e; - } + assertTrue(val != val2); + assertEquals(val, val3); + assertTrue(val != val4); } @Test public void testDrawResidue() throws Exception { - try { - BufferedImage bi = new BufferedImage(200, 200, BufferedImage.TYPE_INT_ARGB); - Graphics2D graphics = bi.createGraphics(); - - ModificationResidue residue = new Residue(); - residue.setPosition(new Point2D.Double(10, 10)); + BufferedImage bi = new BufferedImage(200, 200, BufferedImage.TYPE_INT_ARGB); + Graphics2D graphics = bi.createGraphics(); - ProteinConverter converter = Mockito.spy(new ProteinConverter(colorExtractor)); - converter.drawModification(residue, graphics, false); - verify(converter, times(1)).drawResidue(any(), any(), anyBoolean()); + ModificationResidue residue = new Residue(); + residue.setPosition(new Point2D.Double(10, 10)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + ProteinConverter converter = Mockito.spy(new ProteinConverter(colorExtractor)); + converter.drawModification(residue, graphics, false); + verify(converter, times(1)).drawResidue(any(), any(), anyBoolean()); } @Test public void testDrawBindingRegion() throws Exception { - try { - BufferedImage bi = new BufferedImage(200, 200, BufferedImage.TYPE_INT_ARGB); - Graphics2D graphics = bi.createGraphics(); - - Protein protein = createProtein(); - BindingRegion bindingRegion = new BindingRegion(); - bindingRegion.setPosition(new Point2D.Double(10, 10)); - bindingRegion.setWidth(100.0); - bindingRegion.setHeight(10.0); - protein.addBindingRegion(bindingRegion); - - ProteinConverter converter = Mockito.spy(new ProteinConverter(colorExtractor)); - converter.drawModification(bindingRegion, graphics, false); - verify(converter, times(1)).drawBindingRegion(any(), any()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + BufferedImage bi = new BufferedImage(200, 200, BufferedImage.TYPE_INT_ARGB); + Graphics2D graphics = bi.createGraphics(); + + Protein protein = createProtein(); + BindingRegion bindingRegion = new BindingRegion(); + bindingRegion.setPosition(new Point2D.Double(10, 10)); + bindingRegion.setWidth(100.0); + bindingRegion.setHeight(10.0); + protein.addBindingRegion(bindingRegion); + + ProteinConverter converter = Mockito.spy(new ProteinConverter(colorExtractor)); + converter.drawModification(bindingRegion, graphics, false); + verify(converter, times(1)).drawBindingRegion(any(), any()); } @Test public void testDrawModificationSite() throws Exception { - try { - BufferedImage bi = new BufferedImage(200, 200, BufferedImage.TYPE_INT_ARGB); - Graphics2D graphics = bi.createGraphics(); - - ModificationSite modificationSite = new ModificationSite(); - modificationSite.setPosition(new Point2D.Double(10, 10)); + BufferedImage bi = new BufferedImage(200, 200, BufferedImage.TYPE_INT_ARGB); + Graphics2D graphics = bi.createGraphics(); - ProteinConverter converter = Mockito.spy(new ProteinConverter(colorExtractor)); - converter.drawModification(modificationSite, graphics, false); - verify(converter, times(1)).drawModificationSite(any(), any(), anyBoolean()); + ModificationSite modificationSite = new ModificationSite(); + modificationSite.setPosition(new Point2D.Double(10, 10)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + ProteinConverter converter = Mockito.spy(new ProteinConverter(colorExtractor)); + converter.drawModification(modificationSite, graphics, false); + verify(converter, times(1)).drawModificationSite(any(), any(), anyBoolean()); } @Test public void testDrawProteinBindingRegion() throws Exception { - try { - BufferedImage bi = new BufferedImage(200, 200, BufferedImage.TYPE_INT_ARGB); - Graphics2D graphics = bi.createGraphics(); - - ProteinBindingDomain proteinBindingRegion = new ProteinBindingDomain(); - proteinBindingRegion.setPosition(new Point2D.Double(10, 10)); - proteinBindingRegion.setWidth(100); - proteinBindingRegion.setHeight(20); - - ProteinConverter converter = Mockito.spy(new ProteinConverter(colorExtractor)); - converter.drawModification(proteinBindingRegion, graphics, false); - verify(converter, times(1)).drawProteinBindingDomain(any(), any()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + BufferedImage bi = new BufferedImage(200, 200, BufferedImage.TYPE_INT_ARGB); + Graphics2D graphics = bi.createGraphics(); + + ProteinBindingDomain proteinBindingRegion = new ProteinBindingDomain(); + proteinBindingRegion.setPosition(new Point2D.Double(10, 10)); + proteinBindingRegion.setWidth(100); + proteinBindingRegion.setHeight(20); + + ProteinConverter converter = Mockito.spy(new ProteinConverter(colorExtractor)); + converter.drawModification(proteinBindingRegion, graphics, false); + verify(converter, times(1)).drawProteinBindingDomain(any(), any()); } @Test public void testDrawCodingRegion() throws Exception { - try { - BufferedImage bi = new BufferedImage(200, 200, BufferedImage.TYPE_INT_ARGB); - Graphics2D graphics = bi.createGraphics(); - - CodingRegion codingRegion = new CodingRegion(); - codingRegion.setPosition(new Point2D.Double(10, 10)); - codingRegion.setWidth(100); - codingRegion.setHeight(20); - - ProteinConverter converter = Mockito.spy(new ProteinConverter(colorExtractor)); - converter.drawModification(codingRegion, graphics, false); - verify(converter, times(1)).drawCodingRegion(any(), any()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + BufferedImage bi = new BufferedImage(200, 200, BufferedImage.TYPE_INT_ARGB); + Graphics2D graphics = bi.createGraphics(); + + CodingRegion codingRegion = new CodingRegion(); + codingRegion.setPosition(new Point2D.Double(10, 10)); + codingRegion.setWidth(100); + codingRegion.setHeight(20); + + ProteinConverter converter = Mockito.spy(new ProteinConverter(colorExtractor)); + converter.drawModification(codingRegion, graphics, false); + verify(converter, times(1)).drawCodingRegion(any(), any()); } @Test public void testDrawRegulatoryRegion() throws Exception { - try { - BufferedImage bi = new BufferedImage(200, 200, BufferedImage.TYPE_INT_ARGB); - Graphics2D graphics = bi.createGraphics(); - - RegulatoryRegion regulatoryRegion = new RegulatoryRegion(); - regulatoryRegion.setPosition(new Point2D.Double(10, 10)); - regulatoryRegion.setWidth(100); - regulatoryRegion.setHeight(20); - - ProteinConverter converter = Mockito.spy(new ProteinConverter(colorExtractor)); - converter.drawModification(regulatoryRegion, graphics, false); - verify(converter, times(1)).drawRegulatoryRegion(any(), any()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + BufferedImage bi = new BufferedImage(200, 200, BufferedImage.TYPE_INT_ARGB); + Graphics2D graphics = bi.createGraphics(); + + RegulatoryRegion regulatoryRegion = new RegulatoryRegion(); + regulatoryRegion.setPosition(new Point2D.Double(10, 10)); + regulatoryRegion.setWidth(100); + regulatoryRegion.setHeight(20); + + ProteinConverter converter = Mockito.spy(new ProteinConverter(colorExtractor)); + converter.drawModification(regulatoryRegion, graphics, false); + verify(converter, times(1)).drawRegulatoryRegion(any(), any()); } @Test public void testDrawTranscriptionSite() throws Exception { - try { - BufferedImage bi = new BufferedImage(200, 200, BufferedImage.TYPE_INT_ARGB); - Graphics2D graphics = bi.createGraphics(); - - TranscriptionSite transcriptionSite = new TranscriptionSite(); - transcriptionSite.setPosition(new Point2D.Double(10, 10)); - transcriptionSite.setWidth(100); - transcriptionSite.setHeight(20); - transcriptionSite.setActive(true); - transcriptionSite.setDirection("LEFT"); - - ProteinConverter converter = Mockito.spy(new ProteinConverter(colorExtractor)); - - converter.drawModification(transcriptionSite, graphics, false); - verify(converter, times(1)).drawTranscriptionSite(any(), any()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + BufferedImage bi = new BufferedImage(200, 200, BufferedImage.TYPE_INT_ARGB); + Graphics2D graphics = bi.createGraphics(); + + TranscriptionSite transcriptionSite = new TranscriptionSite(); + transcriptionSite.setPosition(new Point2D.Double(10, 10)); + transcriptionSite.setWidth(100); + transcriptionSite.setHeight(20); + transcriptionSite.setActive(true); + transcriptionSite.setDirection("LEFT"); + + ProteinConverter converter = Mockito.spy(new ProteinConverter(colorExtractor)); + + converter.drawModification(transcriptionSite, graphics, false); + verify(converter, times(1)).drawTranscriptionSite(any(), any()); } @Test public void testDrawTranscriptionSiteSize() throws Exception { - try { - BufferedImage bi = new BufferedImage(200, 200, BufferedImage.TYPE_INT_ARGB); - Graphics2D graphics = bi.createGraphics(); - - TranscriptionSite transcriptionSite = new TranscriptionSite(); - transcriptionSite.setPosition(new Point2D.Double(10, 10)); - transcriptionSite.setWidth(100); - transcriptionSite.setHeight(20); - transcriptionSite.setDirection("LEFT"); - - ArrowTransformation arrowTransformation = Mockito.spy(new ArrowTransformation()); - - ProteinConverter converter = new ProteinConverter(colorExtractor); - converter.setArrowTransformation(arrowTransformation); - - converter.drawModification(transcriptionSite, graphics, false); - verify(arrowTransformation, times(1)).drawLine( - argThat( - polylineData -> polylineData.getEndAtd().getLen() == SpeciesConverter.TRANSCRIPTION_SITE_ARROW_LENGTH), - any()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + BufferedImage bi = new BufferedImage(200, 200, BufferedImage.TYPE_INT_ARGB); + Graphics2D graphics = bi.createGraphics(); + + TranscriptionSite transcriptionSite = new TranscriptionSite(); + transcriptionSite.setPosition(new Point2D.Double(10, 10)); + transcriptionSite.setWidth(100); + transcriptionSite.setHeight(20); + transcriptionSite.setDirection("LEFT"); + + ArrowTransformation arrowTransformation = Mockito.spy(new ArrowTransformation()); + + ProteinConverter converter = new ProteinConverter(colorExtractor); + converter.setArrowTransformation(arrowTransformation); + + converter.drawModification(transcriptionSite, graphics, false); + verify(arrowTransformation, times(1)).drawLine( + argThat( + polylineData -> polylineData.getEndAtd().getLen() == SpeciesConverter.TRANSCRIPTION_SITE_ARROW_LENGTH), + any()); } @Test public void testDrawTranscriptionSiteDescription() throws Exception { - try { - BufferedImage bi = new BufferedImage(200, 200, BufferedImage.TYPE_INT_ARGB); - Graphics2D graphics = Mockito.spy(bi.createGraphics()); - - TranscriptionSite transcriptionSite = new TranscriptionSite(); - transcriptionSite.setPosition(new Point2D.Double(10, 10)); - transcriptionSite.setWidth(100); - transcriptionSite.setHeight(20); - transcriptionSite.setActive(true); - transcriptionSite.setDirection("LEFT"); - transcriptionSite.setName("x"); - - ProteinConverter converter = new ProteinConverter(colorExtractor); - - converter.drawModification(transcriptionSite, graphics, false); - verify(graphics, times(1)).drawString(anyString(), anyInt(), anyInt()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + BufferedImage bi = new BufferedImage(200, 200, BufferedImage.TYPE_INT_ARGB); + Graphics2D graphics = Mockito.spy(bi.createGraphics()); + + TranscriptionSite transcriptionSite = new TranscriptionSite(); + transcriptionSite.setPosition(new Point2D.Double(10, 10)); + transcriptionSite.setWidth(100); + transcriptionSite.setHeight(20); + transcriptionSite.setActive(true); + transcriptionSite.setDirection("LEFT"); + transcriptionSite.setName("x"); + + ProteinConverter converter = new ProteinConverter(colorExtractor); + + converter.drawModification(transcriptionSite, graphics, false); + verify(graphics, times(1)).drawString(anyString(), anyInt(), anyInt()); } @Test public void testDrawAliasWithGlyph() throws Exception { - try { - BufferedImage bi = new BufferedImage(200, 200, BufferedImage.TYPE_INT_ARGB); - Graphics2D graphics = Mockito.spy(bi.createGraphics()); - ProteinConverter rc = new ProteinConverter(colorExtractor); - - GenericProtein alias = createProtein(); - Glyph glyph = new Glyph(); - UploadedFileEntry file = new UploadedFileEntry(); - file.setOriginalFileName("test"); - byte[] fileContent = Files.readAllBytes(new File("testFiles/glyph.png").toPath()); - - file.setFileContent(fileContent); - glyph.setFile(file); - alias.setGlyph(glyph); - rc.draw(alias, graphics, new ConverterParams()); - - verify(graphics, times(1)).drawImage(any(Image.class), anyInt(), anyInt(), anyInt(), anyInt(), anyInt(), anyInt(), - anyInt(), anyInt(), nullable(ImageObserver.class)); - - } catch (Exception e) { - throw e; - } + BufferedImage bi = new BufferedImage(200, 200, BufferedImage.TYPE_INT_ARGB); + Graphics2D graphics = Mockito.spy(bi.createGraphics()); + ProteinConverter rc = new ProteinConverter(colorExtractor); + + GenericProtein alias = createProtein(); + Glyph glyph = new Glyph(); + UploadedFileEntry file = new UploadedFileEntry(); + file.setOriginalFileName("test"); + byte[] fileContent = Files.readAllBytes(new File("testFiles/glyph.png").toPath()); + + file.setFileContent(fileContent); + glyph.setFile(file); + alias.setGlyph(glyph); + rc.draw(alias, graphics, new ConverterParams()); + + verify(graphics, times(1)).drawImage(any(Image.class), anyInt(), anyInt(), anyInt(), anyInt(), anyInt(), anyInt(), + anyInt(), anyInt(), nullable(ImageObserver.class)); } } diff --git a/converter-graphics/src/test/java/lcsb/mapviewer/converter/graphics/geometry/ArrowTransformationTest.java b/converter-graphics/src/test/java/lcsb/mapviewer/converter/graphics/geometry/ArrowTransformationTest.java index f90dec91527104175b107b6685ea8e3801949dc2..ed479adf117df7b6caa3d1626ec959978b673bdd 100644 --- a/converter-graphics/src/test/java/lcsb/mapviewer/converter/graphics/geometry/ArrowTransformationTest.java +++ b/converter-graphics/src/test/java/lcsb/mapviewer/converter/graphics/geometry/ArrowTransformationTest.java @@ -1,6 +1,6 @@ package lcsb.mapviewer.converter.graphics.geometry; -import static org.junit.Assert.assertTrue; +import static org.junit.Assert.*; import java.awt.Color; import java.awt.Graphics2D; @@ -9,16 +9,16 @@ import java.awt.geom.Point2D; import java.awt.image.BufferedImage; import java.util.List; -import org.apache.logging.log4j.*; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.junit.*; import lcsb.mapviewer.common.geometry.PointTransformation; +import lcsb.mapviewer.converter.graphics.GraphicsTestFunctions; import lcsb.mapviewer.model.graphics.ArrowType; import lcsb.mapviewer.model.graphics.PolylineData; -public class ArrowTransformationTest { +public class ArrowTransformationTest extends GraphicsTestFunctions { Logger logger = LogManager.getLogger(ArrowTransformationTest.class); ArrowTransformation at = new ArrowTransformation(); @@ -34,49 +34,31 @@ public class ArrowTransformationTest { @Test public void testDrawingArrows() throws Exception { - try { - int coordX = 0; - int coordY = 10; - int height = 60; + int coordX = 0; + int coordY = 10; + int height = 60; - for (ArrowType type : ArrowType.values()) { - BufferedImage bi = new BufferedImage((int) 65, (int) 20, BufferedImage.TYPE_INT_ARGB); - Graphics2D graphics = bi.createGraphics(); + for (ArrowType type : ArrowType.values()) { + BufferedImage bi = new BufferedImage((int) 65, (int) 20, BufferedImage.TYPE_INT_ARGB); + Graphics2D graphics = bi.createGraphics(); - graphics.setColor(Color.BLACK); + graphics.setColor(Color.BLACK); - PolylineData pd = new PolylineData(new Point2D.Double(coordX, coordY), - new Point2D.Double(coordX + height, coordY)); - pd.getEndAtd().setArrowType(type); - at.drawLine(pd, graphics); - - // FileOutputStream fos = new FileOutputStream(new File(type.name() + ".png")); - // ImageIO.write(bi, "PNG", fos); - // fos.close(); - - // Desktop.getDesktop().open(new File(type.name() + ".png")); - - } - - } catch (Exception e) { - e.printStackTrace(); - throw e; + PolylineData pd = new PolylineData(new Point2D.Double(coordX, coordY), + new Point2D.Double(coordX + height, coordY)); + pd.getEndAtd().setArrowType(type); + at.drawLine(pd, graphics); } } @Test public void testGetArrowTrianglePointsForInvalidLibe() throws Exception { - try { - double angle = 1; - double len = 3; - Line2D line = new Line2D.Double(10, 20, 10, 20); - List<Point2D> points = at.getArrowTrianglePoints(line, len, angle); - for (Point2D point : points) { - assertTrue("Invalid point found: " + point, pointTransformation.isValidPoint(point)); - } - } catch (Exception e) { - e.printStackTrace(); - throw e; + double angle = 1; + double len = 3; + Line2D line = new Line2D.Double(10, 20, 10, 20); + List<Point2D> points = at.getArrowTrianglePoints(line, len, angle); + for (Point2D point : points) { + assertTrue("Invalid point found: " + point, pointTransformation.isValidPoint(point)); } } diff --git a/converter-graphics/src/test/java/lcsb/mapviewer/converter/graphics/geometry/FontFinderTest.java b/converter-graphics/src/test/java/lcsb/mapviewer/converter/graphics/geometry/FontFinderTest.java index 634f24d841fe365812d2f6256e2722ebddfe1584..4e2b9ac0d4c9d42a75ae464c94b7377a05d108ce 100644 --- a/converter-graphics/src/test/java/lcsb/mapviewer/converter/graphics/geometry/FontFinderTest.java +++ b/converter-graphics/src/test/java/lcsb/mapviewer/converter/graphics/geometry/FontFinderTest.java @@ -1,145 +1,108 @@ package lcsb.mapviewer.converter.graphics.geometry; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.Assert.*; -import java.awt.Color; -import java.awt.Font; -import java.awt.Graphics2D; +import java.awt.*; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; -public class FontFinderTest { +import lcsb.mapviewer.converter.graphics.GraphicsTestFunctions; - @Before - public void setUp() throws Exception { - } +public class FontFinderTest extends GraphicsTestFunctions { - @After - public void tearDown() throws Exception { - } + @Before + public void setUp() throws Exception { + } - @Test - public void testFindFontSize1() throws Exception { - try { - String text = "Some text to write"; - int coordX = 20; - int coordY = 40; - int height = 20; + @After + public void tearDown() throws Exception { + } - BufferedImage bi = new BufferedImage((int) 400, (int) 400, BufferedImage.TYPE_INT_ARGB); - Graphics2D graphics = bi.createGraphics(); - graphics.fill(new Rectangle2D.Double(0, 0, 400, 400)); + @Test + public void testFindFontSize1() throws Exception { + String text = "Some text to write"; + int coordX = 20; + int coordY = 40; + int height = 20; - Rectangle2D border = new Rectangle2D.Double(coordX, coordY, 100, height); + BufferedImage bi = new BufferedImage((int) 400, (int) 400, BufferedImage.TYPE_INT_ARGB); + Graphics2D graphics = bi.createGraphics(); + graphics.fill(new Rectangle2D.Double(0, 0, 400, 400)); - double size = FontFinder.findMaxFontSize(13, Font.SANS_SERIF, graphics, border, text); + Rectangle2D border = new Rectangle2D.Double(coordX, coordY, 100, height); - assertTrue(size < 13); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + double size = FontFinder.findMaxFontSize(13, Font.SANS_SERIF, graphics, border, text); - } + assertTrue(size < 13); + } - @Test - public void testFindFontSize2() throws Exception { - try { - String text = "Some text to write"; - int coordX = 20; - int coordY = 40; - int height = 60; + @Test + public void testFindFontSize2() throws Exception { + String text = "Some text to write"; + int coordX = 20; + int coordY = 40; + int height = 60; - BufferedImage bi = new BufferedImage((int) 400, (int) 400, BufferedImage.TYPE_INT_ARGB); - Graphics2D graphics = bi.createGraphics(); - graphics.fill(new Rectangle2D.Double(0, 0, 400, 400)); + BufferedImage bi = new BufferedImage((int) 400, (int) 400, BufferedImage.TYPE_INT_ARGB); + Graphics2D graphics = bi.createGraphics(); + graphics.fill(new Rectangle2D.Double(0, 0, 400, 400)); - Rectangle2D border = new Rectangle2D.Double(coordX, coordY, 100, height); + Rectangle2D border = new Rectangle2D.Double(coordX, coordY, 100, height); - double size = FontFinder.findMaxFontSize(20, Font.SANS_SERIF, graphics, border, text); + double size = FontFinder.findMaxFontSize(20, Font.SANS_SERIF, graphics, border, text); - graphics.setColor(Color.BLACK); - graphics.draw(border); - // graphics.setFont(new Font(Font.SANS_SERIF, 0, (int) size)); - FontFinder.drawText((int) size, Font.SANS_SERIF, graphics, border, text); + graphics.setColor(Color.BLACK); + graphics.draw(border); + FontFinder.drawText((int) size, Font.SANS_SERIF, graphics, border, text); - // graphics.drawString(text, coordX, coordY + height); + // different O compute it differently ... + assertTrue(size > 18); + assertTrue(size <= 20); + } - // FileOutputStream fos = new FileOutputStream(new File("tmp.png")); - // ImageIO.write(bi, "PNG", fos); - // fos.close(); + @Test + public void testFindFontSize3() throws Exception { + String text = "Some\ntext\n to write"; + int coordX = 20; + int coordY = 40; + int height = 60; - // Desktop.getDesktop().open(new File("tmp.png")); + BufferedImage bi = new BufferedImage((int) 400, (int) 400, BufferedImage.TYPE_INT_ARGB); + Graphics2D graphics = bi.createGraphics(); + graphics.fill(new Rectangle2D.Double(0, 0, 400, 400)); - //different os compute it differnetly ... - assertTrue(size>18); - assertTrue(size<=20); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Rectangle2D border = new Rectangle2D.Double(coordX, coordY, 100, height); - } + double size = FontFinder.findMaxFontSize(20, Font.SANS_SERIF, graphics, border, text); - @Test - public void testFindFontSize3() throws Exception { - try { - String text = "Some\ntext\n to write"; - int coordX = 20; - int coordY = 40; - int height = 60; + graphics.setColor(Color.BLACK); + graphics.draw(border); + FontFinder.drawText((int) size, Font.SANS_SERIF, graphics, border, text); - BufferedImage bi = new BufferedImage((int) 400, (int) 400, BufferedImage.TYPE_INT_ARGB); - Graphics2D graphics = bi.createGraphics(); - graphics.fill(new Rectangle2D.Double(0, 0, 400, 400)); + assertTrue(size < 20); + } - Rectangle2D border = new Rectangle2D.Double(coordX, coordY, 100, height); + @Test + public void testFindFontSize4() throws Exception { + String text = ""; + int coordX = 20; + int coordY = 40; + int height = 60; - double size = FontFinder.findMaxFontSize(20, Font.SANS_SERIF, graphics, border, text); + BufferedImage bi = new BufferedImage((int) 400, (int) 400, BufferedImage.TYPE_INT_ARGB); + Graphics2D graphics = bi.createGraphics(); + graphics.fill(new Rectangle2D.Double(0, 0, 400, 400)); - graphics.setColor(Color.BLACK); - graphics.draw(border); - // graphics.setFont(new Font(Font.SANS_SERIF, 0, (int) size)); - FontFinder.drawText((int) size, Font.SANS_SERIF, graphics, border, text); + Rectangle2D border = new Rectangle2D.Double(coordX, coordY, 100, height); - assertTrue(size < 20); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + double size = FontFinder.findMaxFontSize(20, Font.SANS_SERIF, graphics, border, text); - } + assertEquals(20, (int) size); + size = FontFinder.findMaxFontSize(20, Font.SANS_SERIF, graphics, border, " "); - @Test - public void testFindFontSize4() throws Exception { - try { - String text = ""; - int coordX = 20; - int coordY = 40; - int height = 60; - - BufferedImage bi = new BufferedImage((int) 400, (int) 400, BufferedImage.TYPE_INT_ARGB); - Graphics2D graphics = bi.createGraphics(); - graphics.fill(new Rectangle2D.Double(0, 0, 400, 400)); - - Rectangle2D border = new Rectangle2D.Double(coordX, coordY, 100, height); - - double size = FontFinder.findMaxFontSize(20, Font.SANS_SERIF, graphics, border, text); - - assertEquals(20, (int) size); - size = FontFinder.findMaxFontSize(20, Font.SANS_SERIF, graphics, border, " "); - - assertEquals(20, (int) size); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - - } + assertEquals(20, (int) size); + } } diff --git a/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/CellDesignerToMultiExportTest.java b/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/CellDesignerToMultiExportTest.java index 8f1b1876ffcaf1df37c22d26671d2efebe30abc2..414011212d4b77c1e09aa7b0d7ac7a0d00f01046 100644 --- a/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/CellDesignerToMultiExportTest.java +++ b/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/CellDesignerToMultiExportTest.java @@ -1,31 +1,27 @@ package lcsb.mapviewer.converter.model.sbml; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; +import static org.junit.Assert.*; + +import java.io.*; +import java.nio.file.*; import java.util.ArrayList; import java.util.Collection; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; -import lcsb.mapviewer.converter.ConverterParams; import lcsb.mapviewer.converter.Converter; +import lcsb.mapviewer.converter.ConverterParams; import lcsb.mapviewer.converter.model.celldesigner.CellDesignerXmlParser; import lcsb.mapviewer.model.map.model.Model; import lcsb.mapviewer.model.map.model.ModelComparator; @RunWith(Parameterized.class) -public class CellDesignerToMultiExportTest { +public class CellDesignerToMultiExportTest extends SbmlTestFunctions { static Logger logger = LogManager.getLogger(CellDesignerToMultiExportTest.class.getName()); @@ -48,29 +44,23 @@ public class CellDesignerToMultiExportTest { @Test public void createModelTest() throws Exception { - try { - Converter converter = new CellDesignerXmlParser(); - - Model model = converter.createModel(new ConverterParams().filename(filePath.toString())); - model.setName(null); + Converter converter = new CellDesignerXmlParser(); - SbmlExporter sbmlExporter = new SbmlExporter(); - SbmlParser sbmlParser = new SbmlParser(); - String xmlString = sbmlExporter.toXml(model); + Model model = converter.createModel(new ConverterParams().filename(filePath.toString())); + model.setName(null); - InputStream is = new ByteArrayInputStream(xmlString.getBytes("UTF-8")); + SbmlExporter sbmlExporter = new SbmlExporter(); + SbmlParser sbmlParser = new SbmlParser(); + String xmlString = sbmlExporter.toXml(model); - Model model2 = sbmlParser.createModel(new ConverterParams().inputStream(is).sizeAutoAdjust(false)); - model2.setName(null); + InputStream is = new ByteArrayInputStream(xmlString.getBytes("UTF-8")); - assertNotNull(model2); - ModelComparator comparator = new ModelComparator(1.0); - assertEquals(0, comparator.compare(model, model2)); + Model model2 = sbmlParser.createModel(new ConverterParams().inputStream(is).sizeAutoAdjust(false)); + model2.setName(null); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertNotNull(model2); + ModelComparator comparator = new ModelComparator(1.0); + assertEquals(0, comparator.compare(model, model2)); } } diff --git a/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/CopasiImportTest.java b/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/CopasiImportTest.java index d98c3a97d39be527ca627ec1da55467fc713eb93..10e04d311fd148b88a46b04fe023f3554d407ad0 100644 --- a/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/CopasiImportTest.java +++ b/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/CopasiImportTest.java @@ -1,26 +1,25 @@ package lcsb.mapviewer.converter.model.sbml; -import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.*; import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; +import java.nio.file.*; import java.util.ArrayList; import java.util.Collection; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; -import lcsb.mapviewer.converter.ConverterParams; import lcsb.mapviewer.converter.Converter; +import lcsb.mapviewer.converter.ConverterParams; import lcsb.mapviewer.model.map.model.Model; @RunWith(Parameterized.class) -public class CopasiImportTest extends SbmlTestFunctions{ +public class CopasiImportTest extends SbmlTestFunctions { static Logger logger = LogManager.getLogger(CopasiImportTest.class.getName()); @@ -43,17 +42,11 @@ public class CopasiImportTest extends SbmlTestFunctions{ @Test public void createModelTest() throws Exception { - try { - Converter converter = new SbmlParser(); - - Model model = converter.createModel(new ConverterParams().filename(filePath.toString())); - assertNotNull(model); - converter.model2InputStream(model); + Converter converter = new SbmlParser(); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Model model = converter.createModel(new ConverterParams().filename(filePath.toString())); + assertNotNull(model); + converter.model2InputStream(model); } } diff --git a/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/ElementPropertiesExport.java b/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/ElementPropertiesExport.java index 20743bf242f202dde67b15393500dcadc968dfee..015e5fe98754237a9c8f3ef760359865f9de22b1 100644 --- a/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/ElementPropertiesExport.java +++ b/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/ElementPropertiesExport.java @@ -1,23 +1,20 @@ package lcsb.mapviewer.converter.model.sbml; -import static org.junit.Assert.assertEquals; +import static org.junit.Assert.*; -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; +import java.io.*; import java.util.ArrayList; import java.util.Collection; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; import lcsb.mapviewer.converter.ConverterParams; -import lcsb.mapviewer.model.map.model.Model; -import lcsb.mapviewer.model.map.model.ModelComparator; -import lcsb.mapviewer.model.map.model.ModelFullIndexed; +import lcsb.mapviewer.model.map.model.*; import lcsb.mapviewer.model.map.species.Element; import lcsb.mapviewer.model.map.species.Species; @@ -68,24 +65,18 @@ public class ElementPropertiesExport extends SbmlTestFunctions { @Test public void createModelTest() throws Exception { - try { - SbmlExporter sbmlExporter = new SbmlExporter(); - sbmlExporter.setProvideDefaults(false); - SbmlParser sbmlParser = new SbmlParser(); - String xmlString = sbmlExporter.toXml(model); + SbmlExporter sbmlExporter = new SbmlExporter(); + sbmlExporter.setProvideDefaults(false); + SbmlParser sbmlParser = new SbmlParser(); + String xmlString = sbmlExporter.toXml(model); - InputStream is = new ByteArrayInputStream(xmlString.getBytes("UTF-8")); + InputStream is = new ByteArrayInputStream(xmlString.getBytes("UTF-8")); - Model model2 = sbmlParser.createModel(new ConverterParams().inputStream(is).sizeAutoAdjust(false)); - model2.setName(model.getName()); + Model model2 = sbmlParser.createModel(new ConverterParams().inputStream(is).sizeAutoAdjust(false)); + model2.setName(model.getName()); - ModelComparator comparator = new ModelComparator(); - assertEquals(0, comparator.compare(model, model2)); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + ModelComparator comparator = new ModelComparator(); + assertEquals(0, comparator.compare(model, model2)); } } diff --git a/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/ElementPropertiesExportToLayoutTest.java b/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/ElementPropertiesExportToLayoutTest.java index d9ed2f12c7b5ccb3189fd0922d427db43c968afa..0d0599802879831288996e839551d186c09106c0 100644 --- a/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/ElementPropertiesExportToLayoutTest.java +++ b/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/ElementPropertiesExportToLayoutTest.java @@ -1,23 +1,20 @@ package lcsb.mapviewer.converter.model.sbml; -import static org.junit.Assert.assertEquals; +import static org.junit.Assert.*; -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; +import java.io.*; import java.util.ArrayList; import java.util.Collection; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; import lcsb.mapviewer.converter.ConverterParams; -import lcsb.mapviewer.model.map.model.Model; -import lcsb.mapviewer.model.map.model.ModelComparator; -import lcsb.mapviewer.model.map.model.ModelFullIndexed; +import lcsb.mapviewer.model.map.model.*; import lcsb.mapviewer.model.map.species.Element; import lcsb.mapviewer.model.map.species.Species; @@ -56,24 +53,18 @@ public class ElementPropertiesExportToLayoutTest extends SbmlTestFunctions { @Test public void createModelTest() throws Exception { - try { - SbmlExporter sbmlExporter = new SbmlExporter(); - sbmlExporter.setProvideDefaults(false); - SbmlParser sbmlParser = new SbmlParser(); - String xmlString = sbmlExporter.toXml(model); + SbmlExporter sbmlExporter = new SbmlExporter(); + sbmlExporter.setProvideDefaults(false); + SbmlParser sbmlParser = new SbmlParser(); + String xmlString = sbmlExporter.toXml(model); - InputStream is = new ByteArrayInputStream(xmlString.getBytes("UTF-8")); + InputStream is = new ByteArrayInputStream(xmlString.getBytes("UTF-8")); - Model model2 = sbmlParser.createModel(new ConverterParams().inputStream(is).sizeAutoAdjust(false)); - model2.setName(model.getName()); + Model model2 = sbmlParser.createModel(new ConverterParams().inputStream(is).sizeAutoAdjust(false)); + model2.setName(model.getName()); - ModelComparator comparator = new ModelComparator(); - assertEquals(0, comparator.compare(model, model2)); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + ModelComparator comparator = new ModelComparator(); + assertEquals(0, comparator.compare(model, model2)); } } diff --git a/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/ElementPropertiesExportToMultiTest.java b/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/ElementPropertiesExportToMultiTest.java index 50cb4b1f7ca95cefa988ff5ad31cb930f00888ab..af722e4bb0b6bbf4ae23f376f6315e5af6abc6e7 100644 --- a/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/ElementPropertiesExportToMultiTest.java +++ b/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/ElementPropertiesExportToMultiTest.java @@ -1,24 +1,19 @@ package lcsb.mapviewer.converter.model.sbml; -import static org.junit.Assert.assertEquals; +import static org.junit.Assert.*; -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; +import java.io.*; +import java.util.*; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; import lcsb.mapviewer.converter.ConverterParams; -import lcsb.mapviewer.model.map.model.Model; -import lcsb.mapviewer.model.map.model.ModelComparator; -import lcsb.mapviewer.model.map.model.ModelFullIndexed; +import lcsb.mapviewer.model.map.model.*; import lcsb.mapviewer.model.map.species.Element; import lcsb.mapviewer.model.map.species.Species; @@ -93,24 +88,18 @@ public class ElementPropertiesExportToMultiTest extends SbmlTestFunctions { @Test public void createModelTest() throws Exception { - try { - SbmlExporter sbmlExporter = new SbmlExporter(); - sbmlExporter.setProvideDefaults(false); - SbmlParser sbmlParser = new SbmlParser(); - String xmlString = sbmlExporter.toXml(model); + SbmlExporter sbmlExporter = new SbmlExporter(); + sbmlExporter.setProvideDefaults(false); + SbmlParser sbmlParser = new SbmlParser(); + String xmlString = sbmlExporter.toXml(model); - InputStream is = new ByteArrayInputStream(xmlString.getBytes("UTF-8")); + InputStream is = new ByteArrayInputStream(xmlString.getBytes("UTF-8")); - Model model2 = sbmlParser.createModel(new ConverterParams().inputStream(is).sizeAutoAdjust(false)); - model2.setName(model.getName()); + Model model2 = sbmlParser.createModel(new ConverterParams().inputStream(is).sizeAutoAdjust(false)); + model2.setName(model.getName()); - ModelComparator comparator = new ModelComparator(); - assertEquals(0, comparator.compare(model, model2)); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + ModelComparator comparator = new ModelComparator(); + assertEquals(0, comparator.compare(model, model2)); } } diff --git a/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/GenericSbmlParserTest.java b/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/GenericSbmlParserTest.java index aa3b251c4df47407e90dfe263b239170f6ea39a4..2b46babbafc0594f33211f2f01c902af91ded698 100644 --- a/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/GenericSbmlParserTest.java +++ b/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/GenericSbmlParserTest.java @@ -1,30 +1,23 @@ package lcsb.mapviewer.converter.model.sbml; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - -import java.io.ByteArrayInputStream; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; +import static org.junit.Assert.*; + +import java.io.*; +import java.nio.file.*; import java.util.ArrayList; import java.util.Collection; import org.apache.commons.io.FileUtils; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; -import lcsb.mapviewer.converter.ConverterParams; import lcsb.mapviewer.converter.Converter; -import lcsb.mapviewer.converter.graphics.AbstractImageGenerator; -import lcsb.mapviewer.converter.graphics.NormalImageGenerator; -import lcsb.mapviewer.converter.graphics.PngImageGenerator; +import lcsb.mapviewer.converter.ConverterParams; +import lcsb.mapviewer.converter.graphics.*; import lcsb.mapviewer.converter.model.celldesigner.CellDesignerXmlParser; import lcsb.mapviewer.model.map.BioEntity; import lcsb.mapviewer.model.map.model.Model; @@ -32,7 +25,7 @@ import lcsb.mapviewer.model.map.model.ModelComparator; import lcsb.mapviewer.model.map.reaction.ReactionComparator; @RunWith(Parameterized.class) -public class GenericSbmlParserTest { +public class GenericSbmlParserTest extends SbmlTestFunctions { static Logger logger = LogManager.getLogger(GenericSbmlParserTest.class.getName()); @@ -60,53 +53,46 @@ public class GenericSbmlParserTest { @Test public void createModelTest() throws Exception { - try { - String dir = Files.createTempDirectory("sbml-temp-images-dir").toFile().getAbsolutePath(); + String dir = Files.createTempDirectory("sbml-temp-images-dir").toFile().getAbsolutePath(); - Converter converter = new SbmlParser(); + Converter converter = new SbmlParser(); - Model model = converter.createModel(new ConverterParams().filename(filePath.toString())); - model.setName(null); + Model model = converter.createModel(new ConverterParams().filename(filePath.toString())); + model.setName(null); - // Create and display image of parsed map - AbstractImageGenerator.Params params = new AbstractImageGenerator.Params().height(model.getHeight()) - .width(model.getWidth()).nested(true).scale(1).level(20).x(0).y(0).model(model); - NormalImageGenerator nig = new PngImageGenerator(params); - String pathWithouExtension = dir + "/" - + filePath.getFileName().toString().substring(0, filePath.getFileName().toString().indexOf(".xml")); - String pngFilePath = pathWithouExtension.concat(".png"); - nig.saveToFile(pngFilePath); - // Desktop.getDesktop().open(new File(pngFilePath)); + // Create and display image of parsed map + AbstractImageGenerator.Params params = new AbstractImageGenerator.Params().height(model.getHeight()) + .width(model.getWidth()).nested(true).scale(1).level(20).x(0).y(0).model(model); + NormalImageGenerator nig = new PngImageGenerator(params); + String pathWithouExtension = dir + "/" + + filePath.getFileName().toString().substring(0, filePath.getFileName().toString().indexOf(".xml")); + String pngFilePath = pathWithouExtension.concat(".png"); + nig.saveToFile(pngFilePath); - CellDesignerXmlParser cellDesignerXmlParser = new CellDesignerXmlParser(); - String xmlString = cellDesignerXmlParser.model2String(model); + CellDesignerXmlParser cellDesignerXmlParser = new CellDesignerXmlParser(); + String xmlString = cellDesignerXmlParser.model2String(model); - InputStream is = new ByteArrayInputStream(xmlString.getBytes("UTF-8")); + InputStream is = new ByteArrayInputStream(xmlString.getBytes("UTF-8")); - Model model2 = cellDesignerXmlParser.createModel(new ConverterParams().inputStream(is).sizeAutoAdjust(false)); + Model model2 = cellDesignerXmlParser.createModel(new ConverterParams().inputStream(is).sizeAutoAdjust(false)); - AbstractImageGenerator.Params params2 = new AbstractImageGenerator.Params().height(model2.getHeight()) - .width(model2.getWidth()).nested(true).scale(1).level(20).x(0).y(0).model(model2); - NormalImageGenerator nig2 = new PngImageGenerator(params2); - String pngFilePath2 = pathWithouExtension.concat("_2.png"); - nig2.saveToFile(pngFilePath2); + AbstractImageGenerator.Params params2 = new AbstractImageGenerator.Params().height(model2.getHeight()) + .width(model2.getWidth()).nested(true).scale(1).level(20).x(0).y(0).model(model2); + NormalImageGenerator nig2 = new PngImageGenerator(params2); + String pngFilePath2 = pathWithouExtension.concat("_2.png"); + nig2.saveToFile(pngFilePath2); - assertNotNull(model2); - ModelComparator comparator = new ModelComparator(1.0); - for (BioEntity bioEntity: model.getBioEntities()) { - bioEntity.setZ(null); - } - for (BioEntity bioEntity: model2.getBioEntities()) { - bioEntity.setZ(null); - } - comparator.getReactionSetComparator().setObjectComparator(new ReactionComparator(1.0, true)); - assertEquals(0, comparator.compare(model, model2)); - FileUtils.deleteDirectory(new File(dir)); - - } catch (Exception e) { - e.printStackTrace(); - throw e; + assertNotNull(model2); + ModelComparator comparator = new ModelComparator(1.0); + for (BioEntity bioEntity : model.getBioEntities()) { + bioEntity.setZ(null); + } + for (BioEntity bioEntity : model2.getBioEntities()) { + bioEntity.setZ(null); } + comparator.getReactionSetComparator().setObjectComparator(new ReactionComparator(1.0, true)); + assertEquals(0, comparator.compare(model, model2)); + FileUtils.deleteDirectory(new File(dir)); } } diff --git a/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/GenericSbmlToXmlParserTest.java b/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/GenericSbmlToXmlParserTest.java index 965e38c3f09632dbfb4a672115bd32916a874356..4c56a69dfcc51120fada4cfbccec1080e8ef60b2 100644 --- a/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/GenericSbmlToXmlParserTest.java +++ b/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/GenericSbmlToXmlParserTest.java @@ -1,18 +1,16 @@ package lcsb.mapviewer.converter.model.sbml; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.*; import java.io.File; import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; +import java.nio.file.*; import java.util.ArrayList; import java.util.Collection; import org.apache.commons.io.FileUtils; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; @@ -23,7 +21,7 @@ import lcsb.mapviewer.model.map.model.Model; import lcsb.mapviewer.model.map.model.ModelComparator; @RunWith(Parameterized.class) -public class GenericSbmlToXmlParserTest { +public class GenericSbmlToXmlParserTest extends SbmlTestFunctions { static Logger logger = LogManager.getLogger(GenericSbmlToXmlParserTest.class.getName()); @@ -51,34 +49,26 @@ public class GenericSbmlToXmlParserTest { @Test public void toXmlModelTest() throws Exception { - try { + String dir = Files.createTempDirectory("sbgn-temp-images-dir").toFile().getAbsolutePath(); - String dir = Files.createTempDirectory("sbgn-temp-images-dir").toFile().getAbsolutePath(); + SbmlParser converter = new SbmlParser(); + converter.setProvideDefaults(false); - SbmlParser converter = new SbmlParser(); - converter.setProvideDefaults(false); + Model model = converter.createModel(new ConverterParams().filename(filePath.toString())); + model.setName(null); - Model model = converter.createModel(new ConverterParams().filename(filePath.toString())); - model.setName(null); + String pathWithouExtension = dir + "/" + + filePath.getFileName().toString().substring(0, filePath.getFileName().toString().indexOf(".xml")); + String xmlFilePath = pathWithouExtension.concat(".xml"); + converter.model2File(model, xmlFilePath); - String pathWithouExtension = dir + "/" - + filePath.getFileName().toString().substring(0, filePath.getFileName().toString().indexOf(".xml")); - String xmlFilePath = pathWithouExtension.concat(".xml"); - converter.model2File(model, xmlFilePath); + Model model2 = converter.createModel(new ConverterParams().filename(xmlFilePath).sizeAutoAdjust(false)); + model2.setName(null); - Model model2 = converter.createModel(new ConverterParams().filename(xmlFilePath).sizeAutoAdjust(false)); - model2.setName(null); - - assertNotNull(model2); - ModelComparator comparator = new ModelComparator(1.0); - assertEquals(0, comparator.compare(model, model2)); - FileUtils.deleteDirectory(new File(dir)); - - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - throw e; - } + assertNotNull(model2); + ModelComparator comparator = new ModelComparator(1.0); + assertEquals(0, comparator.compare(model, model2)); + FileUtils.deleteDirectory(new File(dir)); } } diff --git a/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/MultiParserTest.java b/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/MultiParserTest.java index 0772d2988cd0003b081aaf21dd2e10ecf7370552..13afe4a261c45fbdc41c6474f8f61c7a916814e3 100644 --- a/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/MultiParserTest.java +++ b/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/MultiParserTest.java @@ -1,36 +1,29 @@ package lcsb.mapviewer.converter.model.sbml; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - -import java.io.ByteArrayInputStream; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; +import static org.junit.Assert.*; + +import java.io.*; +import java.nio.file.*; import java.util.ArrayList; import java.util.Collection; import org.apache.commons.io.FileUtils; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; -import lcsb.mapviewer.converter.ConverterParams; import lcsb.mapviewer.converter.Converter; -import lcsb.mapviewer.converter.graphics.AbstractImageGenerator; -import lcsb.mapviewer.converter.graphics.NormalImageGenerator; -import lcsb.mapviewer.converter.graphics.PngImageGenerator; +import lcsb.mapviewer.converter.ConverterParams; +import lcsb.mapviewer.converter.graphics.*; import lcsb.mapviewer.converter.model.celldesigner.CellDesignerXmlParser; import lcsb.mapviewer.model.map.model.Model; import lcsb.mapviewer.model.map.model.ModelComparator; @RunWith(Parameterized.class) -public class MultiParserTest { +public class MultiParserTest extends SbmlTestFunctions { static Logger logger = LogManager.getLogger(MultiParserTest.class.getName()); @@ -53,47 +46,39 @@ public class MultiParserTest { @Test public void createModelTest() throws Exception { - try { - String dir = Files.createTempDirectory("sbml-temp-images-dir").toFile().getAbsolutePath(); - - Converter converter = new SbmlParser(); - - Model model = converter.createModel(new ConverterParams().filename(filePath.toString())); - model.setName(null); - - // Create and display image of parsed map - AbstractImageGenerator.Params params = new AbstractImageGenerator.Params().height(model.getHeight()) - .width(model.getWidth()).nested(true).scale(1).level(20).x(0).y(0).model(model); - NormalImageGenerator nig = new PngImageGenerator(params); - String pathWithouExtension = dir + "/" - + filePath.getFileName().toString().substring(0, filePath.getFileName().toString().indexOf(".xml")); - String pngFilePath = pathWithouExtension.concat(".png"); - nig.saveToFile(pngFilePath); - // Desktop.getDesktop().open(new File(pngFilePath)); - - CellDesignerXmlParser cellDesignerXmlParser = new CellDesignerXmlParser(); - String xmlString = cellDesignerXmlParser.model2String(model); - - InputStream is = new ByteArrayInputStream(xmlString.getBytes("UTF-8")); - - Model model2 = cellDesignerXmlParser.createModel(new ConverterParams().inputStream(is).sizeAutoAdjust(false)); - - AbstractImageGenerator.Params params2 = new AbstractImageGenerator.Params().height(model2.getHeight()) - .width(model2.getWidth()).nested(true).scale(1).level(20).x(0).y(0).model(model2); - NormalImageGenerator nig2 = new PngImageGenerator(params2); - String pngFilePath2 = pathWithouExtension.concat("_2.png"); - nig2.saveToFile(pngFilePath2); - - assertNotNull(model2); - ModelComparator comparator = new ModelComparator(1.0); - assertEquals(0, comparator.compare(model, model2)); - FileUtils.deleteDirectory(new File(dir)); - - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - throw e; - } + String dir = Files.createTempDirectory("sbml-temp-images-dir").toFile().getAbsolutePath(); + + Converter converter = new SbmlParser(); + + Model model = converter.createModel(new ConverterParams().filename(filePath.toString())); + model.setName(null); + + // Create and display image of parsed map + AbstractImageGenerator.Params params = new AbstractImageGenerator.Params().height(model.getHeight()) + .width(model.getWidth()).nested(true).scale(1).level(20).x(0).y(0).model(model); + NormalImageGenerator nig = new PngImageGenerator(params); + String pathWithouExtension = dir + "/" + + filePath.getFileName().toString().substring(0, filePath.getFileName().toString().indexOf(".xml")); + String pngFilePath = pathWithouExtension.concat(".png"); + nig.saveToFile(pngFilePath); + + CellDesignerXmlParser cellDesignerXmlParser = new CellDesignerXmlParser(); + String xmlString = cellDesignerXmlParser.model2String(model); + + InputStream is = new ByteArrayInputStream(xmlString.getBytes("UTF-8")); + + Model model2 = cellDesignerXmlParser.createModel(new ConverterParams().inputStream(is).sizeAutoAdjust(false)); + + AbstractImageGenerator.Params params2 = new AbstractImageGenerator.Params().height(model2.getHeight()) + .width(model2.getWidth()).nested(true).scale(1).level(20).x(0).y(0).model(model2); + NormalImageGenerator nig2 = new PngImageGenerator(params2); + String pngFilePath2 = pathWithouExtension.concat("_2.png"); + nig2.saveToFile(pngFilePath2); + + assertNotNull(model2); + ModelComparator comparator = new ModelComparator(1.0); + assertEquals(0, comparator.compare(model, model2)); + FileUtils.deleteDirectory(new File(dir)); } } diff --git a/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/ReactionPropertiesExportToMultiTest.java b/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/ReactionPropertiesExportToMultiTest.java index dd4c81fe20f8e65c415c8c63066588aa69d9ee2f..19c2ee4938bcd44e1ffd828d6d3f55b17cd8c83c 100644 --- a/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/ReactionPropertiesExportToMultiTest.java +++ b/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/ReactionPropertiesExportToMultiTest.java @@ -1,16 +1,13 @@ package lcsb.mapviewer.converter.model.sbml; -import static org.junit.Assert.assertEquals; +import static org.junit.Assert.*; import java.awt.geom.Point2D; -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; - -import org.apache.logging.log4j.*; +import java.io.*; +import java.util.*; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; @@ -19,19 +16,14 @@ import org.junit.runners.Parameterized.Parameters; import lcsb.mapviewer.converter.ConverterParams; import lcsb.mapviewer.model.graphics.PolylineData; -import lcsb.mapviewer.model.map.model.Model; -import lcsb.mapviewer.model.map.model.ModelComparator; -import lcsb.mapviewer.model.map.model.ModelFullIndexed; -import lcsb.mapviewer.model.map.reaction.Product; -import lcsb.mapviewer.model.map.reaction.Reactant; -import lcsb.mapviewer.model.map.reaction.Reaction; -import lcsb.mapviewer.model.map.reaction.ReactionNode; +import lcsb.mapviewer.model.map.model.*; +import lcsb.mapviewer.model.map.reaction.*; import lcsb.mapviewer.model.map.reaction.type.StateTransitionReaction; import lcsb.mapviewer.model.map.species.Ion; @Ignore("Not supported by multi extension") @RunWith(Parameterized.class) -public class ReactionPropertiesExportToMultiTest { +public class ReactionPropertiesExportToMultiTest extends SbmlTestFunctions { static Logger logger = LogManager.getLogger(ReactionPropertiesExportToMultiTest.class.getName()); @@ -144,24 +136,18 @@ public class ReactionPropertiesExportToMultiTest { @Test public void createModelTest() throws Exception { - try { - SbmlExporter sbmlExporter = new SbmlExporter(); - SbmlParser sbmlParser = new SbmlParser(); - String xmlString = sbmlExporter.toXml(model); - - InputStream is = new ByteArrayInputStream(xmlString.getBytes("UTF-8")); + SbmlExporter sbmlExporter = new SbmlExporter(); + SbmlParser sbmlParser = new SbmlParser(); + String xmlString = sbmlExporter.toXml(model); - Model model2 = sbmlParser.createModel(new ConverterParams().inputStream(is).sizeAutoAdjust(false)); - model2.setName(model.getName()); - model2.getReactions().iterator().next().setIdReaction(reactionId); + InputStream is = new ByteArrayInputStream(xmlString.getBytes("UTF-8")); - ModelComparator comparator = new ModelComparator(); - assertEquals(0, comparator.compare(model, model2)); + Model model2 = sbmlParser.createModel(new ConverterParams().inputStream(is).sizeAutoAdjust(false)); + model2.setName(model.getName()); + model2.getReactions().iterator().next().setIdReaction(reactionId); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + ModelComparator comparator = new ModelComparator(); + assertEquals(0, comparator.compare(model, model2)); } } diff --git a/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/SbmlExporterFromCellDesignerTest.java b/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/SbmlExporterFromCellDesignerTest.java index 3bdf0a5b846f9fdc723767c9c62263f0d1cffcde..0d44c40bd7ed2126ec95dc702ce9e79ff420167e 100644 --- a/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/SbmlExporterFromCellDesignerTest.java +++ b/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/SbmlExporterFromCellDesignerTest.java @@ -1,10 +1,11 @@ package lcsb.mapviewer.converter.model.sbml; -import static org.junit.Assert.assertEquals; +import static org.junit.Assert.*; import java.io.ByteArrayInputStream; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.junit.Test; import lcsb.mapviewer.converter.ConverterParams; @@ -22,31 +23,26 @@ public class SbmlExporterFromCellDesignerTest extends SbmlTestFunctions { @Test public void testExportHeterodimerAssociation() throws Exception { - try { - Model originalModel = cellDesignerXmlParser - .createModel(new ConverterParams().filename("testFiles/cell_designer_problems/heterodimer_association.xml")); - Model model = getModelAfterSerializing(originalModel); - Reaction reaction1 = originalModel.getReactions().iterator().next(); - Reaction reaction2 = model.getReactions().iterator().next(); - // change reaction id - due to some issues it cannot be persisted properly in - // sbml format - reaction2.setIdReaction(reaction1.getIdReaction()); - - model.setName(originalModel.getName()); - - String cellDesignerXml = cellDesignerXmlParser.model2String(model); - ByteArrayInputStream stream = new ByteArrayInputStream(cellDesignerXml.getBytes("UTF-8")); - - assertEquals(0, comparator.compare(model, originalModel)); - Model cdModel = cellDesignerXmlParser.createModel(new ConverterParams().inputStream(stream)); - - cdModel.setName(originalModel.getName()); - - assertEquals(0, comparator.compare(model, cdModel)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Model originalModel = cellDesignerXmlParser + .createModel(new ConverterParams().filename("testFiles/cell_designer_problems/heterodimer_association.xml")); + Model model = getModelAfterSerializing(originalModel); + Reaction reaction1 = originalModel.getReactions().iterator().next(); + Reaction reaction2 = model.getReactions().iterator().next(); + // change reaction id - due to some issues it cannot be persisted properly in + // sbml format + reaction2.setIdReaction(reaction1.getIdReaction()); + + model.setName(originalModel.getName()); + + String cellDesignerXml = cellDesignerXmlParser.model2String(model); + ByteArrayInputStream stream = new ByteArrayInputStream(cellDesignerXml.getBytes("UTF-8")); + + assertEquals(0, comparator.compare(model, originalModel)); + Model cdModel = cellDesignerXmlParser.createModel(new ConverterParams().inputStream(stream)); + + cdModel.setName(originalModel.getName()); + + assertEquals(0, comparator.compare(model, cdModel)); } } diff --git a/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/SbmlExporterTest.java b/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/SbmlExporterTest.java index 64f29afefbc4a7e34c78fdf0728f89ac7ffaafba..0cdda07e1687c69a68e9c8d3d2729e87b29cdd40 100644 --- a/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/SbmlExporterTest.java +++ b/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/SbmlExporterTest.java @@ -1,29 +1,20 @@ package lcsb.mapviewer.converter.model.sbml; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.Assert.*; import java.awt.Color; import java.awt.geom.Line2D; import java.awt.geom.Point2D; import java.io.File; import java.lang.reflect.Modifier; -import java.util.Arrays; -import java.util.List; -import java.util.Set; +import java.util.*; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.junit.Test; import org.reflections.Reflections; import org.sbml.jsbml.SBMLDocument; -import org.sbml.jsbml.ext.multi.MultiModelPlugin; -import org.sbml.jsbml.ext.multi.MultiSpeciesPlugin; -import org.sbml.jsbml.ext.multi.MultiSpeciesType; -import org.sbml.jsbml.ext.multi.PossibleSpeciesFeatureValue; -import org.sbml.jsbml.ext.multi.SpeciesFeatureType; +import org.sbml.jsbml.ext.multi.*; import lcsb.mapviewer.common.Configuration; import lcsb.mapviewer.common.comparator.LineComparator; @@ -31,20 +22,10 @@ import lcsb.mapviewer.common.comparator.ListComparator; import lcsb.mapviewer.converter.ConverterParams; import lcsb.mapviewer.converter.model.celldesigner.CellDesignerXmlParser; import lcsb.mapviewer.model.map.compartment.Compartment; -import lcsb.mapviewer.model.map.model.Model; -import lcsb.mapviewer.model.map.model.ModelComparator; -import lcsb.mapviewer.model.map.model.ModelFullIndexed; -import lcsb.mapviewer.model.map.reaction.AbstractNode; -import lcsb.mapviewer.model.map.reaction.NodeOperator; -import lcsb.mapviewer.model.map.reaction.Product; -import lcsb.mapviewer.model.map.reaction.Reaction; -import lcsb.mapviewer.model.map.reaction.ReactionNode; -import lcsb.mapviewer.model.map.species.Element; -import lcsb.mapviewer.model.map.species.GenericProtein; -import lcsb.mapviewer.model.map.species.Species; -import lcsb.mapviewer.model.map.species.field.ModificationState; -import lcsb.mapviewer.model.map.species.field.PositionToCompartment; -import lcsb.mapviewer.model.map.species.field.Residue; +import lcsb.mapviewer.model.map.model.*; +import lcsb.mapviewer.model.map.reaction.*; +import lcsb.mapviewer.model.map.species.*; +import lcsb.mapviewer.model.map.species.field.*; public class SbmlExporterTest extends SbmlTestFunctions { Logger logger = LogManager.getLogger(SbmlExporterTest.class); @@ -578,9 +559,9 @@ public class SbmlExporterTest extends SbmlTestFunctions { NodeOperator o1 = r1.getOperators().get(0); NodeOperator o11 = r1.getOperators().get(1); NodeOperator o2 = r2.getOperators().get(0); - - assertEquals(p1.getLine().length()+o1.getLine().length()+o11.getLine().length()+r1.getLine().length(), - p2.getLine().length()+o2.getLine().length()+r2.getLine().length(), Configuration.EPSILON); + + assertEquals(p1.getLine().length() + o1.getLine().length() + o11.getLine().length() + r1.getLine().length(), + p2.getLine().length() + o2.getLine().length() + r2.getLine().length(), Configuration.EPSILON); } @@ -600,17 +581,11 @@ public class SbmlExporterTest extends SbmlTestFunctions { @Test public void testExportIronMetabolismReaction() throws Exception { - try { - Model originalModel = new CellDesignerXmlParser() - .createModel(new ConverterParams().filename("testFiles/cell_designer_problems/iron_metabolism_reaction.xml")); - exporter.setProvideDefaults(false); - String xml = exporter.toXml(originalModel); - assertNotNull(xml); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - + Model originalModel = new CellDesignerXmlParser() + .createModel(new ConverterParams().filename("testFiles/cell_designer_problems/iron_metabolism_reaction.xml")); + exporter.setProvideDefaults(false); + String xml = exporter.toXml(originalModel); + assertNotNull(xml); } @Test diff --git a/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/SbmlPareserForInvalidReactionTest.java b/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/SbmlPareserForInvalidReactionTest.java index 4f4f0f41ee5c3b5e6a26525dee1eda23edd4a603..a870709d73dd9dd1fc3cfafb5adbfbb0e5468cf4 100644 --- a/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/SbmlPareserForInvalidReactionTest.java +++ b/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/SbmlPareserForInvalidReactionTest.java @@ -1,26 +1,21 @@ package lcsb.mapviewer.converter.model.sbml; -import static org.junit.Assert.fail; - import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; +import java.nio.file.*; import java.util.ArrayList; import java.util.Collection; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; -import lcsb.mapviewer.converter.ConverterParams; -import lcsb.mapviewer.converter.Converter; -import lcsb.mapviewer.converter.InvalidInputDataExecption; +import lcsb.mapviewer.converter.*; @RunWith(Parameterized.class) -public class SbmlPareserForInvalidReactionTest { +public class SbmlPareserForInvalidReactionTest extends SbmlTestFunctions { static Logger logger = LogManager.getLogger(SbmlPareserForInvalidReactionTest.class.getName()); @@ -41,18 +36,10 @@ public class SbmlPareserForInvalidReactionTest { return data; } - @Test + @Test(expected = InvalidInputDataExecption.class) public void createModelTest() throws Exception { - try { - Converter converter = new SbmlParser(); - - converter.createModel(new ConverterParams().filename(filePath.toString())); - fail("Exception expected when parsing file: " + filePath.toString()); - } catch (InvalidInputDataExecption e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Converter converter = new SbmlParser(); + converter.createModel(new ConverterParams().filename(filePath.toString())); } } diff --git a/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/SbmlParserTest.java b/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/SbmlParserTest.java index 8147576f8a6781c625efb6a78b79219d3ee4d0d2..28885299cfd8eab16cc8ddbd49c97847dc604255 100644 --- a/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/SbmlParserTest.java +++ b/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/SbmlParserTest.java @@ -1,15 +1,13 @@ package lcsb.mapviewer.converter.model.sbml; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.Assert.*; import java.io.FileNotFoundException; import java.util.HashSet; import java.util.Set; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.junit.Test; import lcsb.mapviewer.commands.CreateHierarchyCommand; @@ -18,13 +16,8 @@ import lcsb.mapviewer.converter.ConverterParams; import lcsb.mapviewer.converter.InvalidInputDataExecption; import lcsb.mapviewer.model.map.compartment.Compartment; import lcsb.mapviewer.model.map.model.Model; -import lcsb.mapviewer.model.map.reaction.Reactant; -import lcsb.mapviewer.model.map.reaction.Reaction; -import lcsb.mapviewer.model.map.reaction.ReactionNode; -import lcsb.mapviewer.model.map.species.Element; -import lcsb.mapviewer.model.map.species.Gene; -import lcsb.mapviewer.model.map.species.GenericProtein; -import lcsb.mapviewer.model.map.species.Species; +import lcsb.mapviewer.model.map.reaction.*; +import lcsb.mapviewer.model.map.species.*; public class SbmlParserTest extends SbmlTestFunctions { Logger logger = LogManager.getLogger(SbmlParserTest.class); @@ -190,36 +183,26 @@ public class SbmlParserTest extends SbmlTestFunctions { @Test public void testCyclicComplexes() throws Exception { - try { - Model model = parser.createModel(new ConverterParams().filename("testFiles/cyclic_complex.xml")); + Model model = parser.createModel(new ConverterParams().filename("testFiles/cyclic_complex.xml")); - new CreateHierarchyCommand(model, 8, 80).execute(); - - for (Species species : model.getSpeciesList()) { - Set<Element> parents = new HashSet<>(); - while (species.getComplex() != null) { - assertFalse("Cyclic nesting", parents.contains(species.getComplex())); - species = species.getComplex(); - parents.add(species); - } + new CreateHierarchyCommand(model, 8, 80).execute(); + for (Species species : model.getSpeciesList()) { + Set<Element> parents = new HashSet<>(); + while (species.getComplex() != null) { + assertFalse("Cyclic nesting", parents.contains(species.getComplex())); + species = species.getComplex(); + parents.add(species); } - } catch (Exception e) { - e.printStackTrace(); - throw e; + } } @Test public void testCyclicComplsexes() throws Exception { - try { - Model model = parser - .createModel(new ConverterParams().filename("testFiles/reaction_with_species_used_twice.xml")); - assertEquals(1, model.getReactions().size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Model model = parser + .createModel(new ConverterParams().filename("testFiles/reaction_with_species_used_twice.xml")); + assertEquals(1, model.getReactions().size()); } @Test @@ -234,17 +217,12 @@ public class SbmlParserTest extends SbmlTestFunctions { @Test public void testParseProblematicLayout() throws Exception { - try { - Model model = parser - .createModel(new ConverterParams().filename("testFiles/small/problematic_layout.xml")); - Reaction reaction = model.getReactions().iterator().next(); - Reactant reactant = reaction.getReactants().get(0); - assertEquals("Reactant line should start at position 120, 40", 0, - reactant.getLine().getBeginPoint().distance(120, 40), Configuration.EPSILON); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Model model = parser + .createModel(new ConverterParams().filename("testFiles/small/problematic_layout.xml")); + Reaction reaction = model.getReactions().iterator().next(); + Reactant reactant = reaction.getReactants().get(0); + assertEquals("Reactant line should start at position 120, 40", 0, + reactant.getLine().getBeginPoint().distance(120, 40), Configuration.EPSILON); } } diff --git a/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/SbmlTestFunctions.java b/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/SbmlTestFunctions.java index 8fb0fd6f0fea6ccaa74c6da630014987054ad0cd..06f0468308eb578218cbfd46d34788e75b4d2522 100644 --- a/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/SbmlTestFunctions.java +++ b/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/SbmlTestFunctions.java @@ -2,35 +2,33 @@ package lcsb.mapviewer.converter.model.sbml; import java.awt.Desktop; import java.awt.geom.Point2D; -import java.io.ByteArrayInputStream; -import java.io.File; -import java.io.InputStream; +import java.io.*; import java.nio.file.Files; import java.util.List; import org.apache.log4j.Logger; import org.apache.logging.log4j.core.LogEvent; -import org.junit.After; -import org.junit.Before; +import org.junit.*; import lcsb.mapviewer.common.MinervaLoggerAppender; +import lcsb.mapviewer.common.UnitTestFailedWatcher; import lcsb.mapviewer.converter.ConverterParams; -import lcsb.mapviewer.converter.graphics.AbstractImageGenerator; -import lcsb.mapviewer.converter.graphics.NormalImageGenerator; -import lcsb.mapviewer.converter.graphics.PngImageGenerator; +import lcsb.mapviewer.converter.graphics.*; import lcsb.mapviewer.converter.model.celldesigner.CellDesignerXmlParser; import lcsb.mapviewer.model.graphics.PolylineData; import lcsb.mapviewer.model.map.BioEntity; import lcsb.mapviewer.model.map.compartment.Compartment; import lcsb.mapviewer.model.map.model.Model; -import lcsb.mapviewer.model.map.reaction.Product; -import lcsb.mapviewer.model.map.reaction.Reactant; -import lcsb.mapviewer.model.map.reaction.Reaction; +import lcsb.mapviewer.model.map.reaction.*; import lcsb.mapviewer.model.map.reaction.type.StateTransitionReaction; import lcsb.mapviewer.model.map.species.Element; import lcsb.mapviewer.model.map.species.GenericProtein; public class SbmlTestFunctions { + + @Rule + public UnitTestFailedWatcher unitTestFailedWatcher = new UnitTestFailedWatcher(); + @SuppressWarnings("unused") private Logger logger = Logger.getLogger(SbmlTestFunctions.class); diff --git a/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/reaction/SbmlReactionParserExtractCurveTest.java b/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/reaction/SbmlReactionParserExtractCurveTest.java index 2c357c664b253f4d3e72e27fd2f46ff06dbaff2d..2294c84bce0317e5b94eaa6097388a5309b71d68 100644 --- a/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/reaction/SbmlReactionParserExtractCurveTest.java +++ b/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/reaction/SbmlReactionParserExtractCurveTest.java @@ -1,8 +1,6 @@ package lcsb.mapviewer.converter.model.sbml.reaction; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.Assert.*; import java.io.IOException; import java.util.ArrayList; @@ -10,26 +8,17 @@ import java.util.Collection; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; import org.sbml.jsbml.Model; -import org.sbml.jsbml.ext.layout.Curve; -import org.sbml.jsbml.ext.layout.LineSegment; -import org.sbml.jsbml.ext.layout.Point; -import org.sbml.jsbml.ext.layout.ReactionGlyph; +import org.sbml.jsbml.ext.layout.*; import lcsb.mapviewer.common.Configuration; import lcsb.mapviewer.converter.model.sbml.SbmlTestFunctions; import lcsb.mapviewer.model.graphics.PolylineData; -import lcsb.mapviewer.model.map.reaction.AndOperator; -import lcsb.mapviewer.model.map.reaction.Product; -import lcsb.mapviewer.model.map.reaction.Reactant; -import lcsb.mapviewer.model.map.reaction.Reaction; -import lcsb.mapviewer.model.map.reaction.SplitOperator; +import lcsb.mapviewer.model.map.reaction.*; @RunWith(Parameterized.class) public class SbmlReactionParserExtractCurveTest extends SbmlTestFunctions { @@ -92,101 +81,78 @@ public class SbmlReactionParserExtractCurveTest extends SbmlTestFunctions { @Test public void testCenterLine() throws Exception { - try { - Reaction reaction = createReaction(createProtein(), createProtein()); - - PolylineData line = sbmlReactionParser.extractCurve(glyph, reaction, null); - assertNotNull("Extracted line cannot be null", line); - assertEquals(length, line.length(), Configuration.EPSILON); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Reaction reaction = createReaction(createProtein(), createProtein()); + + PolylineData line = sbmlReactionParser.extractCurve(glyph, reaction, null); + assertNotNull("Extracted line cannot be null", line); + assertEquals(length, line.length(), Configuration.EPSILON); } @Test public void testCenterLineWithInputOperator() throws Exception { - try { - Reaction reaction = createReaction(createProtein(), createProtein()); - reaction.addReactant(new Reactant(createProtein())); - - PolylineData centerLine = sbmlReactionParser.extractCurve(glyph, reaction, null); - assertNotNull("Extracted center line cannot be null", centerLine); - if (length > 0) { - assertTrue(centerLine.length() > 0); - } - - PolylineData inputLine = sbmlReactionParser.extractCurve(glyph, reaction, AndOperator.class); - assertNotNull("Extracted input line cannot be null", inputLine); - if (length > 0) { - assertTrue(inputLine.length() > 0); - } + Reaction reaction = createReaction(createProtein(), createProtein()); + reaction.addReactant(new Reactant(createProtein())); - assertEquals(length, inputLine.length() + centerLine.length(), Configuration.EPSILON); + PolylineData centerLine = sbmlReactionParser.extractCurve(glyph, reaction, null); + assertNotNull("Extracted center line cannot be null", centerLine); + if (length > 0) { + assertTrue(centerLine.length() > 0); + } - } catch (Exception e) { - e.printStackTrace(); - throw e; + PolylineData inputLine = sbmlReactionParser.extractCurve(glyph, reaction, AndOperator.class); + assertNotNull("Extracted input line cannot be null", inputLine); + if (length > 0) { + assertTrue(inputLine.length() > 0); } + + assertEquals(length, inputLine.length() + centerLine.length(), Configuration.EPSILON); } @Test public void testCenterLineWithOutputOperator() throws Exception { - try { - Reaction reaction = createReaction(createProtein(), createProtein()); - reaction.addProduct(new Product(createProtein())); - - PolylineData centerLine = sbmlReactionParser.extractCurve(glyph, reaction, null); - assertNotNull("Extracted center line cannot be null", centerLine); - if (length > 0) { - assertTrue(centerLine.length() > 0); - } - - PolylineData outputLine = sbmlReactionParser.extractCurve(glyph, reaction, SplitOperator.class); - assertNotNull("Extracted output line cannot be null", outputLine); - if (length > 0) { - assertTrue(outputLine.length() > 0); - } + Reaction reaction = createReaction(createProtein(), createProtein()); + reaction.addProduct(new Product(createProtein())); - assertEquals(length, outputLine.length() + centerLine.length(), Configuration.EPSILON); + PolylineData centerLine = sbmlReactionParser.extractCurve(glyph, reaction, null); + assertNotNull("Extracted center line cannot be null", centerLine); + if (length > 0) { + assertTrue(centerLine.length() > 0); + } - } catch (Exception e) { - e.printStackTrace(); - throw e; + PolylineData outputLine = sbmlReactionParser.extractCurve(glyph, reaction, SplitOperator.class); + assertNotNull("Extracted output line cannot be null", outputLine); + if (length > 0) { + assertTrue(outputLine.length() > 0); } + + assertEquals(length, outputLine.length() + centerLine.length(), Configuration.EPSILON); } @Test public void testCenterLineWithInputAndOutputOperator() throws Exception { - try { - Reaction reaction = createReaction(createProtein(), createProtein()); - reaction.addProduct(new Product(createProtein())); - reaction.addReactant(new Reactant(createProtein())); - - PolylineData centerLine = sbmlReactionParser.extractCurve(glyph, reaction, null); - assertNotNull("Extracted center line cannot be null", centerLine); - if (length > 0) { - assertTrue(centerLine.length() > 0); - } - - PolylineData inputLine = sbmlReactionParser.extractCurve(glyph, reaction, AndOperator.class); - assertNotNull("Extracted input line cannot be null", inputLine); - if (length > 0) { - assertTrue(inputLine.length() > 0); - } - - PolylineData outputLine = sbmlReactionParser.extractCurve(glyph, reaction, SplitOperator.class); - assertNotNull("Extracted output line cannot be null", outputLine); - if (length > 0) { - assertTrue(outputLine.length() > 0); - } + Reaction reaction = createReaction(createProtein(), createProtein()); + reaction.addProduct(new Product(createProtein())); + reaction.addReactant(new Reactant(createProtein())); + + PolylineData centerLine = sbmlReactionParser.extractCurve(glyph, reaction, null); + assertNotNull("Extracted center line cannot be null", centerLine); + if (length > 0) { + assertTrue(centerLine.length() > 0); + } - assertEquals(length, outputLine.length() + inputLine.length() + centerLine.length(), Configuration.EPSILON); + PolylineData inputLine = sbmlReactionParser.extractCurve(glyph, reaction, AndOperator.class); + assertNotNull("Extracted input line cannot be null", inputLine); + if (length > 0) { + assertTrue(inputLine.length() > 0); + } - } catch (Exception e) { - e.printStackTrace(); - throw e; + PolylineData outputLine = sbmlReactionParser.extractCurve(glyph, reaction, SplitOperator.class); + assertNotNull("Extracted output line cannot be null", outputLine); + if (length > 0) { + assertTrue(outputLine.length() > 0); } + + assertEquals(length, outputLine.length() + inputLine.length() + centerLine.length(), Configuration.EPSILON); } } diff --git a/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/reaction/SbmlReactionParserTest.java b/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/reaction/SbmlReactionParserTest.java index 9a7993b4618abcf16a25a907542e947dc866fd6c..0fa97e0c4c330a620a8e316859f7e51c27f9b1b6 100644 --- a/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/reaction/SbmlReactionParserTest.java +++ b/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/reaction/SbmlReactionParserTest.java @@ -1,21 +1,13 @@ package lcsb.mapviewer.converter.model.sbml.reaction; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.Assert.*; import java.io.FileNotFoundException; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.junit.Test; -import org.sbml.jsbml.ext.layout.BoundingBox; -import org.sbml.jsbml.ext.layout.Curve; -import org.sbml.jsbml.ext.layout.CurveSegment; -import org.sbml.jsbml.ext.layout.Dimensions; -import org.sbml.jsbml.ext.layout.LineSegment; -import org.sbml.jsbml.ext.layout.Point; -import org.sbml.jsbml.ext.layout.ReactionGlyph; +import org.sbml.jsbml.ext.layout.*; import lcsb.mapviewer.common.Configuration; import lcsb.mapviewer.converter.ConverterParams; @@ -24,24 +16,9 @@ import lcsb.mapviewer.converter.model.sbml.SbmlParser; import lcsb.mapviewer.converter.model.sbml.SbmlTestFunctions; import lcsb.mapviewer.model.map.model.Model; import lcsb.mapviewer.model.map.model.ModelFullIndexed; -import lcsb.mapviewer.model.map.modifier.Catalysis; -import lcsb.mapviewer.model.map.modifier.Inhibition; -import lcsb.mapviewer.model.map.modifier.UnknownCatalysis; -import lcsb.mapviewer.model.map.modifier.UnknownInhibition; +import lcsb.mapviewer.model.map.modifier.*; import lcsb.mapviewer.model.map.reaction.Reaction; -import lcsb.mapviewer.model.map.reaction.type.DissociationReaction; -import lcsb.mapviewer.model.map.reaction.type.HeterodimerAssociationReaction; -import lcsb.mapviewer.model.map.reaction.type.KnownTransitionOmittedReaction; -import lcsb.mapviewer.model.map.reaction.type.NegativeInfluenceReaction; -import lcsb.mapviewer.model.map.reaction.type.PositiveInfluenceReaction; -import lcsb.mapviewer.model.map.reaction.type.StateTransitionReaction; -import lcsb.mapviewer.model.map.reaction.type.TranscriptionReaction; -import lcsb.mapviewer.model.map.reaction.type.TranslationReaction; -import lcsb.mapviewer.model.map.reaction.type.TransportReaction; -import lcsb.mapviewer.model.map.reaction.type.TruncationReaction; -import lcsb.mapviewer.model.map.reaction.type.UnknownNegativeInfluenceReaction; -import lcsb.mapviewer.model.map.reaction.type.UnknownPositiveInfluenceReaction; -import lcsb.mapviewer.model.map.reaction.type.UnknownTransitionReaction; +import lcsb.mapviewer.model.map.reaction.type.*; import lcsb.mapviewer.model.map.species.GenericProtein; public class SbmlReactionParserTest extends SbmlTestFunctions { @@ -140,17 +117,12 @@ public class SbmlReactionParserTest extends SbmlTestFunctions { @Test public void testParseHeterodimerAssociationWithSingleReactant() throws Exception { - try { - Model model = parser - .createModel(new ConverterParams() - .filename("testFiles/small/reaction/heterodimer_association_with_single_reactant.xml")); - Reaction reaction = model.getReactions().iterator().next(); - assertNotNull(reaction); - assertTrue(reaction instanceof Reaction); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Model model = parser + .createModel(new ConverterParams() + .filename("testFiles/small/reaction/heterodimer_association_with_single_reactant.xml")); + Reaction reaction = model.getReactions().iterator().next(); + assertNotNull(reaction); + assertTrue(reaction instanceof Reaction); } @Test @@ -205,163 +177,112 @@ public class SbmlReactionParserTest extends SbmlTestFunctions { @Test public void testParseReactionWithoutReactant() throws Exception { - try { - Model model = parser - .createModel(new ConverterParams().filename("testFiles/small/reaction/reaction_without_reactant.xml")); - Reaction reaction = model.getReactions().iterator().next(); - assertNotNull(reaction); - assertTrue(reaction instanceof Reaction); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Model model = parser + .createModel(new ConverterParams().filename("testFiles/small/reaction/reaction_without_reactant.xml")); + Reaction reaction = model.getReactions().iterator().next(); + assertNotNull(reaction); + assertTrue(reaction instanceof Reaction); } @Test public void testParseReactionWithoutProduct() throws Exception { - try { - Model model = parser - .createModel(new ConverterParams().filename("testFiles/small/reaction/reaction_without_product.xml")); - Reaction reaction = model.getReactions().iterator().next(); - assertNotNull(reaction); - assertTrue(reaction instanceof Reaction); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Model model = parser + .createModel(new ConverterParams().filename("testFiles/small/reaction/reaction_without_product.xml")); + Reaction reaction = model.getReactions().iterator().next(); + assertNotNull(reaction); + assertTrue(reaction instanceof Reaction); } @Test public void testParseReactionKineticsWithDefaultCompartment() throws Exception { - try { - Model model = parser - .createModel(new ConverterParams() - .filename("testFiles/small/reaction/reaction_with_kinetics_including_default_compartment.xml")); - Reaction reaction = model.getReactions().iterator().next(); - assertNotNull(reaction); - assertTrue(reaction instanceof Reaction); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Model model = parser + .createModel(new ConverterParams() + .filename("testFiles/small/reaction/reaction_with_kinetics_including_default_compartment.xml")); + Reaction reaction = model.getReactions().iterator().next(); + assertNotNull(reaction); + assertTrue(reaction instanceof Reaction); } @Test public void testParseReactionWithEmptyKinetics() throws Exception { - try { - Model model = parser - .createModel(new ConverterParams() - .filename("testFiles/small/reaction/reaction_with_empty_kinetics.xml")); - Reaction reaction = model.getReactions().iterator().next(); - assertNotNull(reaction); - assertTrue(reaction instanceof Reaction); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Model model = parser + .createModel(new ConverterParams() + .filename("testFiles/small/reaction/reaction_with_empty_kinetics.xml")); + Reaction reaction = model.getReactions().iterator().next(); + assertNotNull(reaction); + assertTrue(reaction instanceof Reaction); } @Test public void testParseReactionWithProductWithoutLayout() throws Exception { - try { - Model model = parser - .createModel(new ConverterParams().filename("testFiles/small/reaction/product_without_layout.xml")); - Reaction reaction = model.getReactions().iterator().next(); - assertNotNull(reaction); - assertTrue(reaction instanceof Reaction); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Model model = parser + .createModel(new ConverterParams().filename("testFiles/small/reaction/product_without_layout.xml")); + Reaction reaction = model.getReactions().iterator().next(); + assertNotNull(reaction); + assertTrue(reaction instanceof Reaction); } @Test public void testParseReactionWithReactantWithoutLayout() throws Exception { - try { - Model model = parser - .createModel(new ConverterParams().filename("testFiles/small/reaction/reactant_without_layout.xml")); - Reaction reaction = model.getReactions().iterator().next(); - assertNotNull(reaction); - assertTrue(reaction instanceof Reaction); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Model model = parser + .createModel(new ConverterParams().filename("testFiles/small/reaction/reactant_without_layout.xml")); + Reaction reaction = model.getReactions().iterator().next(); + assertNotNull(reaction); + assertTrue(reaction instanceof Reaction); } @Test public void testParseReactionWithZIndex() throws Exception { - try { - Model model = new ModelFullIndexed(null); - GenericProtein p1 = createProtein(); - GenericProtein p2 = createProtein(); - Reaction reaction = createReaction(p1, p2); - model.addElement(p1); - model.addElement(p2); - model.addReaction(reaction); - Model model2 = getModelAfterSerializing(model); - - assertEquals(reaction.getZ(), model2.getReactions().iterator().next().getZ()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Model model = new ModelFullIndexed(null); + GenericProtein p1 = createProtein(); + GenericProtein p2 = createProtein(); + Reaction reaction = createReaction(p1, p2); + model.addElement(p1); + model.addElement(p2); + model.addReaction(reaction); + Model model2 = getModelAfterSerializing(model); + + assertEquals(reaction.getZ(), model2.getReactions().iterator().next().getZ()); } @Test public void testGetPointOnSegment() throws Exception { - try { - SbmlReactionParser parser = new SbmlReactionParser(new org.sbml.jsbml.Model(), null, null, null); - CurveSegment segment = new LineSegment(3, 2); - segment.setStart(new Point(12, 2, 0, 3, 2)); - segment.setEnd(new Point(2, 8, 0, 3, 2)); - Point p = parser.getPointOnSegment(segment, 0.4); - - assertEquals(8, p.getX(), Configuration.EPSILON); - assertEquals(4.4, p.getY(), Configuration.EPSILON); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + SbmlReactionParser parser = new SbmlReactionParser(new org.sbml.jsbml.Model(), null, null, null); + CurveSegment segment = new LineSegment(3, 2); + segment.setStart(new Point(12, 2, 0, 3, 2)); + segment.setEnd(new Point(2, 8, 0, 3, 2)); + Point p = parser.getPointOnSegment(segment, 0.4); + + assertEquals(8, p.getX(), Configuration.EPSILON); + assertEquals(4.4, p.getY(), Configuration.EPSILON); } @Test public void testGetCurveFromEmptyBoundingBox() throws Exception { - try { - SbmlReactionParser sbmlReactionParser = new SbmlReactionParser(new org.sbml.jsbml.Model(), null, null, null); - ReactionGlyph glyph = new ReactionGlyph(3, 2); - BoundingBox box = new BoundingBox(3, 2); - box.setPosition(new Point(1, 1, 1, 3, 2)); - box.setDimensions(new Dimensions(3, 2)); - glyph.setBoundingBox(box); - - Curve result = sbmlReactionParser.getCurve(glyph); - assertNotNull(result); - assertEquals(0, result.getCurveSegmentCount()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + SbmlReactionParser sbmlReactionParser = new SbmlReactionParser(new org.sbml.jsbml.Model(), null, null, null); + ReactionGlyph glyph = new ReactionGlyph(3, 2); + BoundingBox box = new BoundingBox(3, 2); + box.setPosition(new Point(1, 1, 1, 3, 2)); + box.setDimensions(new Dimensions(3, 2)); + glyph.setBoundingBox(box); + + Curve result = sbmlReactionParser.getCurve(glyph); + assertNotNull(result); + assertEquals(0, result.getCurveSegmentCount()); } @Test public void testGetCurveFromNonEmptyBoundingBox() throws Exception { - try { - SbmlReactionParser sbmlReactionParser = new SbmlReactionParser(new org.sbml.jsbml.Model(), null, null, null); - ReactionGlyph glyph = new ReactionGlyph(3, 2); - BoundingBox box = new BoundingBox(3, 2); - box.setPosition(new Point(1, 1, 1, 3, 2)); - box.setDimensions(new Dimensions(2, 2, 2, 3, 2)); - glyph.setBoundingBox(box); - - Curve result = sbmlReactionParser.getCurve(glyph); - assertNotNull(result); - assertEquals(1, result.getCurveSegmentCount()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + SbmlReactionParser sbmlReactionParser = new SbmlReactionParser(new org.sbml.jsbml.Model(), null, null, null); + ReactionGlyph glyph = new ReactionGlyph(3, 2); + BoundingBox box = new BoundingBox(3, 2); + box.setPosition(new Point(1, 1, 1, 3, 2)); + box.setDimensions(new Dimensions(2, 2, 2, 3, 2)); + glyph.setBoundingBox(box); + + Curve result = sbmlReactionParser.getCurve(glyph); + assertNotNull(result); + assertEquals(1, result.getCurveSegmentCount()); } } diff --git a/converter/src/test/java/lcsb/mapviewer/converter/ComplexZipConverterTest.java b/converter/src/test/java/lcsb/mapviewer/converter/ComplexZipConverterTest.java index a4b1126f4306344cad147d2ead8b5ba7fb3f3120..aa71186181d1ca6930c05e32cdb918060b617086 100644 --- a/converter/src/test/java/lcsb/mapviewer/converter/ComplexZipConverterTest.java +++ b/converter/src/test/java/lcsb/mapviewer/converter/ComplexZipConverterTest.java @@ -1,20 +1,14 @@ package lcsb.mapviewer.converter; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import java.io.ByteArrayInputStream; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; -import org.apache.logging.log4j.*; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.junit.*; import org.mockito.Mockito; import lcsb.mapviewer.common.exception.InvalidArgumentException; @@ -22,12 +16,10 @@ import lcsb.mapviewer.common.exception.InvalidClassException; import lcsb.mapviewer.converter.zip.LayoutZipEntryFile; import lcsb.mapviewer.converter.zip.ModelZipEntryFile; import lcsb.mapviewer.model.map.layout.Layout; -import lcsb.mapviewer.model.map.model.Model; -import lcsb.mapviewer.model.map.model.ModelSubmodelConnection; -import lcsb.mapviewer.model.map.model.SubmodelType; +import lcsb.mapviewer.model.map.model.*; import lcsb.mapviewer.model.map.species.Element; -public class ComplexZipConverterTest { +public class ComplexZipConverterTest extends ConverterTestFunctions { @SuppressWarnings("unused") private static Logger logger = LogManager.getLogger(ComplexZipConverterTest.class); @@ -40,369 +32,252 @@ public class ComplexZipConverterTest { public void tearDown() throws Exception { } - @Test + @Test(expected = InvalidClassException.class) public void testConstructor() throws Exception { - try { - new ComplexZipConverter(Converter.class); - fail("Exception expected"); - - } catch (InvalidClassException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + new ComplexZipConverter(Converter.class); } @Test public void testConstructor3() throws Exception { - try { - new ComplexZipConverter(MockConverter.class); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - + new ComplexZipConverter(MockConverter.class); } @Test public void testParamsOk() throws Exception { - try { - ComplexZipConverter converter = new ComplexZipConverter(MockConverter.class); - ComplexZipConverterParams params = new ComplexZipConverterParams(); - params.zipFile(new ZipFile("testFiles/complex_model.zip")); - params.entry(new ModelZipEntryFile("main.xml", "main", true, false, null)); - params.entry(new ModelZipEntryFile("s1.xml", "s1", false, false, SubmodelType.DOWNSTREAM_TARGETS)); - params.entry(new ModelZipEntryFile("s2.xml", "s2", false, false, SubmodelType.PATHWAY)); - params.entry(new ModelZipEntryFile("s3.xml", "s3", false, false, SubmodelType.UNKNOWN)); - params.entry(new ModelZipEntryFile("mapping.xml", null, false, true, null)); - Model model = converter.createModel(params); - assertNotNull(model); - assertEquals("main", model.getName()); - assertEquals(3, model.getSubmodelConnections().size()); - - Model s1Model = null; - Model s2Model = null; - Model s3Model = null; - - for (ModelSubmodelConnection submodel : model.getSubmodelConnections()) { - if (submodel.getName().equals("s1")) { - s1Model = submodel.getSubmodel().getModel(); - } - if (submodel.getName().equals("s2")) { - s2Model = submodel.getSubmodel().getModel(); - } - if (submodel.getName().equals("s3")) { - s3Model = submodel.getSubmodel().getModel(); - } + ComplexZipConverter converter = new ComplexZipConverter(MockConverter.class); + ComplexZipConverterParams params = new ComplexZipConverterParams(); + params.zipFile(new ZipFile("testFiles/complex_model.zip")); + params.entry(new ModelZipEntryFile("main.xml", "main", true, false, null)); + params.entry(new ModelZipEntryFile("s1.xml", "s1", false, false, SubmodelType.DOWNSTREAM_TARGETS)); + params.entry(new ModelZipEntryFile("s2.xml", "s2", false, false, SubmodelType.PATHWAY)); + params.entry(new ModelZipEntryFile("s3.xml", "s3", false, false, SubmodelType.UNKNOWN)); + params.entry(new ModelZipEntryFile("mapping.xml", null, false, true, null)); + Model model = converter.createModel(params); + assertNotNull(model); + assertEquals("main", model.getName()); + assertEquals(3, model.getSubmodelConnections().size()); + + Model s1Model = null; + Model s2Model = null; + Model s3Model = null; + + for (ModelSubmodelConnection submodel : model.getSubmodelConnections()) { + if (submodel.getName().equals("s1")) { + s1Model = submodel.getSubmodel().getModel(); + } + if (submodel.getName().equals("s2")) { + s2Model = submodel.getSubmodel().getModel(); + } + if (submodel.getName().equals("s3")) { + s3Model = submodel.getSubmodel().getModel(); } - assertNotNull(s1Model); - assertNotNull(s2Model); - assertNotNull(s3Model); - - Element al1 = model.getElementByElementId("sa1"); - assertNotNull(al1.getSubmodel()); - assertEquals(SubmodelType.DOWNSTREAM_TARGETS, al1.getSubmodel().getType()); - assertEquals(s1Model, al1.getSubmodel().getSubmodel().getModel()); - - Element al2 = model.getElementByElementId("sa2"); - assertNull(al2.getSubmodel()); - - Element al4 = model.getElementByElementId("sa4"); - assertNotNull(al4.getSubmodel()); - assertEquals(SubmodelType.PATHWAY, al4.getSubmodel().getType()); - assertEquals(s2Model, al4.getSubmodel().getSubmodel().getModel()); - - Element s1_al1 = s1Model.getElementByElementId("sa1"); - assertNotNull(s1_al1.getSubmodel()); - assertEquals(SubmodelType.DOWNSTREAM_TARGETS, s1_al1.getSubmodel().getType()); - assertEquals(s3Model, s1_al1.getSubmodel().getSubmodel().getModel()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; } - + assertNotNull(s1Model); + assertNotNull(s2Model); + assertNotNull(s3Model); + + Element al1 = model.getElementByElementId("sa1"); + assertNotNull(al1.getSubmodel()); + assertEquals(SubmodelType.DOWNSTREAM_TARGETS, al1.getSubmodel().getType()); + assertEquals(s1Model, al1.getSubmodel().getSubmodel().getModel()); + + Element al2 = model.getElementByElementId("sa2"); + assertNull(al2.getSubmodel()); + + Element al4 = model.getElementByElementId("sa4"); + assertNotNull(al4.getSubmodel()); + assertEquals(SubmodelType.PATHWAY, al4.getSubmodel().getType()); + assertEquals(s2Model, al4.getSubmodel().getSubmodel().getModel()); + + Element s1_al1 = s1Model.getElementByElementId("sa1"); + assertNotNull(s1_al1.getSubmodel()); + assertEquals(SubmodelType.DOWNSTREAM_TARGETS, s1_al1.getSubmodel().getType()); + assertEquals(s3Model, s1_al1.getSubmodel().getSubmodel().getModel()); } @Test public void testChangeModelZipEntry() throws Exception { - try { - ComplexZipConverter converter = new ComplexZipConverter(MockConverter.class); - ComplexZipConverterParams params = new ComplexZipConverterParams(); - params.zipFile(new ZipFile("testFiles/complex_model.zip")); - params.entry(new ModelZipEntryFile("main.xml", "main", true, false, null)); - params.entry(new ModelZipEntryFile("s1.xml", "s12", false, false, SubmodelType.DOWNSTREAM_TARGETS)); - params.entry(new ModelZipEntryFile("s2.xml", "s2", false, false, SubmodelType.PATHWAY)); - params.entry(new ModelZipEntryFile("s3.xml", "s3", false, false, SubmodelType.UNKNOWN)); - params.entry(new ModelZipEntryFile("mapping.xml", null, false, true, null)); - Model model = converter.createModel(params); - assertNotNull(model); - assertEquals("main", model.getName()); - assertEquals(3, model.getSubmodelConnections().size()); - - Model s1Model = null; - Model s2Model = null; - Model s3Model = null; - - for (ModelSubmodelConnection submodel : model.getSubmodelConnections()) { - if (submodel.getName().equals("s12")) { - s1Model = submodel.getSubmodel().getModel(); - } - if (submodel.getName().equals("s2")) { - s2Model = submodel.getSubmodel().getModel(); - } - if (submodel.getName().equals("s3")) { - s3Model = submodel.getSubmodel().getModel(); - } + ComplexZipConverter converter = new ComplexZipConverter(MockConverter.class); + ComplexZipConverterParams params = new ComplexZipConverterParams(); + params.zipFile(new ZipFile("testFiles/complex_model.zip")); + params.entry(new ModelZipEntryFile("main.xml", "main", true, false, null)); + params.entry(new ModelZipEntryFile("s1.xml", "s12", false, false, SubmodelType.DOWNSTREAM_TARGETS)); + params.entry(new ModelZipEntryFile("s2.xml", "s2", false, false, SubmodelType.PATHWAY)); + params.entry(new ModelZipEntryFile("s3.xml", "s3", false, false, SubmodelType.UNKNOWN)); + params.entry(new ModelZipEntryFile("mapping.xml", null, false, true, null)); + Model model = converter.createModel(params); + assertNotNull(model); + assertEquals("main", model.getName()); + assertEquals(3, model.getSubmodelConnections().size()); + + Model s1Model = null; + Model s2Model = null; + Model s3Model = null; + + for (ModelSubmodelConnection submodel : model.getSubmodelConnections()) { + if (submodel.getName().equals("s12")) { + s1Model = submodel.getSubmodel().getModel(); + } + if (submodel.getName().equals("s2")) { + s2Model = submodel.getSubmodel().getModel(); + } + if (submodel.getName().equals("s3")) { + s3Model = submodel.getSubmodel().getModel(); } - assertNotNull(s1Model); - assertNotNull(s2Model); - assertNotNull(s3Model); - - Element al1 = model.getElementByElementId("sa1"); - assertNotNull(al1.getSubmodel()); - assertEquals(SubmodelType.DOWNSTREAM_TARGETS, al1.getSubmodel().getType()); - assertEquals(s1Model, al1.getSubmodel().getSubmodel().getModel()); - - Element al2 = model.getElementByElementId("sa2"); - assertNull(al2.getSubmodel()); - - Element al4 = model.getElementByElementId("sa4"); - assertNotNull(al4.getSubmodel()); - assertEquals(SubmodelType.PATHWAY, al4.getSubmodel().getType()); - assertEquals(s2Model, al4.getSubmodel().getSubmodel().getModel()); - - Element s1_al1 = s1Model.getElementByElementId("sa1"); - assertNotNull(s1_al1.getSubmodel()); - assertEquals(SubmodelType.DOWNSTREAM_TARGETS, s1_al1.getSubmodel().getType()); - assertEquals(s3Model, s1_al1.getSubmodel().getSubmodel().getModel()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; } - + assertNotNull(s1Model); + assertNotNull(s2Model); + assertNotNull(s3Model); + + Element al1 = model.getElementByElementId("sa1"); + assertNotNull(al1.getSubmodel()); + assertEquals(SubmodelType.DOWNSTREAM_TARGETS, al1.getSubmodel().getType()); + assertEquals(s1Model, al1.getSubmodel().getSubmodel().getModel()); + + Element al2 = model.getElementByElementId("sa2"); + assertNull(al2.getSubmodel()); + + Element al4 = model.getElementByElementId("sa4"); + assertNotNull(al4.getSubmodel()); + assertEquals(SubmodelType.PATHWAY, al4.getSubmodel().getType()); + assertEquals(s2Model, al4.getSubmodel().getSubmodel().getModel()); + + Element s1_al1 = s1Model.getElementByElementId("sa1"); + assertNotNull(s1_al1.getSubmodel()); + assertEquals(SubmodelType.DOWNSTREAM_TARGETS, s1_al1.getSubmodel().getType()); + assertEquals(s3Model, s1_al1.getSubmodel().getSubmodel().getModel()); } - @Test + @Test(expected = InvalidArgumentException.class) public void testParamsMissing() throws Exception { - try { - ComplexZipConverter converter = new ComplexZipConverter(MockConverter.class); - ComplexZipConverterParams params = new ComplexZipConverterParams(); - params.zipFile(new ZipFile("testFiles/complex_model.zip")); - params.entry(new ModelZipEntryFile("main.xml", "main", true, false, null)); - params.entry(new ModelZipEntryFile("s1.xml", "s1", false, false, SubmodelType.DOWNSTREAM_TARGETS)); - params.entry(new ModelZipEntryFile("s3.xml", "s3", false, false, SubmodelType.UNKNOWN)); - params.entry(new ModelZipEntryFile("mapping.xml", null, false, true, null)); - try { - converter.createModel(params); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - - } - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - + ComplexZipConverter converter = new ComplexZipConverter(MockConverter.class); + ComplexZipConverterParams params = new ComplexZipConverterParams(); + params.zipFile(new ZipFile("testFiles/complex_model.zip")); + params.entry(new ModelZipEntryFile("main.xml", "main", true, false, null)); + params.entry(new ModelZipEntryFile("s1.xml", "s1", false, false, SubmodelType.DOWNSTREAM_TARGETS)); + params.entry(new ModelZipEntryFile("s3.xml", "s3", false, false, SubmodelType.UNKNOWN)); + params.entry(new ModelZipEntryFile("mapping.xml", null, false, true, null)); + converter.createModel(params); } - @Test + @Test(expected = InvalidArgumentException.class) public void testParamsInvalid1() throws Exception { - try { - // two mains - ComplexZipConverter converter = new ComplexZipConverter(MockConverter.class); - ComplexZipConverterParams params = new ComplexZipConverterParams(); - params.zipFile(new ZipFile("testFiles/complex_model.zip")); - params.entry(new ModelZipEntryFile("main.xml", "main", true, false, null)); - params.entry(new ModelZipEntryFile("s1.xml", "s1", true, false, SubmodelType.DOWNSTREAM_TARGETS)); - params.entry(new ModelZipEntryFile("s2.xml", "s2", false, false, SubmodelType.PATHWAY)); - params.entry(new ModelZipEntryFile("s3.xml", "s3", false, false, SubmodelType.UNKNOWN)); - params.entry(new ModelZipEntryFile("mapping.xml", null, false, true, null)); - try { - converter.createModel(params); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - - } - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - + // two mains + ComplexZipConverter converter = new ComplexZipConverter(MockConverter.class); + ComplexZipConverterParams params = new ComplexZipConverterParams(); + params.zipFile(new ZipFile("testFiles/complex_model.zip")); + params.entry(new ModelZipEntryFile("main.xml", "main", true, false, null)); + params.entry(new ModelZipEntryFile("s1.xml", "s1", true, false, SubmodelType.DOWNSTREAM_TARGETS)); + params.entry(new ModelZipEntryFile("s2.xml", "s2", false, false, SubmodelType.PATHWAY)); + params.entry(new ModelZipEntryFile("s3.xml", "s3", false, false, SubmodelType.UNKNOWN)); + params.entry(new ModelZipEntryFile("mapping.xml", null, false, true, null)); + converter.createModel(params); } - @Test + @Test(expected = InvalidArgumentException.class) public void testParamsInvalid2() throws Exception { - try { - // zero mains - ComplexZipConverter converter = new ComplexZipConverter(MockConverter.class); - ComplexZipConverterParams params = new ComplexZipConverterParams(); - params.zipFile(new ZipFile("testFiles/complex_model.zip")); - params.entry(new ModelZipEntryFile("main.xml", "main", false, false, null)); - params.entry(new ModelZipEntryFile("s1.xml", "s1", false, false, SubmodelType.DOWNSTREAM_TARGETS)); - params.entry(new ModelZipEntryFile("s2.xml", "s2", false, false, SubmodelType.PATHWAY)); - params.entry(new ModelZipEntryFile("s3.xml", "s3", false, false, SubmodelType.UNKNOWN)); - params.entry(new ModelZipEntryFile("mapping.xml", null, false, true, null)); - try { - converter.createModel(params); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - - } - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - + // zero mains + ComplexZipConverter converter = new ComplexZipConverter(MockConverter.class); + ComplexZipConverterParams params = new ComplexZipConverterParams(); + params.zipFile(new ZipFile("testFiles/complex_model.zip")); + params.entry(new ModelZipEntryFile("main.xml", "main", false, false, null)); + params.entry(new ModelZipEntryFile("s1.xml", "s1", false, false, SubmodelType.DOWNSTREAM_TARGETS)); + params.entry(new ModelZipEntryFile("s2.xml", "s2", false, false, SubmodelType.PATHWAY)); + params.entry(new ModelZipEntryFile("s3.xml", "s3", false, false, SubmodelType.UNKNOWN)); + params.entry(new ModelZipEntryFile("mapping.xml", null, false, true, null)); + converter.createModel(params); } - @Test + @Test(expected = InvalidArgumentException.class) public void testParamsInvalid3() throws Exception { - try { - // two mappings - ComplexZipConverter converter = new ComplexZipConverter(MockConverter.class); - ComplexZipConverterParams params = new ComplexZipConverterParams(); - params.zipFile(new ZipFile("testFiles/complex_model.zip")); - params.entry(new ModelZipEntryFile("main.xml", "main", true, false, null)); - params.entry(new ModelZipEntryFile("s1.xml", "s1", false, true, SubmodelType.DOWNSTREAM_TARGETS)); - params.entry(new ModelZipEntryFile("s2.xml", "s2", false, false, SubmodelType.PATHWAY)); - params.entry(new ModelZipEntryFile("s3.xml", "s3", false, false, SubmodelType.UNKNOWN)); - params.entry(new ModelZipEntryFile("mapping.xml", null, false, true, null)); - try { - converter.createModel(params); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - - } - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - + // two mappings + ComplexZipConverter converter = new ComplexZipConverter(MockConverter.class); + ComplexZipConverterParams params = new ComplexZipConverterParams(); + params.zipFile(new ZipFile("testFiles/complex_model.zip")); + params.entry(new ModelZipEntryFile("main.xml", "main", true, false, null)); + params.entry(new ModelZipEntryFile("s1.xml", "s1", false, true, SubmodelType.DOWNSTREAM_TARGETS)); + params.entry(new ModelZipEntryFile("s2.xml", "s2", false, false, SubmodelType.PATHWAY)); + params.entry(new ModelZipEntryFile("s3.xml", "s3", false, false, SubmodelType.UNKNOWN)); + params.entry(new ModelZipEntryFile("mapping.xml", null, false, true, null)); + converter.createModel(params); } @Test public void testParamsMissingMapping() throws Exception { - try { - // zero mappings (should be ok) - ComplexZipConverter converter = new ComplexZipConverter(MockConverter.class); - ComplexZipConverterParams params = new ComplexZipConverterParams(); - params.zipFile(new ZipFile("testFiles/complex_model.zip")); - params.entry(new ModelZipEntryFile("main.xml", "main", true, false, null)); - params.entry(new ModelZipEntryFile("s1.xml", "s1", false, false, SubmodelType.DOWNSTREAM_TARGETS)); - params.entry(new ModelZipEntryFile("s2.xml", "s2", false, false, SubmodelType.PATHWAY)); - params.entry(new ModelZipEntryFile("s3.xml", "s3", false, false, SubmodelType.UNKNOWN)); - params.entry(new ModelZipEntryFile("mapping.xml", "", false, false, null)); - Model model = converter.createModel(params); - - assertNotNull(model); - - assertEquals(4, model.getSubmodelConnections().size()); - - for (ModelSubmodelConnection submodel : model.getSubmodelConnections()) { - if (submodel.getName().equals("s1")) { - assertEquals(SubmodelType.DOWNSTREAM_TARGETS, submodel.getType()); - } else if (submodel.getName().equals("s2")) { - assertEquals(SubmodelType.PATHWAY, submodel.getType()); - } else if (submodel.getName().equals("s3")) { - assertEquals(SubmodelType.UNKNOWN, submodel.getType()); - } else if (submodel.getName().equals("mapping")) { - assertEquals(SubmodelType.UNKNOWN, submodel.getType()); - } + // zero mappings (should be ok) + ComplexZipConverter converter = new ComplexZipConverter(MockConverter.class); + ComplexZipConverterParams params = new ComplexZipConverterParams(); + params.zipFile(new ZipFile("testFiles/complex_model.zip")); + params.entry(new ModelZipEntryFile("main.xml", "main", true, false, null)); + params.entry(new ModelZipEntryFile("s1.xml", "s1", false, false, SubmodelType.DOWNSTREAM_TARGETS)); + params.entry(new ModelZipEntryFile("s2.xml", "s2", false, false, SubmodelType.PATHWAY)); + params.entry(new ModelZipEntryFile("s3.xml", "s3", false, false, SubmodelType.UNKNOWN)); + params.entry(new ModelZipEntryFile("mapping.xml", "", false, false, null)); + Model model = converter.createModel(params); + + assertNotNull(model); + + assertEquals(4, model.getSubmodelConnections().size()); + + for (ModelSubmodelConnection submodel : model.getSubmodelConnections()) { + if (submodel.getName().equals("s1")) { + assertEquals(SubmodelType.DOWNSTREAM_TARGETS, submodel.getType()); + } else if (submodel.getName().equals("s2")) { + assertEquals(SubmodelType.PATHWAY, submodel.getType()); + } else if (submodel.getName().equals("s3")) { + assertEquals(SubmodelType.UNKNOWN, submodel.getType()); + } else if (submodel.getName().equals("mapping")) { + assertEquals(SubmodelType.UNKNOWN, submodel.getType()); } - } catch (Exception e) { - e.printStackTrace(); - throw e; } - } - @Test + @Test(expected = InvalidArgumentException.class) public void testTooManyParams() throws Exception { - try { - // zero mappings (should be ok) - ComplexZipConverter converter = new ComplexZipConverter(MockConverter.class); - ComplexZipConverterParams params = new ComplexZipConverterParams(); - params.zipFile(new ZipFile("testFiles/complex_model.zip")); - params.entry(new ModelZipEntryFile("main.xml", "main", true, false, null)); - params.entry(new ModelZipEntryFile("s1.xml", "s1", false, false, SubmodelType.DOWNSTREAM_TARGETS)); - params.entry(new ModelZipEntryFile("s2.xml", "s2", false, false, SubmodelType.PATHWAY)); - params.entry(new ModelZipEntryFile("s3.xml", "s3", false, false, SubmodelType.UNKNOWN)); - params.entry(new ModelZipEntryFile("mapping.xml", "", false, false, null)); - params.entry(new ModelZipEntryFile("blabla.xml", "s3", false, false, SubmodelType.UNKNOWN)); - try { - converter.createModel(params); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - - } - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + // zero mappings (should be ok) + ComplexZipConverter converter = new ComplexZipConverter(MockConverter.class); + ComplexZipConverterParams params = new ComplexZipConverterParams(); + params.zipFile(new ZipFile("testFiles/complex_model.zip")); + params.entry(new ModelZipEntryFile("main.xml", "main", true, false, null)); + params.entry(new ModelZipEntryFile("s1.xml", "s1", false, false, SubmodelType.DOWNSTREAM_TARGETS)); + params.entry(new ModelZipEntryFile("s2.xml", "s2", false, false, SubmodelType.PATHWAY)); + params.entry(new ModelZipEntryFile("s3.xml", "s3", false, false, SubmodelType.UNKNOWN)); + params.entry(new ModelZipEntryFile("mapping.xml", "", false, false, null)); + params.entry(new ModelZipEntryFile("blabla.xml", "s3", false, false, SubmodelType.UNKNOWN)); + converter.createModel(params); } - @Test + @Test(expected = InvalidArgumentException.class) public void testInvalidMappingFile() throws Exception { - try { - // zero mappings (should be ok) - ComplexZipConverter converter = new ComplexZipConverter(MockConverter.class); - ComplexZipConverterParams params = new ComplexZipConverterParams(); - params.zipFile(new ZipFile("testFiles/invalid_mapping.zip")); - params.entry(new ModelZipEntryFile("main.xml", "main", true, false, null)); - params.entry(new ModelZipEntryFile("mapping.xml", null, false, true, null)); - try { - converter.createModel(params); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - - } - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + // zero mappings (should be ok) + ComplexZipConverter converter = new ComplexZipConverter(MockConverter.class); + ComplexZipConverterParams params = new ComplexZipConverterParams(); + params.zipFile(new ZipFile("testFiles/invalid_mapping.zip")); + params.entry(new ModelZipEntryFile("main.xml", "main", true, false, null)); + params.entry(new ModelZipEntryFile("mapping.xml", null, false, true, null)); + converter.createModel(params); } @Test public void testIsIgnoredFileForMac() throws Exception { - try { - ComplexZipConverter converter = new ComplexZipConverter(MockConverter.class); - assertTrue(converter.isIgnoredFile("__MACOSX/.desc")); - assertTrue(converter.isIgnoredFile(".DS_Store")); - assertTrue(converter.isIgnoredFile("images/.DS_Store")); - assertTrue(converter.isIgnoredFile("layouts/.DS_Store")); - assertTrue(converter.isIgnoredFile("submaps/.DS_Store")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + ComplexZipConverter converter = new ComplexZipConverter(MockConverter.class); + assertTrue(converter.isIgnoredFile("__MACOSX/.desc")); + assertTrue(converter.isIgnoredFile(".DS_Store")); + assertTrue(converter.isIgnoredFile("images/.DS_Store")); + assertTrue(converter.isIgnoredFile("layouts/.DS_Store")); + assertTrue(converter.isIgnoredFile("submaps/.DS_Store")); } @Test public void testIsIgnoredFileForOldMacEntries() throws Exception { - try { - ComplexZipConverter converter = new ComplexZipConverter(MockConverter.class); - assertTrue(converter.isIgnoredFile(".DS_Store/.desc")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + ComplexZipConverter converter = new ComplexZipConverter(MockConverter.class); + assertTrue(converter.isIgnoredFile(".DS_Store/.desc")); } @Test public void testIsIgnoredFileForValidFiles() throws Exception { - try { - ComplexZipConverter converter = new ComplexZipConverter(MockConverter.class); - assertFalse(converter.isIgnoredFile("mapping.xml")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + ComplexZipConverter converter = new ComplexZipConverter(MockConverter.class); + assertFalse(converter.isIgnoredFile("mapping.xml")); } @Test diff --git a/converter/src/test/java/lcsb/mapviewer/converter/ConverterTestFunctions.java b/converter/src/test/java/lcsb/mapviewer/converter/ConverterTestFunctions.java index 038ee2cbed0cd0c7ffede7770cbbefb8e14ab861..15d26751d27e83356df4d278bc99f249dd793065 100644 --- a/converter/src/test/java/lcsb/mapviewer/converter/ConverterTestFunctions.java +++ b/converter/src/test/java/lcsb/mapviewer/converter/ConverterTestFunctions.java @@ -28,18 +28,14 @@ import javax.xml.transform.stream.StreamResult; import org.apache.logging.log4j.*; import org.apache.logging.log4j.core.LogEvent; - -import org.junit.After; -import org.junit.Before; +import org.junit.*; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; import org.xml.sax.SAXException; -import lcsb.mapviewer.common.Configuration; - -import lcsb.mapviewer.common.MinervaLoggerAppender; +import lcsb.mapviewer.common.*; import lcsb.mapviewer.common.exception.InvalidXmlSchemaException; public abstract class ConverterTestFunctions { @@ -49,6 +45,9 @@ public abstract class ConverterTestFunctions { private MinervaLoggerAppender appender; + @Rule + public UnitTestFailedWatcher unitTestFailedWatcher = new UnitTestFailedWatcher(); + @Before public final void _setUp() throws Exception { MinervaLoggerAppender.unregisterLogEventStorage(appender); diff --git a/converter/src/test/java/lcsb/mapviewer/converter/OverviewParserTest.java b/converter/src/test/java/lcsb/mapviewer/converter/OverviewParserTest.java index d2617032b0b3e35bd8af7d016b45bd00e0423055..b1e3e0b55fdc29f45cc537bb8ae5706eccdb9945 100644 --- a/converter/src/test/java/lcsb/mapviewer/converter/OverviewParserTest.java +++ b/converter/src/test/java/lcsb/mapviewer/converter/OverviewParserTest.java @@ -1,37 +1,27 @@ package lcsb.mapviewer.converter; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import java.awt.geom.Point2D; import java.io.File; import java.io.IOException; -import java.util.ArrayList; -import java.util.Enumeration; -import java.util.HashSet; -import java.util.List; -import java.util.Set; +import java.util.*; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import org.apache.commons.io.FileUtils; -import org.apache.logging.log4j.*; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.junit.*; import com.google.common.io.Files; import lcsb.mapviewer.converter.zip.ImageZipEntryFile; -import lcsb.mapviewer.model.map.OverviewImage; -import lcsb.mapviewer.model.map.OverviewLink; -import lcsb.mapviewer.model.map.OverviewModelLink; +import lcsb.mapviewer.model.map.*; import lcsb.mapviewer.model.map.model.Model; import lcsb.mapviewer.model.map.model.ModelFullIndexed; -public class OverviewParserTest { +public class OverviewParserTest extends ConverterTestFunctions { private static final String TEST_FILES_VALID_OVERVIEW_ZIP = "testFiles/valid_overview.zip"; private static final String TEST_FILES_VALID_OVERVIEW_CASE_SENSITIVE_ZIP = "testFiles/valid_overview_case_sensitive.zip"; Logger logger = LogManager.getLogger(OverviewParserTest.class); @@ -47,77 +37,65 @@ public class OverviewParserTest { @Test public void testParsingValidFile() throws Exception { - try { - Set<Model> models = createValidTestMapModel(); - List<ImageZipEntryFile> imageEntries = createImageEntries(TEST_FILES_VALID_OVERVIEW_ZIP); - List<OverviewImage> result = parser.parseOverviewLinks(models, imageEntries, null, - new ZipFile(TEST_FILES_VALID_OVERVIEW_ZIP)); - assertNotNull(result); - assertEquals(1, result.size()); - - OverviewImage img = result.get(0); - - assertEquals("test.png", img.getFilename()); - assertEquals((Integer) 639, img.getHeight()); - assertEquals((Integer) 963, img.getWidth()); - assertEquals(2, img.getLinks().size()); - - OverviewLink link = img.getLinks().get(0); - List<Point2D> polygon = link.getPolygonCoordinates(); - assertEquals(4, polygon.size()); - - assertTrue(link instanceof OverviewModelLink); - - OverviewModelLink mLink = (OverviewModelLink) link; - Model mainModel = models.iterator().next(); - assertEquals(mainModel.getModelData(), mLink.getLinkedModel()); - assertEquals((Integer) 10, mLink.getxCoord()); - assertEquals((Integer) 10, mLink.getyCoord()); - assertEquals((Integer) 3, mLink.getZoomLevel()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Set<Model> models = createValidTestMapModel(); + List<ImageZipEntryFile> imageEntries = createImageEntries(TEST_FILES_VALID_OVERVIEW_ZIP); + List<OverviewImage> result = parser.parseOverviewLinks(models, imageEntries, null, + new ZipFile(TEST_FILES_VALID_OVERVIEW_ZIP)); + assertNotNull(result); + assertEquals(1, result.size()); + + OverviewImage img = result.get(0); + + assertEquals("test.png", img.getFilename()); + assertEquals((Integer) 639, img.getHeight()); + assertEquals((Integer) 963, img.getWidth()); + assertEquals(2, img.getLinks().size()); + + OverviewLink link = img.getLinks().get(0); + List<Point2D> polygon = link.getPolygonCoordinates(); + assertEquals(4, polygon.size()); + + assertTrue(link instanceof OverviewModelLink); + + OverviewModelLink mLink = (OverviewModelLink) link; + Model mainModel = models.iterator().next(); + assertEquals(mainModel.getModelData(), mLink.getLinkedModel()); + assertEquals((Integer) 10, mLink.getxCoord()); + assertEquals((Integer) 10, mLink.getyCoord()); + assertEquals((Integer) 3, mLink.getZoomLevel()); } @Test public void testParsingValidCaseSensitiveFile() throws Exception { - try { - Set<Model> models = createValidTestMapModel(); - List<ImageZipEntryFile> imageEntries = createImageEntries(TEST_FILES_VALID_OVERVIEW_CASE_SENSITIVE_ZIP); - for (ImageZipEntryFile imageZipEntryFile : imageEntries) { - imageZipEntryFile.setFilename(imageZipEntryFile.getFilename().toLowerCase()); - } - List<OverviewImage> result = parser.parseOverviewLinks(models, imageEntries, null, - new ZipFile(TEST_FILES_VALID_OVERVIEW_CASE_SENSITIVE_ZIP)); - assertNotNull(result); - assertEquals(1, result.size()); - - OverviewImage img = result.get(0); - - assertEquals("test.png", img.getFilename()); - assertEquals((Integer) 639, img.getHeight()); - assertEquals((Integer) 963, img.getWidth()); - assertEquals(2, img.getLinks().size()); - - OverviewLink link = img.getLinks().get(0); - List<Point2D> polygon = link.getPolygonCoordinates(); - assertEquals(4, polygon.size()); - - assertTrue(link instanceof OverviewModelLink); - - OverviewModelLink mLink = (OverviewModelLink) link; - Model mainModel = models.iterator().next(); - assertEquals(mainModel.getModelData(), mLink.getLinkedModel()); - assertEquals((Integer) 10, mLink.getxCoord()); - assertEquals((Integer) 10, mLink.getyCoord()); - assertEquals((Integer) 3, mLink.getZoomLevel()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; + Set<Model> models = createValidTestMapModel(); + List<ImageZipEntryFile> imageEntries = createImageEntries(TEST_FILES_VALID_OVERVIEW_CASE_SENSITIVE_ZIP); + for (ImageZipEntryFile imageZipEntryFile : imageEntries) { + imageZipEntryFile.setFilename(imageZipEntryFile.getFilename().toLowerCase()); } + List<OverviewImage> result = parser.parseOverviewLinks(models, imageEntries, null, + new ZipFile(TEST_FILES_VALID_OVERVIEW_CASE_SENSITIVE_ZIP)); + assertNotNull(result); + assertEquals(1, result.size()); + + OverviewImage img = result.get(0); + + assertEquals("test.png", img.getFilename()); + assertEquals((Integer) 639, img.getHeight()); + assertEquals((Integer) 963, img.getWidth()); + assertEquals(2, img.getLinks().size()); + + OverviewLink link = img.getLinks().get(0); + List<Point2D> polygon = link.getPolygonCoordinates(); + assertEquals(4, polygon.size()); + + assertTrue(link instanceof OverviewModelLink); + + OverviewModelLink mLink = (OverviewModelLink) link; + Model mainModel = models.iterator().next(); + assertEquals(mainModel.getModelData(), mLink.getLinkedModel()); + assertEquals((Integer) 10, mLink.getxCoord()); + assertEquals((Integer) 10, mLink.getyCoord()); + assertEquals((Integer) 3, mLink.getZoomLevel()); } private List<ImageZipEntryFile> createImageEntries(String string) throws IOException { @@ -140,74 +118,44 @@ public class OverviewParserTest { @Test public void testParsingValidFile2() throws Exception { - try { - Set<Model> models = createValidTestMapModel(); - - String tmpDir = Files.createTempDir().getAbsolutePath(); + Set<Model> models = createValidTestMapModel(); - List<ImageZipEntryFile> imageEntries = createImageEntries(TEST_FILES_VALID_OVERVIEW_ZIP); - List<OverviewImage> result = parser.parseOverviewLinks(models, imageEntries, tmpDir, - new ZipFile(TEST_FILES_VALID_OVERVIEW_ZIP)); + String tmpDir = Files.createTempDir().getAbsolutePath(); - assertTrue(new File(tmpDir + "/test.png").exists()); + List<ImageZipEntryFile> imageEntries = createImageEntries(TEST_FILES_VALID_OVERVIEW_ZIP); + List<OverviewImage> result = parser.parseOverviewLinks(models, imageEntries, tmpDir, + new ZipFile(TEST_FILES_VALID_OVERVIEW_ZIP)); - assertNotNull(result); - assertEquals(1, result.size()); - OverviewImage img = result.get(0); - assertEquals("test.png", img.getFilename()); + assertTrue(new File(tmpDir + "/test.png").exists()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertNotNull(result); + assertEquals(1, result.size()); + OverviewImage img = result.get(0); + assertEquals("test.png", img.getFilename()); } - @Test + @Test(expected = InvalidOverviewFile.class) public void testParsingInvalidFile1() throws Exception { - try { - List<ImageZipEntryFile> imageEntries = createImageEntries("testFiles/invalid_overview_1.zip"); - Set<Model> models = createValidTestMapModel(); - - parser.parseOverviewLinks(models, imageEntries, null, new ZipFile("testFiles/invalid_overview_1.zip")); - fail("Exception expected"); - } catch (InvalidOverviewFile e) { - assertTrue(e.getMessage().contains("Unknown image filename")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + List<ImageZipEntryFile> imageEntries = createImageEntries("testFiles/invalid_overview_1.zip"); + Set<Model> models = createValidTestMapModel(); + + parser.parseOverviewLinks(models, imageEntries, null, new ZipFile("testFiles/invalid_overview_1.zip")); } - @Test + @Test(expected = InvalidOverviewFile.class) public void testParsingInvalidFile2() throws Exception { - try { - List<ImageZipEntryFile> imageEntries = createImageEntries("testFiles/invalid_overview_2.zip"); - Set<Model> models = createValidTestMapModel(); - - parser.parseOverviewLinks(models, imageEntries, null, new ZipFile("testFiles/invalid_overview_2.zip")); - fail("Exception expected"); - } catch (InvalidOverviewFile e) { - assertTrue(e.getMessage().contains("Unknown model")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + List<ImageZipEntryFile> imageEntries = createImageEntries("testFiles/invalid_overview_2.zip"); + Set<Model> models = createValidTestMapModel(); + + parser.parseOverviewLinks(models, imageEntries, null, new ZipFile("testFiles/invalid_overview_2.zip")); } - @Test + @Test(expected = InvalidOverviewFile.class) public void testParsingInvalidFile3() throws Exception { - try { - List<ImageZipEntryFile> imageEntries = createImageEntries("testFiles/invalid_overview_3.zip"); - Set<Model> models = createValidTestMapModel(); - - parser.parseOverviewLinks(models, imageEntries, null, new ZipFile("testFiles/invalid_overview_3.zip")); - fail("Exception expected"); - } catch (InvalidOverviewFile e) { - assertTrue(e.getMessage().contains("coordinates outside image")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + List<ImageZipEntryFile> imageEntries = createImageEntries("testFiles/invalid_overview_3.zip"); + Set<Model> models = createValidTestMapModel(); + + parser.parseOverviewLinks(models, imageEntries, null, new ZipFile("testFiles/invalid_overview_3.zip")); } private Set<Model> createValidTestMapModel() { @@ -223,83 +171,63 @@ public class OverviewParserTest { * * @throws Exception */ - @Test + @Test(expected = InvalidOverviewFile.class) public void testParseInvalidCoordinates() throws Exception { - try { - String invalidCoordinates = "test.png 10,10 100,10 100,100 10,10 main.xml 10,10 3\n" + - "test.png 10,10 10,400 400,400 400,10 main.xml 10,10 4"; - Set<Model> models = createValidTestMapModel(); - - List<OverviewImage> images = new ArrayList<OverviewImage>(); - OverviewImage oi = new OverviewImage(); - oi.setFilename("test.png"); - oi.setWidth(1000); - oi.setHeight(1000); - images.add(oi); - - parser.processCoordinates(models, images, invalidCoordinates); - - fail("Exception expected"); - } catch (InvalidOverviewFile e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String invalidCoordinates = "test.png 10,10 100,10 100,100 10,10 main.xml 10,10 3\n" + + "test.png 10,10 10,400 400,400 400,10 main.xml 10,10 4"; + Set<Model> models = createValidTestMapModel(); + + List<OverviewImage> images = new ArrayList<OverviewImage>(); + OverviewImage oi = new OverviewImage(); + oi.setFilename("test.png"); + oi.setWidth(1000); + oi.setHeight(1000); + images.add(oi); + + parser.processCoordinates(models, images, invalidCoordinates); } @Test public void testParseValidCoordinates() throws Exception { - try { - String invalidCoordinates = "FILE POLYGON LINK_TARGET MODEL_COORDINATES MODEL_ZOOM_LEVEL LINK_TYPE\n" + - "test.png 10,10 100,10 100,100 10,10 main.xml 10,10 3 MODEL\n" + - "test.png 200,200 200,400 400,400 400,200 main.xml 10,10 4 MODEL"; - Set<Model> models = createValidTestMapModel(); - - List<OverviewImage> images = new ArrayList<OverviewImage>(); - OverviewImage oi = new OverviewImage(); - oi.setFilename("test.png"); - oi.setWidth(1000); - oi.setHeight(1000); - images.add(oi); + String invalidCoordinates = "FILE POLYGON LINK_TARGET MODEL_COORDINATES MODEL_ZOOM_LEVEL LINK_TYPE\n" + + "test.png 10,10 100,10 100,100 10,10 main.xml 10,10 3 MODEL\n" + + "test.png 200,200 200,400 400,400 400,200 main.xml 10,10 4 MODEL"; + Set<Model> models = createValidTestMapModel(); - parser.processCoordinates(models, images, invalidCoordinates); + List<OverviewImage> images = new ArrayList<OverviewImage>(); + OverviewImage oi = new OverviewImage(); + oi.setFilename("test.png"); + oi.setWidth(1000); + oi.setHeight(1000); + images.add(oi); - assertEquals(2, oi.getLinks().size()); + parser.processCoordinates(models, images, invalidCoordinates); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(2, oi.getLinks().size()); } @Test public void testParseValidComplexCoordinates() throws Exception { - try { - String invalidCoordinates = FileUtils.readFileToString(new File("testFiles/coordinates.txt"), "UTF-8"); - Set<Model> models = createValidTestMapModel(); - - List<OverviewImage> images = new ArrayList<>(); - OverviewImage oi = new OverviewImage(); - oi.setFilename("test.png"); - oi.setWidth(1000); - oi.setHeight(1000); - images.add(oi); - - OverviewImage oi2 = new OverviewImage(); - oi2.setFilename("test2.png"); - oi2.setWidth(1000); - oi2.setHeight(1000); - images.add(oi2); - - parser.processCoordinates(models, images, invalidCoordinates); - - assertEquals(2, oi.getLinks().size()); - assertEquals(1, oi2.getLinks().size()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String invalidCoordinates = FileUtils.readFileToString(new File("testFiles/coordinates.txt"), "UTF-8"); + Set<Model> models = createValidTestMapModel(); + + List<OverviewImage> images = new ArrayList<>(); + OverviewImage oi = new OverviewImage(); + oi.setFilename("test.png"); + oi.setWidth(1000); + oi.setHeight(1000); + images.add(oi); + + OverviewImage oi2 = new OverviewImage(); + oi2.setFilename("test2.png"); + oi2.setWidth(1000); + oi2.setHeight(1000); + images.add(oi2); + + parser.processCoordinates(models, images, invalidCoordinates); + + assertEquals(2, oi.getLinks().size()); + assertEquals(1, oi2.getLinks().size()); } } diff --git a/converter/src/test/java/lcsb/mapviewer/converter/ProjectFactoryTest.java b/converter/src/test/java/lcsb/mapviewer/converter/ProjectFactoryTest.java index 058b30e58e613415648c14cbfcb56ea368e1698d..3667f9caf3b8a0e9e1e470639a9e378ce5cd5217 100644 --- a/converter/src/test/java/lcsb/mapviewer/converter/ProjectFactoryTest.java +++ b/converter/src/test/java/lcsb/mapviewer/converter/ProjectFactoryTest.java @@ -1,9 +1,6 @@ package lcsb.mapviewer.converter; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.Assert.*; import java.awt.geom.Point2D; import java.util.Enumeration; @@ -11,23 +8,17 @@ import java.util.List; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; -import org.apache.logging.log4j.*; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.Test; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.junit.*; import lcsb.mapviewer.converter.zip.ModelZipEntryFile; import lcsb.mapviewer.converter.zip.ZipEntryFileFactory; import lcsb.mapviewer.model.Project; -import lcsb.mapviewer.model.map.OverviewImage; -import lcsb.mapviewer.model.map.OverviewLink; -import lcsb.mapviewer.model.map.OverviewModelLink; +import lcsb.mapviewer.model.map.*; import lcsb.mapviewer.model.map.layout.graphics.Layer; import lcsb.mapviewer.model.map.layout.graphics.LayerText; -import lcsb.mapviewer.model.map.model.Model; -import lcsb.mapviewer.model.map.model.ModelData; -import lcsb.mapviewer.model.map.model.ModelFullIndexed; +import lcsb.mapviewer.model.map.model.*; import lcsb.mapviewer.model.map.species.GenericProtein; public class ProjectFactoryTest extends ConverterTestFunctions { @@ -50,214 +41,179 @@ public class ProjectFactoryTest extends ConverterTestFunctions { @Test public void testOverviewImageLink() throws Exception { - try { - ComplexZipConverter converter = new ComplexZipConverter(MockConverter.class); - ProjectFactory projectFactory = new ProjectFactory(converter); - ZipFile zipFile = new ZipFile("testFiles/complex_model_with_img.zip"); - ComplexZipConverterParams params = new ComplexZipConverterParams(); - params.zipFile(zipFile); - - ZipEntryFileFactory factory = new ZipEntryFileFactory(); - Enumeration<? extends ZipEntry> entries = zipFile.entries(); - while (entries.hasMoreElements()) { - ZipEntry entry = entries.nextElement(); - if (!entry.isDirectory()) { - params.entry(factory.createZipEntryFile(entry, zipFile)); - } + ComplexZipConverter converter = new ComplexZipConverter(MockConverter.class); + ProjectFactory projectFactory = new ProjectFactory(converter); + ZipFile zipFile = new ZipFile("testFiles/complex_model_with_img.zip"); + ComplexZipConverterParams params = new ComplexZipConverterParams(); + params.zipFile(zipFile); + + ZipEntryFileFactory factory = new ZipEntryFileFactory(); + Enumeration<? extends ZipEntry> entries = zipFile.entries(); + while (entries.hasMoreElements()) { + ZipEntry entry = entries.nextElement(); + if (!entry.isDirectory()) { + params.entry(factory.createZipEntryFile(entry, zipFile)); } + } - Project project = projectFactory.create(params); - assertNotNull(project); - ModelData model = project.getModels().iterator().next(); - assertEquals("main", model.getName()); - - List<OverviewImage> result = project.getOverviewImages(); - - assertNotNull(result); - assertEquals(1, result.size()); + Project project = projectFactory.create(params); + assertNotNull(project); + ModelData model = project.getModels().iterator().next(); + assertEquals("main", model.getName()); - OverviewImage img = result.get(0); + List<OverviewImage> result = project.getOverviewImages(); - assertEquals("test.png", img.getFilename()); - assertEquals((Integer) 639, img.getHeight()); - assertEquals((Integer) 963, img.getWidth()); - assertEquals(2, img.getLinks().size()); + assertNotNull(result); + assertEquals(1, result.size()); - OverviewLink link = img.getLinks().get(0); - List<Point2D> polygon = link.getPolygonCoordinates(); - assertEquals(4, polygon.size()); + OverviewImage img = result.get(0); - assertTrue(link instanceof OverviewModelLink); + assertEquals("test.png", img.getFilename()); + assertEquals((Integer) 639, img.getHeight()); + assertEquals((Integer) 963, img.getWidth()); + assertEquals(2, img.getLinks().size()); - OverviewModelLink mLink = (OverviewModelLink) link; - assertEquals((Integer) 10, mLink.getxCoord()); - assertEquals((Integer) 10, mLink.getyCoord()); - assertEquals((Integer) 3, mLink.getZoomLevel()); - assertEquals(model, mLink.getLinkedModel()); + OverviewLink link = img.getLinks().get(0); + List<Point2D> polygon = link.getPolygonCoordinates(); + assertEquals(4, polygon.size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertTrue(link instanceof OverviewModelLink); + OverviewModelLink mLink = (OverviewModelLink) link; + assertEquals((Integer) 10, mLink.getxCoord()); + assertEquals((Integer) 10, mLink.getyCoord()); + assertEquals((Integer) 3, mLink.getZoomLevel()); + assertEquals(model, mLink.getLinkedModel()); } @Test public void testOverviewImageLinkToSubmapPath() throws Exception { - try { - ComplexZipConverter converter = new ComplexZipConverter(MockConverter.class); - ProjectFactory projectFactory = new ProjectFactory(converter); - ZipFile zipFile = new ZipFile("testFiles/complex_model_with_images_path.zip"); - ComplexZipConverterParams params = new ComplexZipConverterParams(); - params.zipFile(zipFile); - - ZipEntryFileFactory factory = new ZipEntryFileFactory(); - Enumeration<? extends ZipEntry> entries = zipFile.entries(); - while (entries.hasMoreElements()) { - ZipEntry entry = entries.nextElement(); - if (!entry.isDirectory()) { - params.entry(factory.createZipEntryFile(entry, zipFile)); - } + ComplexZipConverter converter = new ComplexZipConverter(MockConverter.class); + ProjectFactory projectFactory = new ProjectFactory(converter); + ZipFile zipFile = new ZipFile("testFiles/complex_model_with_images_path.zip"); + ComplexZipConverterParams params = new ComplexZipConverterParams(); + params.zipFile(zipFile); + + ZipEntryFileFactory factory = new ZipEntryFileFactory(); + Enumeration<? extends ZipEntry> entries = zipFile.entries(); + while (entries.hasMoreElements()) { + ZipEntry entry = entries.nextElement(); + if (!entry.isDirectory()) { + params.entry(factory.createZipEntryFile(entry, zipFile)); } + } - Project project = projectFactory.create(params); - assertNotNull(project); - ModelData model = project.getModels().iterator().next(); - assertEquals("main", model.getName()); - - List<OverviewImage> result = project.getOverviewImages(); - - assertNotNull(result); - assertEquals(2, result.size()); + Project project = projectFactory.create(params); + assertNotNull(project); + ModelData model = project.getModels().iterator().next(); + assertEquals("main", model.getName()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + List<OverviewImage> result = project.getOverviewImages(); + assertNotNull(result); + assertEquals(2, result.size()); } @Test public void testParseGlyphs() throws Exception { - try { - ComplexZipConverter converter = new ComplexZipConverter(MockConverter.class); - ProjectFactory projectFactory = new ProjectFactory(converter); - - ComplexZipConverterParams params = new ComplexZipConverterParams(); - params.zipFile(new ZipFile("testFiles/complex_with_glyphs.zip")); - params.entry(new ModelZipEntryFile("main.xml", "main", true, false, null)); - - ZipFile zipFile = new ZipFile("testFiles/complex_with_glyphs.zip"); - - ZipEntryFileFactory factory = new ZipEntryFileFactory(); - Enumeration<? extends ZipEntry> entries = zipFile.entries(); - while (entries.hasMoreElements()) { - ZipEntry entry = entries.nextElement(); - if (!entry.isDirectory()) { - params.entry(factory.createZipEntryFile(entry, zipFile)); - } - } + ComplexZipConverter converter = new ComplexZipConverter(MockConverter.class); + ProjectFactory projectFactory = new ProjectFactory(converter); - Project project = projectFactory.create(params); - assertNotNull(project); - assertEquals(1, project.getGlyphs().size()); + ComplexZipConverterParams params = new ComplexZipConverterParams(); + params.zipFile(new ZipFile("testFiles/complex_with_glyphs.zip")); + params.entry(new ModelZipEntryFile("main.xml", "main", true, false, null)); - } catch (Exception e) { - e.printStackTrace(); - throw e; + ZipFile zipFile = new ZipFile("testFiles/complex_with_glyphs.zip"); + + ZipEntryFileFactory factory = new ZipEntryFileFactory(); + Enumeration<? extends ZipEntry> entries = zipFile.entries(); + while (entries.hasMoreElements()) { + ZipEntry entry = entries.nextElement(); + if (!entry.isDirectory()) { + params.entry(factory.createZipEntryFile(entry, zipFile)); + } } + Project project = projectFactory.create(params); + assertNotNull(project); + assertEquals(1, project.getGlyphs().size()); } @Test public void testParseGlyphsAndPutThemAsElementGlyphs() throws Exception { - try { - Model model = new ModelFullIndexed(null); - GenericProtein protein = createProtein(); - protein.setNotes("Glyph: glyphs/g1.png"); - model.addElement(protein); - - MockConverter.modelToBeReturned = model; - - ComplexZipConverter converter = new ComplexZipConverter(MockConverter.class); - ProjectFactory projectFactory = new ProjectFactory(converter); - - ComplexZipConverterParams params = new ComplexZipConverterParams(); - params.zipFile(new ZipFile("testFiles/complex_with_glyphs.zip")); - params.entry(new ModelZipEntryFile("main.xml", "main", true, false, null)); - - ZipFile zipFile = new ZipFile("testFiles/complex_with_glyphs.zip"); - - ZipEntryFileFactory factory = new ZipEntryFileFactory(); - Enumeration<? extends ZipEntry> entries = zipFile.entries(); - while (entries.hasMoreElements()) { - ZipEntry entry = entries.nextElement(); - if (!entry.isDirectory()) { - params.entry(factory.createZipEntryFile(entry, zipFile)); - } - } + Model model = new ModelFullIndexed(null); + GenericProtein protein = createProtein(); + protein.setNotes("Glyph: glyphs/g1.png"); + model.addElement(protein); + + MockConverter.modelToBeReturned = model; - Project project = projectFactory.create(params); - assertNotNull(project); - model = project.getModels().iterator().next().getModel(); + ComplexZipConverter converter = new ComplexZipConverter(MockConverter.class); + ProjectFactory projectFactory = new ProjectFactory(converter); - GenericProtein fetchedProtein = (GenericProtein) model.getElements().iterator().next(); + ComplexZipConverterParams params = new ComplexZipConverterParams(); + params.zipFile(new ZipFile("testFiles/complex_with_glyphs.zip")); + params.entry(new ModelZipEntryFile("main.xml", "main", true, false, null)); - assertFalse("Glyph field should be removed from notes", fetchedProtein.getNotes().contains("Glyph")); - assertNotNull("Glyph in the protein is not defined but should", fetchedProtein.getGlyph()); + ZipFile zipFile = new ZipFile("testFiles/complex_with_glyphs.zip"); - } catch (Exception e) { - e.printStackTrace(); - throw e; + ZipEntryFileFactory factory = new ZipEntryFileFactory(); + Enumeration<? extends ZipEntry> entries = zipFile.entries(); + while (entries.hasMoreElements()) { + ZipEntry entry = entries.nextElement(); + if (!entry.isDirectory()) { + params.entry(factory.createZipEntryFile(entry, zipFile)); + } } + Project project = projectFactory.create(params); + assertNotNull(project); + model = project.getModels().iterator().next().getModel(); + + GenericProtein fetchedProtein = (GenericProtein) model.getElements().iterator().next(); + + assertFalse("Glyph field should be removed from notes", fetchedProtein.getNotes().contains("Glyph")); + assertNotNull("Glyph in the protein is not defined but should", fetchedProtein.getGlyph()); } @Test public void testParseGlyphsAndPutThemAsTextGlyphs() throws Exception { - try { - Model model = new ModelFullIndexed(null); - Layer layer = new Layer(); - - LayerText text = new LayerText(); - text.setNotes("Glyph: glyphs/g1.png"); - layer.addLayerText(text); - model.addLayer(layer); - - MockConverter.modelToBeReturned = model; - - ComplexZipConverter converter = new ComplexZipConverter(MockConverter.class); - ProjectFactory projectFactory = new ProjectFactory(converter); - - ComplexZipConverterParams params = new ComplexZipConverterParams(); - params.zipFile(new ZipFile("testFiles/complex_with_glyphs.zip")); - params.entry(new ModelZipEntryFile("main.xml", "main", true, false, null)); - - ZipFile zipFile = new ZipFile("testFiles/complex_with_glyphs.zip"); - - ZipEntryFileFactory factory = new ZipEntryFileFactory(); - Enumeration<? extends ZipEntry> entries = zipFile.entries(); - while (entries.hasMoreElements()) { - ZipEntry entry = entries.nextElement(); - if (!entry.isDirectory()) { - params.entry(factory.createZipEntryFile(entry, zipFile)); - } - } + Model model = new ModelFullIndexed(null); + Layer layer = new Layer(); - Project project = projectFactory.create(params); - assertNotNull(project); - model = project.getModels().iterator().next().getModel(); + LayerText text = new LayerText(); + text.setNotes("Glyph: glyphs/g1.png"); + layer.addLayerText(text); + model.addLayer(layer); - LayerText fetchedProtein = model.getLayers().iterator().next().getTexts().get(0); + MockConverter.modelToBeReturned = model; - assertFalse("Glyph field should be removed from notes", fetchedProtein.getNotes().contains("Glyph")); - assertNotNull("Glyph in the protein is not defined but should", fetchedProtein.getGlyph()); + ComplexZipConverter converter = new ComplexZipConverter(MockConverter.class); + ProjectFactory projectFactory = new ProjectFactory(converter); - } catch (Exception e) { - e.printStackTrace(); - throw e; + ComplexZipConverterParams params = new ComplexZipConverterParams(); + params.zipFile(new ZipFile("testFiles/complex_with_glyphs.zip")); + params.entry(new ModelZipEntryFile("main.xml", "main", true, false, null)); + + ZipFile zipFile = new ZipFile("testFiles/complex_with_glyphs.zip"); + + ZipEntryFileFactory factory = new ZipEntryFileFactory(); + Enumeration<? extends ZipEntry> entries = zipFile.entries(); + while (entries.hasMoreElements()) { + ZipEntry entry = entries.nextElement(); + if (!entry.isDirectory()) { + params.entry(factory.createZipEntryFile(entry, zipFile)); + } } + Project project = projectFactory.create(params); + assertNotNull(project); + model = project.getModels().iterator().next().getModel(); + + LayerText fetchedProtein = model.getLayers().iterator().next().getTexts().get(0); + + assertFalse("Glyph field should be removed from notes", fetchedProtein.getNotes().contains("Glyph")); + assertNotNull("Glyph in the protein is not defined but should", fetchedProtein.getGlyph()); } private GenericProtein createProtein() { diff --git a/converter/src/test/java/lcsb/mapviewer/converter/annotation/XmlAnnotationParserTest.java b/converter/src/test/java/lcsb/mapviewer/converter/annotation/XmlAnnotationParserTest.java index b3e96a1a90e3322d70e91c6125c6f87b96a2895e..8e94a40acb03ba070518529d03575f9b70cdb98c 100644 --- a/converter/src/test/java/lcsb/mapviewer/converter/annotation/XmlAnnotationParserTest.java +++ b/converter/src/test/java/lcsb/mapviewer/converter/annotation/XmlAnnotationParserTest.java @@ -1,22 +1,15 @@ package lcsb.mapviewer.converter.annotation; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import java.util.Set; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.w3c.dom.Node; import lcsb.mapviewer.common.exception.InvalidXmlSchemaException; import lcsb.mapviewer.converter.ConverterTestFunctions; -import lcsb.mapviewer.model.map.MiriamData; -import lcsb.mapviewer.model.map.MiriamRelationType; -import lcsb.mapviewer.model.map.MiriamType; +import lcsb.mapviewer.model.map.*; public class XmlAnnotationParserTest extends ConverterTestFunctions { @@ -30,120 +23,75 @@ public class XmlAnnotationParserTest extends ConverterTestFunctions { @Test public void testParseRdf() throws Exception { - try { - XmlAnnotationParser xap = new XmlAnnotationParser(); + XmlAnnotationParser xap = new XmlAnnotationParser(); - String xml = readFile("testFiles/annotation/rdf.xml"); + String xml = readFile("testFiles/annotation/rdf.xml"); - Set<MiriamData> set = xap.parse(xml); - assertEquals(2, set.size()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Set<MiriamData> set = xap.parse(xml); + assertEquals(2, set.size()); } @Test public void testMiriamDataToXmlAndBack() throws Exception { - try { - MiriamData md = new MiriamData(MiriamRelationType.BQ_BIOL_IS_DESCRIBED_BY, MiriamType.CHEBI, "e:f"); - XmlAnnotationParser parser = new XmlAnnotationParser(); - String xml = parser.miriamDataToXmlString(md); - assertNotNull(xml); - Set<MiriamData> set = parser.parseMiriamNode(super.getNodeFromXmlString(xml)); - assertNotNull(set); - assertEquals(1, set.size()); - MiriamData md1 = set.iterator().next(); - assertNotNull(md1); - assertEquals(md.getDataType(), md1.getDataType()); - assertEquals(md.getRelationType(), md1.getRelationType()); - assertEquals(md.getResource(), md1.getResource()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + MiriamData md = new MiriamData(MiriamRelationType.BQ_BIOL_IS_DESCRIBED_BY, MiriamType.CHEBI, "e:f"); + XmlAnnotationParser parser = new XmlAnnotationParser(); + String xml = parser.miriamDataToXmlString(md); + assertNotNull(xml); + Set<MiriamData> set = parser.parseMiriamNode(super.getNodeFromXmlString(xml)); + assertNotNull(set); + assertEquals(1, set.size()); + MiriamData md1 = set.iterator().next(); + assertNotNull(md1); + assertEquals(md.getDataType(), md1.getDataType()); + assertEquals(md.getRelationType(), md1.getRelationType()); + assertEquals(md.getResource(), md1.getResource()); } - @Test + @Test(expected = InvalidXmlSchemaException.class) public void testParseInvalidRdf() throws Exception { - try { - XmlAnnotationParser xap = new XmlAnnotationParser(); - - xap.parseRdfNode((Node) null); - fail("Exception expected"); - - } catch (InvalidXmlSchemaException e) { - assertTrue(e.getMessage().contains("rdf:Rdf node not found")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + XmlAnnotationParser xap = new XmlAnnotationParser(); + + xap.parseRdfNode((Node) null); } @Test public void testParseRdfWithCreatorTag() throws Exception { - try { - XmlAnnotationParser xap = new XmlAnnotationParser(); - String xml = readFile("testFiles/annotation/rdf_with_creator_tag.xml"); - - Set<MiriamData> set = xap.parse(xml); - assertTrue(set.size() > 0); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + XmlAnnotationParser xap = new XmlAnnotationParser(); + String xml = readFile("testFiles/annotation/rdf_with_creator_tag.xml"); + + Set<MiriamData> set = xap.parse(xml); + assertTrue(set.size() > 0); } - @Test + @Test(expected = InvalidXmlSchemaException.class) public void testParseInvalidRdf3() throws Exception { - try { - XmlAnnotationParser xap = new XmlAnnotationParser(); - - String xml = readFile("testFiles/annotation/invalid_rdf2.xml"); + XmlAnnotationParser xap = new XmlAnnotationParser(); - xap.parse(xml); + String xml = readFile("testFiles/annotation/invalid_rdf2.xml"); - fail("Exception expected"); - } catch (InvalidXmlSchemaException e) { - assertTrue("Invalid message: " + e.getMessage(), - e.getMessage().contains("rdf:li does not have a rdf:resource attribute")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + xap.parse(xml); } @Test public void testParseInvalidRdf4() throws Exception { - try { - XmlAnnotationParser xap = new XmlAnnotationParser(); + XmlAnnotationParser xap = new XmlAnnotationParser(); - String xml = readFile("testFiles/annotation/invalid_rdf3.xml"); + String xml = readFile("testFiles/annotation/invalid_rdf3.xml"); - xap.parse(xml); + xap.parse(xml); - assertEquals(1, getWarnings().size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(1, getWarnings().size()); } @Test public void testParseInvalidRdf5() throws Exception { - try { - XmlAnnotationParser xap = new XmlAnnotationParser(); + XmlAnnotationParser xap = new XmlAnnotationParser(); - String xml = readFile("testFiles/annotation/invalid_rdf4.xml"); + String xml = readFile("testFiles/annotation/invalid_rdf4.xml"); - xap.parse(xml); + xap.parse(xml); - assertEquals(1, getWarnings().size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(1, getWarnings().size()); } } diff --git a/model-command/src/test/java/lcsb/mapviewer/commands/ColorModelCommandTest.java b/model-command/src/test/java/lcsb/mapviewer/commands/ColorModelCommandTest.java index ad04e4e0010a5705c1a3b41093af37912cb6027e..16db4493fccfabdb35f55d010b6c744aca1ba52d 100644 --- a/model-command/src/test/java/lcsb/mapviewer/commands/ColorModelCommandTest.java +++ b/model-command/src/test/java/lcsb/mapviewer/commands/ColorModelCommandTest.java @@ -1,35 +1,20 @@ package lcsb.mapviewer.commands; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.Assert.*; import java.awt.Color; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; -import java.util.Map; - -import org.apache.logging.log4j.*; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import lcsb.mapviewer.model.map.BioEntity; -import lcsb.mapviewer.model.map.MiriamData; -import lcsb.mapviewer.model.map.MiriamType; +import java.util.*; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.junit.*; + +import lcsb.mapviewer.model.map.*; import lcsb.mapviewer.model.map.layout.ColorSchema; import lcsb.mapviewer.model.map.layout.GenericColorSchema; -import lcsb.mapviewer.model.map.model.Model; -import lcsb.mapviewer.model.map.model.ModelComparator; -import lcsb.mapviewer.model.map.model.ModelFullIndexed; -import lcsb.mapviewer.model.map.model.ModelSubmodelConnection; -import lcsb.mapviewer.model.map.model.SubmodelType; +import lcsb.mapviewer.model.map.model.*; import lcsb.mapviewer.model.map.reaction.Reaction; -import lcsb.mapviewer.model.map.species.Element; -import lcsb.mapviewer.model.map.species.GenericProtein; -import lcsb.mapviewer.model.map.species.Protein; +import lcsb.mapviewer.model.map.species.*; public class ColorModelCommandTest extends CommandTestFunctions { Logger logger = LogManager.getLogger(ColorModelCommandTest.class); @@ -53,568 +38,425 @@ public class ColorModelCommandTest extends CommandTestFunctions { @Test public void testColorFullModel() throws Exception { ModelComparator comparator = new ModelComparator(); - try { - Model model = getModelForFile("testFiles/sample.xml", false); - Model model2 = getModelForFile("testFiles/sample.xml", false); - Model coloredModel = new CopyCommand(model).execute(); + Model model = getModelForFile("testFiles/sample.xml", false); + Model model2 = getModelForFile("testFiles/sample.xml", false); + Model coloredModel = new CopyCommand(model).execute(); - List<ColorSchema> schemas = new ArrayList<>(); - ColorSchema schema = new GenericColorSchema(); - schema.setName("CNC"); - schema.setValue(-1.0); - schemas.add(schema); - ColorModelCommand factory = new ColorModelCommand(coloredModel, schemas, colorExtractor); + List<ColorSchema> schemas = new ArrayList<>(); + ColorSchema schema = new GenericColorSchema(); + schema.setName("CNC"); + schema.setValue(-1.0); + schemas.add(schema); + ColorModelCommand factory = new ColorModelCommand(coloredModel, schemas, colorExtractor); - assertFalse(Color.RED.equals(coloredModel.getElementByElementId("sa14").getColor())); + assertFalse(Color.RED.equals(coloredModel.getElementByElementId("sa14").getColor())); - factory.execute(); + factory.execute(); - assertEquals(0, comparator.compare(model, model2)); + assertEquals(0, comparator.compare(model, model2)); - assertFalse(comparator.compare(model, coloredModel) == 0); + assertFalse(comparator.compare(model, coloredModel) == 0); - assertEquals(Color.RED, coloredModel.getElementByElementId("sa14").getColor()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(Color.RED, coloredModel.getElementByElementId("sa14").getColor()); } @Test public void testColoring2() throws Exception { - try { - Model model = getModelForFile("testFiles/coloring_model.xml", true); - Collection<ColorSchema> schemas = new ArrayList<>(); - ColorSchema schema = new GenericColorSchema(); - schema.addMiriamData(new MiriamData(MiriamType.HGNC, "11138")); - schema.setValue(1.0); - schemas.add(schema); - schema = new GenericColorSchema(); - schema.addMiriamData(new MiriamData(MiriamType.CHEBI, "CHEBI:15377")); - schema.setValue(1.0); - schemas.add(schema); - schema = new GenericColorSchema(); - schema.addMiriamData(new MiriamData(MiriamType.CHEBI, "CHEBI:15376")); - schema.setValue(1.0); - schemas.add(schema); - - ColorModelCommand factory = new ColorModelCommand(model, schemas, colorExtractor); - Collection<ColorSchema> missing = factory.getMissingSchema(); - - assertEquals(1, missing.size()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Model model = getModelForFile("testFiles/coloring_model.xml", true); + Collection<ColorSchema> schemas = new ArrayList<>(); + ColorSchema schema = new GenericColorSchema(); + schema.addMiriamData(new MiriamData(MiriamType.HGNC, "11138")); + schema.setValue(1.0); + schemas.add(schema); + schema = new GenericColorSchema(); + schema.addMiriamData(new MiriamData(MiriamType.CHEBI, "CHEBI:15377")); + schema.setValue(1.0); + schemas.add(schema); + schema = new GenericColorSchema(); + schema.addMiriamData(new MiriamData(MiriamType.CHEBI, "CHEBI:15376")); + schema.setValue(1.0); + schemas.add(schema); + + ColorModelCommand factory = new ColorModelCommand(model, schemas, colorExtractor); + Collection<ColorSchema> missing = factory.getMissingSchema(); + + assertEquals(1, missing.size()); } @Test public void testReactionColoring1() throws Exception { - try { - Model model = getModelForFile("testFiles/reactions_to_color.xml", false); - Reaction re4 = model.getReactionByReactionId("re4"); - Collection<ColorSchema> schemas = new ArrayList<ColorSchema>(); - - ColorModelCommand factory = new ColorModelCommand(model, schemas, colorExtractor); - assertFalse(Color.BLACK.equals(re4.getNodes().get(0).getLine().getColor())); + Model model = getModelForFile("testFiles/reactions_to_color.xml", false); + Reaction re4 = model.getReactionByReactionId("re4"); + Collection<ColorSchema> schemas = new ArrayList<ColorSchema>(); - factory.execute(); - re4 = model.getReactionByReactionId("re4"); + ColorModelCommand factory = new ColorModelCommand(model, schemas, colorExtractor); + assertFalse(Color.BLACK.equals(re4.getNodes().get(0).getLine().getColor())); - assertEquals(Color.BLACK, re4.getNodes().get(0).getLine().getColor()); + factory.execute(); + re4 = model.getReactionByReactionId("re4"); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(Color.BLACK, re4.getNodes().get(0).getLine().getColor()); } @Test public void testReactionColoring2() throws Exception { - try { - Model model = getModelForFile("testFiles/reactions_to_color.xml", false); - Reaction re1 = model.getReactionByReactionId("re1"); - Collection<ColorSchema> schemas = new ArrayList<ColorSchema>(); - ColorSchema schema = new GenericColorSchema(); - schema.setElementId("re1"); - schema.setColor(Color.RED); - schemas.add(schema); - - ColorModelCommand factory = new ColorModelCommand(model, schemas, colorExtractor); - assertEquals(Color.BLACK, re1.getNodes().get(0).getLine().getColor()); - - factory.execute(); - re1 = model.getReactionByReactionId("re1"); - - assertEquals(Color.RED, re1.getNodes().get(0).getLine().getColor()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Model model = getModelForFile("testFiles/reactions_to_color.xml", false); + Reaction re1 = model.getReactionByReactionId("re1"); + Collection<ColorSchema> schemas = new ArrayList<ColorSchema>(); + ColorSchema schema = new GenericColorSchema(); + schema.setElementId("re1"); + schema.setColor(Color.RED); + schemas.add(schema); + + ColorModelCommand factory = new ColorModelCommand(model, schemas, colorExtractor); + assertEquals(Color.BLACK, re1.getNodes().get(0).getLine().getColor()); + + factory.execute(); + re1 = model.getReactionByReactionId("re1"); + + assertEquals(Color.RED, re1.getNodes().get(0).getLine().getColor()); } @Test public void testReactionColoring3() throws Exception { - try { - Model model = getModelForFile("testFiles/reactions_to_color.xml", false); - Reaction re2 = model.getReactionByReactionId("re2"); - Collection<ColorSchema> schemas = new ArrayList<ColorSchema>(); - ColorSchema schema = new GenericColorSchema(); - schema.setElementId("re2"); - schema.setValue(-1.0); - schemas.add(schema); - - ColorModelCommand factory = new ColorModelCommand(model, schemas, colorExtractor); - assertEquals(Color.BLACK, re2.getNodes().get(0).getLine().getColor()); - - factory.execute(); - re2 = model.getReactionByReactionId("re2"); - - assertEquals(Color.RED, re2.getNodes().get(0).getLine().getColor()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Model model = getModelForFile("testFiles/reactions_to_color.xml", false); + Reaction re2 = model.getReactionByReactionId("re2"); + Collection<ColorSchema> schemas = new ArrayList<ColorSchema>(); + ColorSchema schema = new GenericColorSchema(); + schema.setElementId("re2"); + schema.setValue(-1.0); + schemas.add(schema); + + ColorModelCommand factory = new ColorModelCommand(model, schemas, colorExtractor); + assertEquals(Color.BLACK, re2.getNodes().get(0).getLine().getColor()); + + factory.execute(); + re2 = model.getReactionByReactionId("re2"); + + assertEquals(Color.RED, re2.getNodes().get(0).getLine().getColor()); } @Test public void testReactionColoring4() throws Exception { - try { - Model model = getModelForFile("testFiles/reactions_to_color.xml", false); - Reaction re3 = model.getReactionByReactionId("re3"); - Collection<ColorSchema> schemas = new ArrayList<ColorSchema>(); - ColorSchema schema = new GenericColorSchema(); - schema.addMiriamData(new MiriamData(MiriamType.PUBMED, "12345")); - schema.setValue(-1.0); - schemas.add(schema); - - ColorModelCommand factory = new ColorModelCommand(model, schemas, colorExtractor); + Model model = getModelForFile("testFiles/reactions_to_color.xml", false); + Reaction re3 = model.getReactionByReactionId("re3"); + Collection<ColorSchema> schemas = new ArrayList<ColorSchema>(); + ColorSchema schema = new GenericColorSchema(); + schema.addMiriamData(new MiriamData(MiriamType.PUBMED, "12345")); + schema.setValue(-1.0); + schemas.add(schema); - assertEquals(Color.BLACK, re3.getNodes().get(0).getLine().getColor()); + ColorModelCommand factory = new ColorModelCommand(model, schemas, colorExtractor); - factory.execute(); - re3 = model.getReactionByReactionId("re3"); + assertEquals(Color.BLACK, re3.getNodes().get(0).getLine().getColor()); - assertEquals(Color.RED, re3.getNodes().get(0).getLine().getColor()); + factory.execute(); + re3 = model.getReactionByReactionId("re3"); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(Color.RED, re3.getNodes().get(0).getLine().getColor()); } @Test public void testColoringComplexModel() throws Exception { - try { - Model model = getModelForFile("testFiles/sample.xml", false); - Model model2 = getModelForFile("testFiles/sample.xml", false); - - model.addSubmodelConnection(new ModelSubmodelConnection(model2, SubmodelType.UNKNOWN, "BLA")); + Model model = getModelForFile("testFiles/sample.xml", false); + Model model2 = getModelForFile("testFiles/sample.xml", false); - Collection<ColorSchema> schemas = new ArrayList<>(); - Model coloredModel = new CopyCommand(model).execute(); - new ColorModelCommand(coloredModel, schemas, colorExtractor).execute(); + model.addSubmodelConnection(new ModelSubmodelConnection(model2, SubmodelType.UNKNOWN, "BLA")); - Model coloredModel2 = coloredModel.getSubmodelConnections().iterator().next().getSubmodel().getModel(); - Model coloredModel3 = coloredModel.getSubmodelByConnectionName("BLA"); + Collection<ColorSchema> schemas = new ArrayList<>(); + Model coloredModel = new CopyCommand(model).execute(); + new ColorModelCommand(coloredModel, schemas, colorExtractor).execute(); - assertFalse( - coloredModel2.getElementByElementId("sa2").getColor().equals(model2.getElementByElementId("sa2").getColor())); - assertFalse( - coloredModel3.getElementByElementId("sa2").getColor().equals(model2.getElementByElementId("sa2").getColor())); + Model coloredModel2 = coloredModel.getSubmodelConnections().iterator().next().getSubmodel().getModel(); + Model coloredModel3 = coloredModel.getSubmodelByConnectionName("BLA"); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertFalse( + coloredModel2.getElementByElementId("sa2").getColor().equals(model2.getElementByElementId("sa2").getColor())); + assertFalse( + coloredModel3.getElementByElementId("sa2").getColor().equals(model2.getElementByElementId("sa2").getColor())); } @Test public void testColoredAliases() throws Exception { - try { - Model model = getModelForFile("testFiles/sample.xml", false); - Collection<ColorSchema> schemas = new ArrayList<>(); - ColorSchema schema = new GenericColorSchema(); - schema.setName("CNC"); - schema.setColor(Color.BLUE); - schemas.add(schema); - schema = new GenericColorSchema(); - schema.setName("BDH1"); - schema.setColor(Color.BLUE); - schemas.add(schema); - ColorModelCommand factory = new ColorModelCommand(model, schemas, colorExtractor); - - Map<Object, ColorSchema> map = factory.getModifiedElements(); - assertEquals(2, map.size()); - for (Map.Entry<Object, ColorSchema> entry : map.entrySet()) { - assertTrue(entry.getKey() instanceof Element); - } - } catch (Exception e) { - e.printStackTrace(); - throw e; + Model model = getModelForFile("testFiles/sample.xml", false); + Collection<ColorSchema> schemas = new ArrayList<>(); + ColorSchema schema = new GenericColorSchema(); + schema.setName("CNC"); + schema.setColor(Color.BLUE); + schemas.add(schema); + schema = new GenericColorSchema(); + schema.setName("BDH1"); + schema.setColor(Color.BLUE); + schemas.add(schema); + ColorModelCommand factory = new ColorModelCommand(model, schemas, colorExtractor); + + Map<Object, ColorSchema> map = factory.getModifiedElements(); + assertEquals(2, map.size()); + for (Map.Entry<Object, ColorSchema> entry : map.entrySet()) { + assertTrue(entry.getKey() instanceof Element); } } @Test public void testColoredReactions() throws Exception { - try { - Model model = getModelForFile("testFiles/sample.xml", false); - Collection<ColorSchema> schemas = new ArrayList<>(); - ColorSchema schema = new GenericColorSchema(); - schema.setElementId("re1"); - schema.setLineWidth(3.0); - schema.setColor(Color.BLUE); - schema.setName(""); - schema.setReverseReaction(true); - schemas.add(schema); - ColorModelCommand factory = new ColorModelCommand(model, schemas, colorExtractor); - - Map<Object, ColorSchema> map = factory.getModifiedElements(); - assertEquals(0, map.size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Model model = getModelForFile("testFiles/sample.xml", false); + Collection<ColorSchema> schemas = new ArrayList<>(); + ColorSchema schema = new GenericColorSchema(); + schema.setElementId("re1"); + schema.setLineWidth(3.0); + schema.setColor(Color.BLUE); + schema.setName(""); + schema.setReverseReaction(true); + schemas.add(schema); + ColorModelCommand factory = new ColorModelCommand(model, schemas, colorExtractor); + + Map<Object, ColorSchema> map = factory.getModifiedElements(); + assertEquals(0, map.size()); } @Test public void testColoredReactions2() throws Exception { - try { - Model model = getModelForFile("testFiles/sample.xml", false); - Collection<ColorSchema> schemas = new ArrayList<>(); - ColorSchema schema = new GenericColorSchema(); - schema.setElementId("re1"); - schema.setLineWidth(3.0); - schema.setColor(Color.BLUE); - schema.setName(null); - schema.setReverseReaction(true); - schemas.add(schema); - ColorModelCommand factory = new ColorModelCommand(model, schemas, colorExtractor); - - Map<Object, ColorSchema> map = factory.getModifiedElements(); - assertEquals(1, map.size()); - for (Map.Entry<Object, ColorSchema> entry : map.entrySet()) { - assertTrue(entry.getKey() instanceof Reaction); - assertEquals("re1", ((Reaction) entry.getKey()).getIdReaction()); - assertEquals(entry.getValue(), schema); - } - - } catch (Exception e) { - e.printStackTrace(); - throw e; + Model model = getModelForFile("testFiles/sample.xml", false); + Collection<ColorSchema> schemas = new ArrayList<>(); + ColorSchema schema = new GenericColorSchema(); + schema.setElementId("re1"); + schema.setLineWidth(3.0); + schema.setColor(Color.BLUE); + schema.setName(null); + schema.setReverseReaction(true); + schemas.add(schema); + ColorModelCommand factory = new ColorModelCommand(model, schemas, colorExtractor); + + Map<Object, ColorSchema> map = factory.getModifiedElements(); + assertEquals(1, map.size()); + for (Map.Entry<Object, ColorSchema> entry : map.entrySet()) { + assertTrue(entry.getKey() instanceof Reaction); + assertEquals("re1", ((Reaction) entry.getKey()).getIdReaction()); + assertEquals(entry.getValue(), schema); } } @Test public void testAliasMatchWithInvalidElementId() throws Exception { - try { - GenericColorSchema colorSchema = new GenericColorSchema(); - colorSchema.setName(null); - colorSchema.setElementId("1"); - - BioEntity protein = new GenericProtein("id"); - protein.setName("test"); + GenericColorSchema colorSchema = new GenericColorSchema(); + colorSchema.setName(null); + colorSchema.setElementId("1"); - List<ColorSchema> schemas = new ArrayList<>(); - schemas.add(colorSchema); + BioEntity protein = new GenericProtein("id"); + protein.setName("test"); - ColorModelCommand factory = new ColorModelCommand(new ModelFullIndexed(null), schemas, colorExtractor); + List<ColorSchema> schemas = new ArrayList<>(); + schemas.add(colorSchema); - assertFalse(factory.match(protein, colorSchema)); + ColorModelCommand factory = new ColorModelCommand(new ModelFullIndexed(null), schemas, colorExtractor); - colorSchema.setElementId(null); - assertTrue(factory.match(protein, colorSchema)); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertFalse(factory.match(protein, colorSchema)); + colorSchema.setElementId(null); + assertTrue(factory.match(protein, colorSchema)); } @Test public void testSpeciesMatchWithProteinType() throws Exception { - try { - GenericColorSchema colorSchema = new GenericColorSchema(); - colorSchema.setName("s1"); - colorSchema.addType(Protein.class); - - GenericProtein species = new GenericProtein("id"); - species.setName("s1"); + GenericColorSchema colorSchema = new GenericColorSchema(); + colorSchema.setName("s1"); + colorSchema.addType(Protein.class); - List<ColorSchema> schemas = new ArrayList<>(); - schemas.add(colorSchema); + GenericProtein species = new GenericProtein("id"); + species.setName("s1"); - ColorModelCommand factory = new ColorModelCommand(new ModelFullIndexed(null), schemas, colorExtractor); + List<ColorSchema> schemas = new ArrayList<>(); + schemas.add(colorSchema); - assertTrue(factory.match(species, colorSchema)); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + ColorModelCommand factory = new ColorModelCommand(new ModelFullIndexed(null), schemas, colorExtractor); + assertTrue(factory.match(species, colorSchema)); } @Test public void testSpeciesMatchWithMiriamData() throws Exception { - try { - GenericColorSchema colorSchema = new GenericColorSchema(); - colorSchema.setName("s1"); - colorSchema.addMiriamData(new MiriamData(MiriamType.HGNC_SYMBOL, "SNCA")); - - GenericColorSchema colorSchema2 = new GenericColorSchema(); - colorSchema2.setName("s1"); - colorSchema2.addMiriamData(new MiriamData(MiriamType.HGNC_SYMBOL, "PARK7")); + GenericColorSchema colorSchema = new GenericColorSchema(); + colorSchema.setName("s1"); + colorSchema.addMiriamData(new MiriamData(MiriamType.HGNC_SYMBOL, "SNCA")); - GenericProtein species = new GenericProtein("id"); - species.setName("s1"); - species.addMiriamData(new MiriamData(MiriamType.HGNC_SYMBOL, "SNCA")); + GenericColorSchema colorSchema2 = new GenericColorSchema(); + colorSchema2.setName("s1"); + colorSchema2.addMiriamData(new MiriamData(MiriamType.HGNC_SYMBOL, "PARK7")); - List<ColorSchema> schemas = new ArrayList<>(); - schemas.add(colorSchema); + GenericProtein species = new GenericProtein("id"); + species.setName("s1"); + species.addMiriamData(new MiriamData(MiriamType.HGNC_SYMBOL, "SNCA")); - ColorModelCommand factory = new ColorModelCommand(new ModelFullIndexed(null), schemas, colorExtractor); + List<ColorSchema> schemas = new ArrayList<>(); + schemas.add(colorSchema); - assertTrue(factory.match(species, colorSchema)); - assertFalse(factory.match(species, colorSchema2)); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + ColorModelCommand factory = new ColorModelCommand(new ModelFullIndexed(null), schemas, colorExtractor); + assertTrue(factory.match(species, colorSchema)); + assertFalse(factory.match(species, colorSchema2)); } @Test public void testSpeciesMatchWithMiriamDataDifferentAnnotator() throws Exception { - try { - GenericColorSchema colorSchema = new GenericColorSchema(); - colorSchema.setName("s1"); - colorSchema.addMiriamData(new MiriamData(MiriamType.HGNC_SYMBOL, "SNCA")); + GenericColorSchema colorSchema = new GenericColorSchema(); + colorSchema.setName("s1"); + colorSchema.addMiriamData(new MiriamData(MiriamType.HGNC_SYMBOL, "SNCA")); - GenericProtein species = new GenericProtein("id"); - species.setName("s1"); - species.addMiriamData(new MiriamData(MiriamType.HGNC_SYMBOL, "SNCA", Object.class)); + GenericProtein species = new GenericProtein("id"); + species.setName("s1"); + species.addMiriamData(new MiriamData(MiriamType.HGNC_SYMBOL, "SNCA", Object.class)); - List<ColorSchema> schemas = new ArrayList<>(); - schemas.add(colorSchema); + List<ColorSchema> schemas = new ArrayList<>(); + schemas.add(colorSchema); - ColorModelCommand factory = new ColorModelCommand(new ModelFullIndexed(null), schemas, colorExtractor); - - assertTrue(factory.match(species, colorSchema)); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + ColorModelCommand factory = new ColorModelCommand(new ModelFullIndexed(null), schemas, colorExtractor); + assertTrue(factory.match(species, colorSchema)); } @Test public void testReactionMatchWithProteinMiriamData() throws Exception { - try { - GenericColorSchema colorSchema = new GenericColorSchema(); - colorSchema.addMiriamData(new MiriamData(MiriamType.HGNC_SYMBOL, "SNCA")); - - Reaction reaction = new Reaction(); + GenericColorSchema colorSchema = new GenericColorSchema(); + colorSchema.addMiriamData(new MiriamData(MiriamType.HGNC_SYMBOL, "SNCA")); - List<ColorSchema> schemas = new ArrayList<>(); - schemas.add(colorSchema); + Reaction reaction = new Reaction(); - ColorModelCommand factory = new ColorModelCommand(new ModelFullIndexed(null), schemas, colorExtractor); + List<ColorSchema> schemas = new ArrayList<>(); + schemas.add(colorSchema); - assertFalse(factory.match(reaction, colorSchema)); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + ColorModelCommand factory = new ColorModelCommand(new ModelFullIndexed(null), schemas, colorExtractor); + assertFalse(factory.match(reaction, colorSchema)); } @Test public void testReactionMatchWithMiriamData() throws Exception { - try { - GenericColorSchema colorSchema = new GenericColorSchema(); - colorSchema.addMiriamData(new MiriamData(MiriamType.PUBMED, "1234")); - - Reaction reaction = new Reaction(); - reaction.addMiriamData(new MiriamData(MiriamType.PUBMED, "1234")); - - List<ColorSchema> schemas = new ArrayList<>(); - schemas.add(colorSchema); + GenericColorSchema colorSchema = new GenericColorSchema(); + colorSchema.addMiriamData(new MiriamData(MiriamType.PUBMED, "1234")); - ColorModelCommand factory = new ColorModelCommand(new ModelFullIndexed(null), schemas, colorExtractor); + Reaction reaction = new Reaction(); + reaction.addMiriamData(new MiriamData(MiriamType.PUBMED, "1234")); - assertTrue(factory.match(reaction, colorSchema)); + List<ColorSchema> schemas = new ArrayList<>(); + schemas.add(colorSchema); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + ColorModelCommand factory = new ColorModelCommand(new ModelFullIndexed(null), schemas, colorExtractor); + assertTrue(factory.match(reaction, colorSchema)); } @Test public void testReactionColoringWithModelNotMatching() throws Exception { - try { - Model model = getModelForFile("testFiles/reactions_to_color.xml", false); - - ColorSchema schema = new GenericColorSchema(); - schema.setElementId("re4"); - schema.setName(null); - schema.setModelName(model.getName() + "XXX"); + Model model = getModelForFile("testFiles/reactions_to_color.xml", false); - Collection<ColorSchema> schemas = new ArrayList<>(); - schemas.add(schema); + ColorSchema schema = new GenericColorSchema(); + schema.setElementId("re4"); + schema.setName(null); + schema.setModelName(model.getName() + "XXX"); - ColorModelCommand factory = new ColorModelCommand(model, schemas, colorExtractor); - Map<Object, ColorSchema> map = factory.getModifiedElements(); - assertEquals(0, map.values().size()); + Collection<ColorSchema> schemas = new ArrayList<>(); + schemas.add(schema); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + ColorModelCommand factory = new ColorModelCommand(model, schemas, colorExtractor); + Map<Object, ColorSchema> map = factory.getModifiedElements(); + assertEquals(0, map.values().size()); } @Test public void testReactionColoringWithModelMatch() throws Exception { - try { - Model model = getModelForFile("testFiles/reactions_to_color.xml", false); + Model model = getModelForFile("testFiles/reactions_to_color.xml", false); - ColorSchema schema = new GenericColorSchema(); - schema.setElementId("re4"); - schema.setName(null); - schema.setModelName(model.getName()); + ColorSchema schema = new GenericColorSchema(); + schema.setElementId("re4"); + schema.setName(null); + schema.setModelName(model.getName()); - Collection<ColorSchema> schemas = new ArrayList<>(); - schemas.add(schema); + Collection<ColorSchema> schemas = new ArrayList<>(); + schemas.add(schema); - ColorModelCommand factory = new ColorModelCommand(model, schemas, colorExtractor); - Map<Object, ColorSchema> map = factory.getModifiedElements(); - assertEquals(1, map.values().size()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + ColorModelCommand factory = new ColorModelCommand(model, schemas, colorExtractor); + Map<Object, ColorSchema> map = factory.getModifiedElements(); + assertEquals(1, map.values().size()); } @Test public void testAliasColoringWithModelNotMatching() throws Exception { - try { - Model model = getModelForFile("testFiles/sample.xml", false); + Model model = getModelForFile("testFiles/sample.xml", false); - ColorSchema schema = new GenericColorSchema(); - schema.setName("CNC"); - schema.setModelName(model.getName() + "XXX"); + ColorSchema schema = new GenericColorSchema(); + schema.setName("CNC"); + schema.setModelName(model.getName() + "XXX"); - Collection<ColorSchema> schemas = new ArrayList<>(); - schemas.add(schema); + Collection<ColorSchema> schemas = new ArrayList<>(); + schemas.add(schema); - ColorModelCommand factory = new ColorModelCommand(model, schemas, colorExtractor); - Map<Object, ColorSchema> map = factory.getModifiedElements(); - assertEquals(0, map.values().size()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + ColorModelCommand factory = new ColorModelCommand(model, schemas, colorExtractor); + Map<Object, ColorSchema> map = factory.getModifiedElements(); + assertEquals(0, map.values().size()); } @Test public void testAliasColoringWithModelMatch() throws Exception { - try { - Model model = getModelForFile("testFiles/sample.xml", false); + Model model = getModelForFile("testFiles/sample.xml", false); - ColorSchema schema = new GenericColorSchema(); - schema.setName("CNC"); - schema.setModelName(model.getName()); + ColorSchema schema = new GenericColorSchema(); + schema.setName("CNC"); + schema.setModelName(model.getName()); - Collection<ColorSchema> schemas = new ArrayList<>(); - schemas.add(schema); + Collection<ColorSchema> schemas = new ArrayList<>(); + schemas.add(schema); - ColorModelCommand factory = new ColorModelCommand(model, schemas, colorExtractor); - Map<Object, ColorSchema> map = factory.getModifiedElements(); - assertEquals(1, map.values().size()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + ColorModelCommand factory = new ColorModelCommand(model, schemas, colorExtractor); + Map<Object, ColorSchema> map = factory.getModifiedElements(); + assertEquals(1, map.values().size()); } public void testAliasColoringWithUnknownElementSourceId() throws Exception { - try { - Model model = getModelForFile("testFiles/sample.xml", false); - - ColorSchema schema = new GenericColorSchema(); - schema.setElementId("xxx"); + Model model = getModelForFile("testFiles/sample.xml", false); - Collection<ColorSchema> schemas = new ArrayList<>(); - schemas.add(schema); + ColorSchema schema = new GenericColorSchema(); + schema.setElementId("xxx"); - ColorModelCommand factory = new ColorModelCommand(model, schemas, colorExtractor); - Map<Object, ColorSchema> map = factory.getModifiedElements(); - assertEquals(0, map.values().size()); + Collection<ColorSchema> schemas = new ArrayList<>(); + schemas.add(schema); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + ColorModelCommand factory = new ColorModelCommand(model, schemas, colorExtractor); + Map<Object, ColorSchema> map = factory.getModifiedElements(); + assertEquals(0, map.values().size()); } @Test public void testAliasColoringWithElementIdMatch() throws Exception { - try { - Model model = getModelForFile("testFiles/sample.xml", false); - - ColorSchema schema = new GenericColorSchema(); - schema.setElementId(model.getElements().iterator().next().getElementId()); + Model model = getModelForFile("testFiles/sample.xml", false); - Collection<ColorSchema> schemas = new ArrayList<>(); - schemas.add(schema); + ColorSchema schema = new GenericColorSchema(); + schema.setElementId(model.getElements().iterator().next().getElementId()); - ColorModelCommand factory = new ColorModelCommand(model, schemas, colorExtractor); - Map<Object, ColorSchema> map = factory.getModifiedElements(); - assertEquals(1, map.values().size()); + Collection<ColorSchema> schemas = new ArrayList<>(); + schemas.add(schema); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + ColorModelCommand factory = new ColorModelCommand(model, schemas, colorExtractor); + Map<Object, ColorSchema> map = factory.getModifiedElements(); + assertEquals(1, map.values().size()); } @Test public void testGetModifiedElements() throws Exception { - try { - Reaction reaction = new Reaction(); - reaction.addMiriamData(new MiriamData(MiriamType.PUBMED, "1234")); + Reaction reaction = new Reaction(); + reaction.addMiriamData(new MiriamData(MiriamType.PUBMED, "1234")); - Model model = new ModelFullIndexed(null); - model.addReaction(reaction); + Model model = new ModelFullIndexed(null); + model.addReaction(reaction); - GenericColorSchema colorSchema = new GenericColorSchema(); - colorSchema.addMiriamData(new MiriamData(MiriamType.PUBMED, "1234")); + GenericColorSchema colorSchema = new GenericColorSchema(); + colorSchema.addMiriamData(new MiriamData(MiriamType.PUBMED, "1234")); - List<ColorSchema> schemas = new ArrayList<>(); - schemas.add(colorSchema); + List<ColorSchema> schemas = new ArrayList<>(); + schemas.add(colorSchema); - ColorModelCommand factory = new ColorModelCommand(model, schemas, colorExtractor); - - assertNotNull(factory.getModifiedElements().get(reaction)); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + ColorModelCommand factory = new ColorModelCommand(model, schemas, colorExtractor); + assertNotNull(factory.getModifiedElements().get(reaction)); } } diff --git a/model-command/src/test/java/lcsb/mapviewer/commands/CommandTestFunctions.java b/model-command/src/test/java/lcsb/mapviewer/commands/CommandTestFunctions.java index 1a835fc4456d50a8e15760b8b04abb6f6eb48637..6ebfaff56f934898cf45db1179a18c9f33f0b034 100644 --- a/model-command/src/test/java/lcsb/mapviewer/commands/CommandTestFunctions.java +++ b/model-command/src/test/java/lcsb/mapviewer/commands/CommandTestFunctions.java @@ -9,7 +9,9 @@ import java.util.List; import java.util.Map; import org.apache.logging.log4j.*; +import org.junit.Rule; +import lcsb.mapviewer.common.UnitTestFailedWatcher; import lcsb.mapviewer.converter.ConverterParams; import lcsb.mapviewer.converter.InvalidInputDataExecption; import lcsb.mapviewer.converter.model.celldesigner.CellDesignerXmlParser; @@ -23,6 +25,9 @@ import lcsb.mapviewer.model.map.species.GenericProtein; public abstract class CommandTestFunctions { public double EPSILON = 1e-6; + @Rule + public UnitTestFailedWatcher unitTestFailedWatcher = new UnitTestFailedWatcher(); + Logger logger = LogManager.getLogger(CommandTestFunctions.class); private static Map<String, Model> models = new HashMap<String, Model>(); diff --git a/model-command/src/test/java/lcsb/mapviewer/commands/CopyCommandTest.java b/model-command/src/test/java/lcsb/mapviewer/commands/CopyCommandTest.java index a85f57116d456515d8cef542cae888dc91e3563e..129cb31e2b97d0754b65e4a9a3a1fddc36482e59 100644 --- a/model-command/src/test/java/lcsb/mapviewer/commands/CopyCommandTest.java +++ b/model-command/src/test/java/lcsb/mapviewer/commands/CopyCommandTest.java @@ -1,17 +1,11 @@ package lcsb.mapviewer.commands; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import java.awt.geom.Point2D; import java.util.Calendar; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import lcsb.mapviewer.common.exception.InvalidArgumentException; import lcsb.mapviewer.model.graphics.PolylineData; @@ -21,20 +15,10 @@ import lcsb.mapviewer.model.map.compartment.SquareCompartment; import lcsb.mapviewer.model.map.kinetics.SbmlFunction; import lcsb.mapviewer.model.map.kinetics.SbmlParameter; import lcsb.mapviewer.model.map.layout.graphics.Layer; -import lcsb.mapviewer.model.map.model.Author; -import lcsb.mapviewer.model.map.model.ElementSubmodelConnection; -import lcsb.mapviewer.model.map.model.Model; -import lcsb.mapviewer.model.map.model.ModelComparator; -import lcsb.mapviewer.model.map.model.ModelFullIndexed; -import lcsb.mapviewer.model.map.model.ModelSubmodelConnection; -import lcsb.mapviewer.model.map.model.SubmodelType; -import lcsb.mapviewer.model.map.reaction.Product; -import lcsb.mapviewer.model.map.reaction.Reactant; -import lcsb.mapviewer.model.map.reaction.Reaction; +import lcsb.mapviewer.model.map.model.*; +import lcsb.mapviewer.model.map.reaction.*; import lcsb.mapviewer.model.map.reaction.type.StateTransitionReaction; -import lcsb.mapviewer.model.map.species.Complex; -import lcsb.mapviewer.model.map.species.Element; -import lcsb.mapviewer.model.map.species.GenericProtein; +import lcsb.mapviewer.model.map.species.*; public class CopyCommandTest extends CommandTestFunctions { @@ -49,241 +33,173 @@ public class CopyCommandTest extends CommandTestFunctions { } @Test - public void testCopyModel() { - try { - Model model = getModelForFile("testFiles/sample.xml", false); - Model copy = new CopyCommand(model).execute(); - - assertEquals(0, comparator.compare(model, copy)); - } catch (Exception e) { - e.printStackTrace(); - fail("exception occurred"); - } + public void testCopyModel() throws Exception { + Model model = getModelForFile("testFiles/sample.xml", false); + Model copy = new CopyCommand(model).execute(); + + assertEquals(0, comparator.compare(model, copy)); } @Test public void testCopyModelWithKinetics() throws Exception { - try { - Model model = getModelForFile("testFiles/kinetics_with_compartment.xml", false); - Model copy = new CopyCommand(model).execute(); - - assertEquals(0, comparator.compare(model, copy)); - for (Reaction reaction : copy.getReactions()) { - if (reaction.getKinetics() != null) { - for (Element element : reaction.getKinetics().getElements()) { - assertTrue("Element in the copy doesn't belong to copy", copy.getElements().contains(element)); - } - for (SbmlFunction function : reaction.getKinetics().getFunctions()) { - assertTrue("Function in the copy doesn't belong to copy", copy.getFunctions().contains(function)); - } - for (SbmlParameter parameter : reaction.getKinetics().getParameters()) { - if (parameter.getParameterId().equals("k2")) { - assertTrue("Global parameter in the function copy doesn't belong to copy", - copy.getParameters().contains(parameter)); - } + Model model = getModelForFile("testFiles/kinetics_with_compartment.xml", false); + Model copy = new CopyCommand(model).execute(); + + assertEquals(0, comparator.compare(model, copy)); + for (Reaction reaction : copy.getReactions()) { + if (reaction.getKinetics() != null) { + for (Element element : reaction.getKinetics().getElements()) { + assertTrue("Element in the copy doesn't belong to copy", copy.getElements().contains(element)); + } + for (SbmlFunction function : reaction.getKinetics().getFunctions()) { + assertTrue("Function in the copy doesn't belong to copy", copy.getFunctions().contains(function)); + } + for (SbmlParameter parameter : reaction.getKinetics().getParameters()) { + if (parameter.getParameterId().equals("k2")) { + assertTrue("Global parameter in the function copy doesn't belong to copy", + copy.getParameters().contains(parameter)); } } } - } catch (Exception e) { - e.printStackTrace(); - throw e; } } @Test public void testCopyCustomModel() { - try { - Model model = new ModelFullIndexed(null); + Model model = new ModelFullIndexed(null); - GenericProtein protein = new GenericProtein("A"); - protein.setNotes(null); + GenericProtein protein = new GenericProtein("A"); + protein.setNotes(null); - model.addElement(protein); + model.addElement(protein); - Model copy = new CopyCommand(model).execute(); + Model copy = new CopyCommand(model).execute(); - assertEquals(0, comparator.compare(model, copy)); - } catch (Exception e) { - e.printStackTrace(); - fail("exception occurred"); - } + assertEquals(0, comparator.compare(model, copy)); } @Test public void testCopyCustomModel2() { - try { - Model model = new ModelFullIndexed(null); - - Complex complexAlias = new Complex("id2"); - GenericProtein protein = new GenericProtein("A"); - protein.setNotes(null); - complexAlias.addSpecies(protein); - model.addElement(protein); - model.addElement(complexAlias); + Model model = new ModelFullIndexed(null); - GenericProtein alias = new GenericProtein("B"); - alias.setNotes(null); + Complex complexAlias = new Complex("id2"); + GenericProtein protein = new GenericProtein("A"); + protein.setNotes(null); + complexAlias.addSpecies(protein); + model.addElement(protein); + model.addElement(complexAlias); - complexAlias.addSpecies(alias); - model.addElement(alias); + GenericProtein alias = new GenericProtein("B"); + alias.setNotes(null); - Model copy = new CopyCommand(model).execute(); + complexAlias.addSpecies(alias); + model.addElement(alias); - assertEquals(0, comparator.compare(model, copy)); + Model copy = new CopyCommand(model).execute(); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, comparator.compare(model, copy)); } @Test public void testCopyModel3() throws Exception { - try { - Model model = getModelForFile("testFiles/complex_with_state.xml", true); + Model model = getModelForFile("testFiles/complex_with_state.xml", true); - Model copy = new CopyCommand(model).execute(); + Model copy = new CopyCommand(model).execute(); - Model copy2 = serializeViaCellDesigner(copy); + Model copy2 = serializeViaCellDesigner(copy); - // check if after conversion to xml everything works - assertEquals(0, comparator.compare(copy, copy2)); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + // check if after conversion to xml everything works + assertEquals(0, comparator.compare(copy, copy2)); } @Test public void testCopyModel4() throws Exception { - try { - Model model = getModelForFile("testFiles/problematic_description.xml", true); + Model model = getModelForFile("testFiles/problematic_description.xml", true); - Model copy = new CopyCommand(model).execute(); + Model copy = new CopyCommand(model).execute(); - Model copy2 = serializeViaCellDesigner(copy); + Model copy2 = serializeViaCellDesigner(copy); - // check if after conversion to xml everything works - assertEquals(0, comparator.compare(copy, copy2)); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + // check if after conversion to xml everything works + assertEquals(0, comparator.compare(copy, copy2)); } @Test public void testCopyModelWithArtifitialAliases() throws Exception { - try { - Model model = getModelForFile("testFiles/artifitial_compartments.xml", false); - new CreateHierarchyCommand(model, 2, 2).execute(); - - Model copy = new CopyCommand(model).execute(); + Model model = getModelForFile("testFiles/artifitial_compartments.xml", false); + new CreateHierarchyCommand(model, 2, 2).execute(); - Model copy2 = serializeViaCellDesigner(copy); + Model copy = new CopyCommand(model).execute(); - new CreateHierarchyCommand(copy2, 2, 2).execute(); + Model copy2 = serializeViaCellDesigner(copy); - // check if after conversion to xml everything works - assertEquals(0, comparator.compare(copy, copy2)); + new CreateHierarchyCommand(copy2, 2, 2).execute(); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + // check if after conversion to xml everything works + assertEquals(0, comparator.compare(copy, copy2)); } @Test public void testCopyModelWithSubmodels() throws Exception { - try { - Model model = getModel(); - Model model2 = getModel(); - model2.setNotes("ASDSA"); - model.addSubmodelConnection(new ModelSubmodelConnection(model2, SubmodelType.DOWNSTREAM_TARGETS)); - Model copy = new CopyCommand(model).execute(); - - assertEquals(0, comparator.compare(model, copy)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Model model = getModel(); + Model model2 = getModel(); + model2.setNotes("ASDSA"); + model.addSubmodelConnection(new ModelSubmodelConnection(model2, SubmodelType.DOWNSTREAM_TARGETS)); + Model copy = new CopyCommand(model).execute(); + + assertEquals(0, comparator.compare(model, copy)); } @Test public void testCopySubmodel() throws Exception { - try { - Model model = getModel(); - Model model2 = getModel(); - model2.setNotes("ASDSA"); - model.addSubmodelConnection(new ModelSubmodelConnection(model2, SubmodelType.DOWNSTREAM_TARGETS, "name a")); - - Model model3 = getModel(); - model3.setNotes("ASDSA"); - model.addSubmodelConnection(new ModelSubmodelConnection(model3, SubmodelType.DOWNSTREAM_TARGETS, "name b")); - Element alias = model2.getElementByElementId("a_id"); - alias.setSubmodel(new ElementSubmodelConnection(model3, SubmodelType.DOWNSTREAM_TARGETS, "name c")); - Model copy = new CopyCommand(model2).execute(); - - assertEquals(0, comparator.compare(model2, copy)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Model model = getModel(); + Model model2 = getModel(); + model2.setNotes("ASDSA"); + model.addSubmodelConnection(new ModelSubmodelConnection(model2, SubmodelType.DOWNSTREAM_TARGETS, "name a")); + + Model model3 = getModel(); + model3.setNotes("ASDSA"); + model.addSubmodelConnection(new ModelSubmodelConnection(model3, SubmodelType.DOWNSTREAM_TARGETS, "name b")); + Element alias = model2.getElementByElementId("a_id"); + alias.setSubmodel(new ElementSubmodelConnection(model3, SubmodelType.DOWNSTREAM_TARGETS, "name c")); + Model copy = new CopyCommand(model2).execute(); + + assertEquals(0, comparator.compare(model2, copy)); } @Test public void testCopyModelWithSubmodels2() throws Exception { - try { - Model model = getModel(); - Model model2 = getModel(); - model2.setNotes("ASDSA2"); - - model.addSubmodelConnection(new ModelSubmodelConnection(model2, SubmodelType.DOWNSTREAM_TARGETS)); - model.getElementByElementId("a_id") - .setSubmodel(new ElementSubmodelConnection(model2, SubmodelType.DOWNSTREAM_TARGETS)); - Model copy = new CopyCommand(model).execute(); - - assertEquals(0, comparator.compare(model, copy)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Model model = getModel(); + Model model2 = getModel(); + model2.setNotes("ASDSA2"); + + model.addSubmodelConnection(new ModelSubmodelConnection(model2, SubmodelType.DOWNSTREAM_TARGETS)); + model.getElementByElementId("a_id") + .setSubmodel(new ElementSubmodelConnection(model2, SubmodelType.DOWNSTREAM_TARGETS)); + Model copy = new CopyCommand(model).execute(); + + assertEquals(0, comparator.compare(model, copy)); } @Test public void testCopyModelWithName() throws Exception { - try { - Model model = getModel(); - model.setName("ASDSA2"); + Model model = getModel(); + model.setName("ASDSA2"); - Model copy = new CopyCommand(model).execute(); + Model copy = new CopyCommand(model).execute(); - assertEquals(0, comparator.compare(model, copy)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, comparator.compare(model, copy)); } - @Test + @Test(expected = InvalidArgumentException.class) public void testCopyModelWithSubmodelsThrowException() throws Exception { - try { - Model model = getModel(); - Model model2 = getModel(); - model2.setNotes("ASDSA2"); - - model.getElementByElementId("a_id") - .setSubmodel(new ElementSubmodelConnection(model2, SubmodelType.DOWNSTREAM_TARGETS)); - try { - new CopyCommand(model).execute(); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - } - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Model model = getModel(); + Model model2 = getModel(); + model2.setNotes("ASDSA2"); + + model.getElementByElementId("a_id") + .setSubmodel(new ElementSubmodelConnection(model2, SubmodelType.DOWNSTREAM_TARGETS)); + new CopyCommand(model).execute(); } private Model getModel() { @@ -311,115 +227,89 @@ public class CopyCommandTest extends CommandTestFunctions { @Test public void testCopyModelReaction() throws Exception { - try { - Model model = new ModelFullIndexed(null); - - Compartment c1 = new SquareCompartment("c1"); - Compartment c2 = new SquareCompartment("c2"); - c1.setVisibilityLevel("2"); - c2.setVisibilityLevel("3"); + Model model = new ModelFullIndexed(null); - model.addElement(c1); - model.addElement(c2); + Compartment c1 = new SquareCompartment("c1"); + Compartment c2 = new SquareCompartment("c2"); + c1.setVisibilityLevel("2"); + c2.setVisibilityLevel("3"); - GenericProtein s1 = new GenericProtein("s1"); - s1.setCompartment(c1); - model.addElement(s1); + model.addElement(c1); + model.addElement(c2); - GenericProtein s2 = new GenericProtein("s2"); - s2.setCompartment(c2); - model.addElement(s2); + GenericProtein s1 = new GenericProtein("s1"); + s1.setCompartment(c1); + model.addElement(s1); - StateTransitionReaction reaction = new StateTransitionReaction(); - Reactant reactant = new Reactant(s1); - reactant.setLine(new PolylineData(new Point2D.Double(0, 0), new Point2D.Double(10, 10))); - reaction.addReactant(reactant); - Product product = new Product(s2); - product.setLine(new PolylineData(new Point2D.Double(10, 0), new Point2D.Double(120, 10))); - reaction.addProduct(product); - reaction.setVisibilityLevel("4"); + GenericProtein s2 = new GenericProtein("s2"); + s2.setCompartment(c2); + model.addElement(s2); - model.addReaction(reaction); + StateTransitionReaction reaction = new StateTransitionReaction(); + Reactant reactant = new Reactant(s1); + reactant.setLine(new PolylineData(new Point2D.Double(0, 0), new Point2D.Double(10, 10))); + reaction.addReactant(reactant); + Product product = new Product(s2); + product.setLine(new PolylineData(new Point2D.Double(10, 0), new Point2D.Double(120, 10))); + reaction.addProduct(product); + reaction.setVisibilityLevel("4"); - assertTrue(s1.equals(reaction.getReactants().get(0).getElement())); - assertTrue(s2.equals(reaction.getProducts().get(0).getElement())); + model.addReaction(reaction); - Model model2 = new CopyCommand(model).execute(); - Reaction reaction2 = model2.getReactions().iterator().next(); + assertTrue(s1.equals(reaction.getReactants().get(0).getElement())); + assertTrue(s2.equals(reaction.getProducts().get(0).getElement())); - assertTrue(s1.equals(reaction.getReactants().get(0).getElement())); - assertTrue(s2.equals(reaction.getProducts().get(0).getElement())); + Model model2 = new CopyCommand(model).execute(); + Reaction reaction2 = model2.getReactions().iterator().next(); - assertFalse(s1.equals(reaction2.getReactants().get(0).getElement())); - assertFalse(s2.equals(reaction2.getProducts().get(0).getElement())); + assertTrue(s1.equals(reaction.getReactants().get(0).getElement())); + assertTrue(s2.equals(reaction.getProducts().get(0).getElement())); - assertNotNull(reaction2.getReactants().get(0).getElement().getCompartment()); - assertNotNull(reaction2.getProducts().get(0).getElement().getCompartment()); + assertFalse(s1.equals(reaction2.getReactants().get(0).getElement())); + assertFalse(s2.equals(reaction2.getProducts().get(0).getElement())); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertNotNull(reaction2.getReactants().get(0).getElement().getCompartment()); + assertNotNull(reaction2.getProducts().get(0).getElement().getCompartment()); } @Test public void testCopyModelWithAuthor() throws Exception { - try { - Model model = getModel(); - model.addAuthor(new Author("Piotr", "G")); + Model model = getModel(); + model.addAuthor(new Author("Piotr", "G")); - Model copy = new CopyCommand(model).execute(); + Model copy = new CopyCommand(model).execute(); - assertEquals(0, comparator.compare(copy, model)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, comparator.compare(copy, model)); } @Test public void testCopyModelWithAnnotations() throws Exception { - try { - Model model = getModel(); - model.addMiriamData(new MiriamData()); + Model model = getModel(); + model.addMiriamData(new MiriamData()); - Model copy = new CopyCommand(model).execute(); + Model copy = new CopyCommand(model).execute(); - assertEquals(0, comparator.compare(copy, model)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, comparator.compare(copy, model)); } @Test public void testCopyModelWithCreationDate() throws Exception { - try { - Model model = getModel(); - model.setCreationDate(Calendar.getInstance()); + Model model = getModel(); + model.setCreationDate(Calendar.getInstance()); - Model copy = new CopyCommand(model).execute(); + Model copy = new CopyCommand(model).execute(); - assertEquals(0, comparator.compare(copy, model)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, comparator.compare(copy, model)); } @Test public void testCopyModelWithModificationDate() throws Exception { - try { - Model model = getModel(); - model.addModificationDate(Calendar.getInstance()); + Model model = getModel(); + model.addModificationDate(Calendar.getInstance()); - Model copy = new CopyCommand(model).execute(); + Model copy = new CopyCommand(model).execute(); - assertEquals(0, comparator.compare(copy, model)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, comparator.compare(copy, model)); } } diff --git a/model-command/src/test/java/lcsb/mapviewer/commands/CreateHierarchyCommandTest.java b/model-command/src/test/java/lcsb/mapviewer/commands/CreateHierarchyCommandTest.java index f1fefd41d7a859ca5f353f2084978ddbbeaf9961..2fd92abf44a74c240efedb7d0f7b30fad1b8ee01 100644 --- a/model-command/src/test/java/lcsb/mapviewer/commands/CreateHierarchyCommandTest.java +++ b/model-command/src/test/java/lcsb/mapviewer/commands/CreateHierarchyCommandTest.java @@ -1,23 +1,15 @@ package lcsb.mapviewer.commands; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.nio.charset.StandardCharsets; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; +import java.util.*; -import org.apache.logging.log4j.*; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.junit.*; import lcsb.mapviewer.common.exception.InvalidStateException; import lcsb.mapviewer.converter.ConverterParams; @@ -42,355 +34,263 @@ public class CreateHierarchyCommandTest extends CommandTestFunctions { @Test public void testCyclicComplexes() throws Exception { - try { - Model model = getModelForFile("testFiles/cyclic_hierarchy_problem.xml", false); + Model model = getModelForFile("testFiles/cyclic_hierarchy_problem.xml", false); - new CreateHierarchyCommand(model, 8, 80).execute(); + new CreateHierarchyCommand(model, 8, 80).execute(); - Species alias = model.getElementByElementId("sa5033"); + Species alias = model.getElementByElementId("sa5033"); - Set<Element> parents = new HashSet<Element>(); - while (alias.getComplex() != null) { - assertFalse("Cyclic nesting", parents.contains(alias.getComplex())); - alias = alias.getComplex(); - parents.add(alias); - } - - Set<String> levels = new HashSet<>(); - for (Element a : model.getElements()) { - levels.add(a.getVisibilityLevel()); - } - assertTrue(levels.size() > 2); + Set<Element> parents = new HashSet<Element>(); + while (alias.getComplex() != null) { + assertFalse("Cyclic nesting", parents.contains(alias.getComplex())); + alias = alias.getComplex(); + parents.add(alias); + } - } catch (Exception e) { - e.printStackTrace(); - throw e; + Set<String> levels = new HashSet<>(); + for (Element a : model.getElements()) { + levels.add(a.getVisibilityLevel()); } + assertTrue(levels.size() > 2); } @Test public void testCreateHierachy() throws Exception { - try { - Model model = getModelForFile("testFiles/artifitial_compartments.xml", false); - - new CreateHierarchyCommand(model, 2, 2).execute(); - // check if second call will throw an exception... - new CreateHierarchyCommand(model, 2, 2).execute(); + Model model = getModelForFile("testFiles/artifitial_compartments.xml", false); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + new CreateHierarchyCommand(model, 2, 2).execute(); + // check if second call will throw an exception... + new CreateHierarchyCommand(model, 2, 2).execute(); } @Test public void testCreateHierachy2() throws Exception { - try { - Model model = getModelForFile("testFiles/artifitial_compartments.xml", false); + Model model = getModelForFile("testFiles/artifitial_compartments.xml", false); - new CreateHierarchyCommand(model, 2, 2).execute(); + new CreateHierarchyCommand(model, 2, 2).execute(); - boolean artifitial = false; - for (Compartment a : model.getCompartments()) { - if (a instanceof PathwayCompartment) { - artifitial = true; - } + boolean artifitial = false; + for (Compartment a : model.getCompartments()) { + if (a instanceof PathwayCompartment) { + artifitial = true; } - assertTrue("No hierarchical structure element found", artifitial); - - } catch (Exception e) { - e.printStackTrace(); - throw e; } + assertTrue("No hierarchical structure element found", artifitial); } @Test public void testRecreateHierachy() throws Exception { - try { - Model model = getModelForFile("testFiles/artifitial_compartments.xml", false); + Model model = getModelForFile("testFiles/artifitial_compartments.xml", false); - int aliasSize0 = model.getCompartments().size(); + int aliasSize0 = model.getCompartments().size(); - new CreateHierarchyCommand(model, 2, 2).execute(); + new CreateHierarchyCommand(model, 2, 2).execute(); - int aliasSize = model.getCompartments().size(); + int aliasSize = model.getCompartments().size(); - assertTrue(aliasSize0 != aliasSize); - new CreateHierarchyCommand(model, 2, 2).execute(); + assertTrue(aliasSize0 != aliasSize); + new CreateHierarchyCommand(model, 2, 2).execute(); - int aliasSize2 = model.getCompartments().size(); + int aliasSize2 = model.getCompartments().size(); - assertEquals(aliasSize, aliasSize2); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(aliasSize, aliasSize2); } @Test public void testParenting() throws Exception { - try { - Model model = getModelForFile("testFiles/artifitial_compartments.xml", false); + Model model = getModelForFile("testFiles/artifitial_compartments.xml", false); - new CreateHierarchyCommand(model, 2, 2).execute(); + new CreateHierarchyCommand(model, 2, 2).execute(); - assertFalse(model.getElementByElementId("sa1").getCompartment() instanceof PathwayCompartment); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertFalse(model.getElementByElementId("sa1").getCompartment() instanceof PathwayCompartment); } @Test public void testCreateComponentsMinVisibility() throws Exception { - try { - double zoomFactor = 39.0625; - int levels = 6; + double zoomFactor = 39.0625; + int levels = 6; - Model model = getModelForFile("testFiles/other_full/GSTP1 subnetwork_220214.xml", false); + Model model = getModelForFile("testFiles/other_full/GSTP1 subnetwork_220214.xml", false); - new CreateHierarchyCommand(model, levels, zoomFactor).execute(); + new CreateHierarchyCommand(model, levels, zoomFactor).execute(); - for (Compartment compartment : model.getCompartments()) { - if (compartment.getCompartment() == null) { - int visibilityLevel = Integer.valueOf(compartment.getVisibilityLevel()); - assertTrue("Alias " + compartment.getElementId() + " is not visible at levels highers than " - + compartment.getVisibilityLevel(), visibilityLevel <= 1); - } + for (Compartment compartment : model.getCompartments()) { + if (compartment.getCompartment() == null) { + int visibilityLevel = Integer.valueOf(compartment.getVisibilityLevel()); + assertTrue("Alias " + compartment.getElementId() + " is not visible at levels highers than " + + compartment.getVisibilityLevel(), visibilityLevel <= 1); } + } - for (Species species : model.getSpeciesList()) { - if (species.getCompartment() == null) { - int visibilityLevel = Integer.valueOf(species.getVisibilityLevel()); - assertTrue("Alias " + species.getElementId() + " is not visible at levels highers than " - + species.getVisibilityLevel(), visibilityLevel <= 1); - } + for (Species species : model.getSpeciesList()) { + if (species.getCompartment() == null) { + int visibilityLevel = Integer.valueOf(species.getVisibilityLevel()); + assertTrue("Alias " + species.getElementId() + " is not visible at levels highers than " + + species.getVisibilityLevel(), visibilityLevel <= 1); } - - } catch (Exception e) { - e.printStackTrace(); - throw e; } } @Test public void testCreateComponentsMaxVisibility() throws Exception { - try { - double zoomFactor = 39.0625; - int levels = 6; + double zoomFactor = 39.0625; + int levels = 6; - Model model = getModelForFile("testFiles/other_full/GSTP1 subnetwork_220214.xml", false); + Model model = getModelForFile("testFiles/other_full/GSTP1 subnetwork_220214.xml", false); - new CreateHierarchyCommand(model, levels, zoomFactor).execute(); - - for (Element element : model.getElements()) { - int visibilityLevel = Integer.valueOf(element.getVisibilityLevel()); - assertTrue("Alias " + element.getElementId() + " is not visible even at the bottom level (visibility: " - + element.getVisibilityLevel() + ") ", visibilityLevel <= levels); - } + new CreateHierarchyCommand(model, levels, zoomFactor).execute(); - } catch (Exception e) { - e.printStackTrace(); - throw e; + for (Element element : model.getElements()) { + int visibilityLevel = Integer.valueOf(element.getVisibilityLevel()); + assertTrue("Alias " + element.getElementId() + " is not visible even at the bottom level (visibility: " + + element.getVisibilityLevel() + ") ", visibilityLevel <= levels); } } @Test public void testCompactComplexesInNestedView() throws Exception { - Model model; - try { - model = getModelForFile("testFiles/problematic/compact_complex_view_problem.xml", false); - Element alias = model.getElementByElementId("sa1"); - Object parent1 = alias.getCompartment(); - new CreateHierarchyCommand(model, 3, 16).execute(); - Object parent2 = alias.getCompartment(); - assertEquals(parent1, parent2); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Model model = getModelForFile("testFiles/problematic/compact_complex_view_problem.xml", false); + Element alias = model.getElementByElementId("sa1"); + Object parent1 = alias.getCompartment(); + new CreateHierarchyCommand(model, 3, 16).execute(); + Object parent2 = alias.getCompartment(); + assertEquals(parent1, parent2); } - @Test + @Test(expected = InvalidStateException.class) public void testRecallHierachyCreation() throws Exception { - try { - Model model = getModelForFile("testFiles/artifitial_compartments.xml", false); - - CreateHierarchyCommand command = new CreateHierarchyCommand(model, 2, 2); - command.execute(); - try { - command.execute(); - fail("Exception expected"); - } catch (InvalidStateException e) { + Model model = getModelForFile("testFiles/artifitial_compartments.xml", false); - } - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + CreateHierarchyCommand command = new CreateHierarchyCommand(model, 2, 2); + command.execute(); + command.execute(); } @Test public void testClear() throws Exception { - try { - Model model = getModelForFile("testFiles/artifitial_compartments.xml", false); + Model model = getModelForFile("testFiles/artifitial_compartments.xml", false); - CreateHierarchyCommand command = new CreateHierarchyCommand(model, 2, 2); - command.clean(); - for (Element alias : model.getElements()) { - assertNull(alias.getCompartment()); - } - for (Compartment alias : model.getCompartments()) { - assertNull(alias.getCompartment()); - assertTrue(alias.getElements().isEmpty()); - } - - } catch (Exception e) { - e.printStackTrace(); - throw e; + CreateHierarchyCommand command = new CreateHierarchyCommand(model, 2, 2); + command.clean(); + for (Element alias : model.getElements()) { + assertNull(alias.getCompartment()); + } + for (Compartment alias : model.getCompartments()) { + assertNull(alias.getCompartment()); + assertTrue(alias.getElements().isEmpty()); } } @Test public void testNestedProblem() throws Exception { - try { - CellDesignerXmlParser parser = new CellDesignerXmlParser(); - Model model = parser - .createModel(new ConverterParams().filename("testFiles/nested_test.xml").sizeAutoAdjust(true)); - - double zoomFactor = Math.max(model.getHeight(), model.getWidth()) / (256); - int zoomLevels = (int) Math.ceil(Math.log(zoomFactor) / Math.log(2)); - - CreateHierarchyCommand command = new CreateHierarchyCommand(model, zoomLevels, zoomFactor); - command.execute(); - - for (Element alias : model.getElements()) { - Element parentAlias = alias.getCompartment(); + CellDesignerXmlParser parser = new CellDesignerXmlParser(); + Model model = parser + .createModel(new ConverterParams().filename("testFiles/nested_test.xml").sizeAutoAdjust(true)); + + double zoomFactor = Math.max(model.getHeight(), model.getWidth()) / (256); + int zoomLevels = (int) Math.ceil(Math.log(zoomFactor) / Math.log(2)); + + CreateHierarchyCommand command = new CreateHierarchyCommand(model, zoomLevels, zoomFactor); + command.execute(); + + for (Element alias : model.getElements()) { + Element parentAlias = alias.getCompartment(); + if (parentAlias != null) { + int parentVisibilityLevel = Integer.valueOf(parentAlias.getVisibilityLevel()); + int aliasVisibilityLevel = Integer.valueOf(alias.getVisibilityLevel()); + assertTrue(aliasVisibilityLevel >= parentVisibilityLevel); + } + if (alias instanceof Species) { + parentAlias = ((Species) alias).getComplex(); if (parentAlias != null) { int parentVisibilityLevel = Integer.valueOf(parentAlias.getVisibilityLevel()); int aliasVisibilityLevel = Integer.valueOf(alias.getVisibilityLevel()); assertTrue(aliasVisibilityLevel >= parentVisibilityLevel); } - if (alias instanceof Species) { - parentAlias = ((Species) alias).getComplex(); - if (parentAlias != null) { - int parentVisibilityLevel = Integer.valueOf(parentAlias.getVisibilityLevel()); - int aliasVisibilityLevel = Integer.valueOf(alias.getVisibilityLevel()); - assertTrue(aliasVisibilityLevel >= parentVisibilityLevel); - } - } } - } catch (Exception e) { - e.printStackTrace(); - throw e; } } @Test public void testDisconnectedChildInComplex() throws Exception { - try { - Model model = getModelForFile("testFiles/problematic/disconnected_child_in_complex.xml", false); + Model model = getModelForFile("testFiles/problematic/disconnected_child_in_complex.xml", false); - new CreateHierarchyCommand(model, 8, 80).execute(); + new CreateHierarchyCommand(model, 8, 80).execute(); - CellDesignerXmlParser parser = new CellDesignerXmlParser(); - String xmlString = parser.model2String(model); - // logger.debug(xmlString); + CellDesignerXmlParser parser = new CellDesignerXmlParser(); + String xmlString = parser.model2String(model); - InputStream stream = new ByteArrayInputStream(xmlString.getBytes(StandardCharsets.UTF_8)); + InputStream stream = new ByteArrayInputStream(xmlString.getBytes(StandardCharsets.UTF_8)); - parser.createModel(new ConverterParams().inputStream(stream)); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + parser.createModel(new ConverterParams().inputStream(stream)); } @Test public void testHierarchyWithCustomSemanticZooming() throws Exception { - try { - Model model = getModelForFile("testFiles/custom_semantic_zooming.xml", false); + Model model = getModelForFile("testFiles/custom_semantic_zooming.xml", false); - Map<Element, String> visibilityLevels = new HashMap<>(); - for (Element element : model.getElements()) { - if (element.getVisibilityLevel() != null && !element.getVisibilityLevel().isEmpty()) { - visibilityLevels.put(element, element.getVisibilityLevel()); - } + Map<Element, String> visibilityLevels = new HashMap<>(); + for (Element element : model.getElements()) { + if (element.getVisibilityLevel() != null && !element.getVisibilityLevel().isEmpty()) { + visibilityLevels.put(element, element.getVisibilityLevel()); } + } - new CreateHierarchyCommand(model, 4, 80).execute(); + new CreateHierarchyCommand(model, 4, 80).execute(); - for (Element element : model.getElements()) { - if (visibilityLevels.get(element) != null) { - assertEquals("Visibility level changed, but shouldn't", visibilityLevels.get(element), - element.getVisibilityLevel()); - } + for (Element element : model.getElements()) { + if (visibilityLevels.get(element) != null) { + assertEquals("Visibility level changed, but shouldn't", visibilityLevels.get(element), + element.getVisibilityLevel()); } - - } catch (Exception e) { - e.printStackTrace(); - throw e; } } @Test public void testHierarchyWithCustomSemanticZoomingPathwayLevels() throws Exception { - try { - ElementUtils eu = new ElementUtils(); - Model model = getModelForFile("testFiles/custom_semantic_zooming.xml", false); - - Map<Element, String> visibilityLevels = new HashMap<>(); - for (Element element : model.getElements()) { - if (element.getVisibilityLevel() != null && !element.getVisibilityLevel().isEmpty()) { - visibilityLevels.put(element, element.getVisibilityLevel()); - } + ElementUtils eu = new ElementUtils(); + Model model = getModelForFile("testFiles/custom_semantic_zooming.xml", false); + + Map<Element, String> visibilityLevels = new HashMap<>(); + for (Element element : model.getElements()) { + if (element.getVisibilityLevel() != null && !element.getVisibilityLevel().isEmpty()) { + visibilityLevels.put(element, element.getVisibilityLevel()); } + } - new CreateHierarchyCommand(model, 4, 80).execute(); - - for (Element element : model.getElements()) { - if (visibilityLevels.get(element) == null) { - int visibilityLevel = Integer.parseInt(element.getVisibilityLevel()); - if (element.getCompartment() != null) { - int parentTransparency = Integer.parseInt(element.getCompartment().getTransparencyLevel()); - assertEquals( - eu.getElementTag(element) + eu.getElementTag(element.getCompartment()) - + "Element should be directly visible when parent is transparent", - parentTransparency, visibilityLevel); - } else if (element instanceof Species) { - int parentTransparency = Integer.parseInt(((Species) element).getComplex().getTransparencyLevel()); - assertEquals( - eu.getElementTag(element) + eu.getElementTag(((Species) element).getComplex()) - + "Element should be directly visible when parent is transparent", - parentTransparency, visibilityLevel); - } + new CreateHierarchyCommand(model, 4, 80).execute(); + + for (Element element : model.getElements()) { + if (visibilityLevels.get(element) == null) { + int visibilityLevel = Integer.parseInt(element.getVisibilityLevel()); + if (element.getCompartment() != null) { + int parentTransparency = Integer.parseInt(element.getCompartment().getTransparencyLevel()); + assertEquals( + eu.getElementTag(element) + eu.getElementTag(element.getCompartment()) + + "Element should be directly visible when parent is transparent", + parentTransparency, visibilityLevel); + } else if (element instanceof Species) { + int parentTransparency = Integer.parseInt(((Species) element).getComplex().getTransparencyLevel()); + assertEquals( + eu.getElementTag(element) + eu.getElementTag(((Species) element).getComplex()) + + "Element should be directly visible when parent is transparent", + parentTransparency, visibilityLevel); } } - - } catch (Exception e) { - e.printStackTrace(); - throw e; } } @Test public void testLayerWithNotes() throws Exception { - try { - Model model = getModelForFile("testFiles/layer_text_with_notes.xml", false); + Model model = getModelForFile("testFiles/layer_text_with_notes.xml", false); - new CreateHierarchyCommand(model, 4, 80).execute(); + new CreateHierarchyCommand(model, 4, 80).execute(); - PathwayCompartment pathway = (PathwayCompartment) model.getCompartments().get(0); + PathwayCompartment pathway = (PathwayCompartment) model.getCompartments().get(0); - assertEquals("test", pathway.getName()); - assertEquals("5", pathway.getVisibilityLevel()); - assertEquals((Integer)11, pathway.getZ()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals("test", pathway.getName()); + assertEquals("5", pathway.getVisibilityLevel()); + assertEquals((Integer) 11, pathway.getZ()); } } diff --git a/model-command/src/test/java/lcsb/mapviewer/commands/MoveElementsCommandTest.java b/model-command/src/test/java/lcsb/mapviewer/commands/MoveElementsCommandTest.java index efc14fabd446a75566b134306fdf54b86caedeb7..f903edd67deb62938a1b938bbfa957db1eabf77b 100644 --- a/model-command/src/test/java/lcsb/mapviewer/commands/MoveElementsCommandTest.java +++ b/model-command/src/test/java/lcsb/mapviewer/commands/MoveElementsCommandTest.java @@ -1,18 +1,12 @@ package lcsb.mapviewer.commands; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import java.awt.geom.Rectangle2D; import java.util.ArrayList; import java.util.List; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.mockito.Mockito; import lcsb.mapviewer.common.Configuration; @@ -37,243 +31,206 @@ public class MoveElementsCommandTest extends CommandTestFunctions { @Test public void testMoveAlias() throws Exception { - try { - Model model = getModelForFile("testFiles/spliting_test_Case.xml", false); - Model model2 = getModelForFile("testFiles/spliting_test_Case.xml", false); - Element alias = model.getElementByElementId("sa2"); - Element alias2 = model.getElementByElementId("sa1"); - double anotherAliasX = alias2.getX(); - double anotherAliasY = alias2.getY(); - - List<BioEntity> list = new ArrayList<>(); - list.add(alias); - double x = alias.getX(); - double y = alias.getY(); - - double dx = 10; - double dy = 2; - - // models should be equal before move - assertEquals(0, modelComparator.compare(model, model2)); - - MoveElementsCommand moveCommand = new MoveElementsCommand(model, list, dx, dy); - moveCommand.execute(); - - // after move models should be different - assertTrue(0 != modelComparator.compare(model, model2)); - - // check new coordinates - assertEquals(x + dx, alias.getX(), Configuration.EPSILON); - assertEquals(y + dy, alias.getY(), Configuration.EPSILON); - - // and check if another alias didn't change coordinates - assertEquals(anotherAliasX, alias2.getX(), Configuration.EPSILON); - assertEquals(anotherAliasY, alias2.getY(), Configuration.EPSILON); - - list = new ArrayList<>(); - list.add(model2.getElementByElementId("sa2")); - MoveElementsCommand moveCommand2 = new MoveElementsCommand(model2, list, dx, dy); - moveCommand2.execute(); - - // if we perfomr the same operator on the second model then they should be - // equal - assertEquals(0, modelComparator.compare(model, model2)); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Model model = getModelForFile("testFiles/spliting_test_Case.xml", false); + Model model2 = getModelForFile("testFiles/spliting_test_Case.xml", false); + Element alias = model.getElementByElementId("sa2"); + Element alias2 = model.getElementByElementId("sa1"); + double anotherAliasX = alias2.getX(); + double anotherAliasY = alias2.getY(); + + List<BioEntity> list = new ArrayList<>(); + list.add(alias); + double x = alias.getX(); + double y = alias.getY(); + + double dx = 10; + double dy = 2; + + // models should be equal before move + assertEquals(0, modelComparator.compare(model, model2)); + + MoveElementsCommand moveCommand = new MoveElementsCommand(model, list, dx, dy); + moveCommand.execute(); + + // after move models should be different + assertTrue(0 != modelComparator.compare(model, model2)); + + // check new coordinates + assertEquals(x + dx, alias.getX(), Configuration.EPSILON); + assertEquals(y + dy, alias.getY(), Configuration.EPSILON); + + // and check if another alias didn't change coordinates + assertEquals(anotherAliasX, alias2.getX(), Configuration.EPSILON); + assertEquals(anotherAliasY, alias2.getY(), Configuration.EPSILON); + + list = new ArrayList<>(); + list.add(model2.getElementByElementId("sa2")); + MoveElementsCommand moveCommand2 = new MoveElementsCommand(model2, list, dx, dy); + moveCommand2.execute(); + + // if we perform the same operator on the second model then they should be + // equal + assertEquals(0, modelComparator.compare(model, model2)); } - @Test + @Test(expected = InvalidArgumentException.class) public void testMoveSpecies() throws Exception { - try { - Model model = getModelForFile("testFiles/spliting_test_Case.xml", false); - List<BioEntity> list = new ArrayList<>(); - list.add(Mockito.mock(BioEntity.class)); - - MoveElementsCommand moveCommand = new MoveElementsCommand(model, list, 10, 10); - moveCommand.execute(); - fail("Exception expected"); - - } catch (InvalidArgumentException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Model model = getModelForFile("testFiles/spliting_test_Case.xml", false); + List<BioEntity> list = new ArrayList<>(); + list.add(Mockito.mock(BioEntity.class)); + + MoveElementsCommand moveCommand = new MoveElementsCommand(model, list, 10, 10); + moveCommand.execute(); } @Test public void testAliasWithReaction() throws Exception { - try { - Model model = getModelForFile("testFiles/spliting_test_Case.xml", false); - Model model2 = getModelForFile("testFiles/spliting_test_Case.xml", false); - Element alias = model.getElementByElementId("sa1"); - Element alias2 = model.getElementByElementId("sa2"); - double anotherAliasX = alias2.getX(); - double anotherAliasY = alias2.getY(); - Reaction reaction = model.getReactionByReactionId("re1"); - - List<BioEntity> list = new ArrayList<>(); - list.add(alias); - double x = reaction.getReactants().get(0).getLine().getBeginPoint().getX(); - double y = reaction.getReactants().get(0).getLine().getBeginPoint().getY(); - - double dx = 10; - double dy = 2; - - // models should be equal before move - assertEquals(0, modelComparator.compare(model, model2)); - - MoveElementsCommand moveCommand = new MoveElementsCommand(model, list, dx, dy); - moveCommand.execute(); - - // after move models should be different - assertTrue(0 != modelComparator.compare(model, model2)); - - // check new coordinates of reaction - assertEquals(x + dx, reaction.getReactants().get(0).getLine().getBeginPoint().getX(), Configuration.EPSILON); - assertEquals(y + dy, reaction.getReactants().get(0).getLine().getBeginPoint().getY(), Configuration.EPSILON); - - // and check if another alias didn't change coordinates - assertEquals(anotherAliasX, alias2.getX(), Configuration.EPSILON); - assertEquals(anotherAliasY, alias2.getY(), Configuration.EPSILON); - - list = new ArrayList<>(); - list.add(model2.getElementByElementId("sa1")); - MoveElementsCommand moveCommand2 = new MoveElementsCommand(model2, list, dx, dy); - moveCommand2.execute(); - - // if we perfomr the same operator on the second model then they should be - // equal - assertEquals(0, modelComparator.compare(model, model2)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Model model = getModelForFile("testFiles/spliting_test_Case.xml", false); + Model model2 = getModelForFile("testFiles/spliting_test_Case.xml", false); + Element alias = model.getElementByElementId("sa1"); + Element alias2 = model.getElementByElementId("sa2"); + double anotherAliasX = alias2.getX(); + double anotherAliasY = alias2.getY(); + Reaction reaction = model.getReactionByReactionId("re1"); + + List<BioEntity> list = new ArrayList<>(); + list.add(alias); + double x = reaction.getReactants().get(0).getLine().getBeginPoint().getX(); + double y = reaction.getReactants().get(0).getLine().getBeginPoint().getY(); + + double dx = 10; + double dy = 2; + + // models should be equal before move + assertEquals(0, modelComparator.compare(model, model2)); + + MoveElementsCommand moveCommand = new MoveElementsCommand(model, list, dx, dy); + moveCommand.execute(); + + // after move models should be different + assertTrue(0 != modelComparator.compare(model, model2)); + + // check new coordinates of reaction + assertEquals(x + dx, reaction.getReactants().get(0).getLine().getBeginPoint().getX(), Configuration.EPSILON); + assertEquals(y + dy, reaction.getReactants().get(0).getLine().getBeginPoint().getY(), Configuration.EPSILON); + + // and check if another alias didn't change coordinates + assertEquals(anotherAliasX, alias2.getX(), Configuration.EPSILON); + assertEquals(anotherAliasY, alias2.getY(), Configuration.EPSILON); + + list = new ArrayList<>(); + list.add(model2.getElementByElementId("sa1")); + MoveElementsCommand moveCommand2 = new MoveElementsCommand(model2, list, dx, dy); + moveCommand2.execute(); + + // if we perform the same operator on the second model then they should be + // equal + assertEquals(0, modelComparator.compare(model, model2)); } @Test public void testMoveReaction() throws Exception { - try { - Model model = getModelForFile("testFiles/spliting_test_Case.xml", false); - Element alias2 = model.getElementByElementId("sa1"); - double anotherAliasX = alias2.getX(); - double anotherAliasY = alias2.getY(); - Reaction reaction = model.getReactionByReactionId("re1"); - - List<BioEntity> list = new ArrayList<>(); - list.add(reaction); - double x = reaction.getReactants().get(0).getLine().getBeginPoint().getX(); - double y = reaction.getReactants().get(0).getLine().getBeginPoint().getY(); - - double x2 = reaction.getReactants().get(0).getLine().getEndPoint().getX(); - double y2 = reaction.getReactants().get(0).getLine().getEndPoint().getY(); - - double dx = 10; - double dy = 2; - - MoveElementsCommand moveCommand = new MoveElementsCommand(model, list, dx, dy); - moveCommand.execute(); - - // check new coordinates of reaction (point attached to alias shouldn't - // move, the one not attached should move) - assertEquals(x, reaction.getReactants().get(0).getLine().getBeginPoint().getX(), Configuration.EPSILON); - assertEquals(y, reaction.getReactants().get(0).getLine().getBeginPoint().getY(), Configuration.EPSILON); - assertEquals(x2 + dx, reaction.getReactants().get(0).getLine().getEndPoint().getX(), Configuration.EPSILON); - assertEquals(y2 + dy, reaction.getReactants().get(0).getLine().getEndPoint().getY(), Configuration.EPSILON); - - // and check if another alias didn't change coordinates - assertEquals(anotherAliasX, alias2.getX(), Configuration.EPSILON); - assertEquals(anotherAliasY, alias2.getY(), Configuration.EPSILON); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Model model = getModelForFile("testFiles/spliting_test_Case.xml", false); + Element alias2 = model.getElementByElementId("sa1"); + double anotherAliasX = alias2.getX(); + double anotherAliasY = alias2.getY(); + Reaction reaction = model.getReactionByReactionId("re1"); + + List<BioEntity> list = new ArrayList<>(); + list.add(reaction); + double x = reaction.getReactants().get(0).getLine().getBeginPoint().getX(); + double y = reaction.getReactants().get(0).getLine().getBeginPoint().getY(); + + double x2 = reaction.getReactants().get(0).getLine().getEndPoint().getX(); + double y2 = reaction.getReactants().get(0).getLine().getEndPoint().getY(); + + double dx = 10; + double dy = 2; + + MoveElementsCommand moveCommand = new MoveElementsCommand(model, list, dx, dy); + moveCommand.execute(); + + // check new coordinates of reaction (point attached to alias shouldn't + // move, the one not attached should move) + assertEquals(x, reaction.getReactants().get(0).getLine().getBeginPoint().getX(), Configuration.EPSILON); + assertEquals(y, reaction.getReactants().get(0).getLine().getBeginPoint().getY(), Configuration.EPSILON); + assertEquals(x2 + dx, reaction.getReactants().get(0).getLine().getEndPoint().getX(), Configuration.EPSILON); + assertEquals(y2 + dy, reaction.getReactants().get(0).getLine().getEndPoint().getY(), Configuration.EPSILON); + + // and check if another alias didn't change coordinates + assertEquals(anotherAliasX, alias2.getX(), Configuration.EPSILON); + assertEquals(anotherAliasY, alias2.getY(), Configuration.EPSILON); } @Test public void testUndo() throws Exception { - try { - Model model = getModelForFile("testFiles/spliting_test_Case.xml", false); - Model model2 = getModelForFile("testFiles/spliting_test_Case.xml", false); - Element alias = model.getElementByElementId("sa2"); - - List<BioEntity> list = new ArrayList<>(); - list.add(alias); + Model model = getModelForFile("testFiles/spliting_test_Case.xml", false); + Model model2 = getModelForFile("testFiles/spliting_test_Case.xml", false); + Element alias = model.getElementByElementId("sa2"); - double dx = 10; - double dy = 2; + List<BioEntity> list = new ArrayList<>(); + list.add(alias); - // models should be equal before move - assertEquals(0, modelComparator.compare(model, model2)); + double dx = 10; + double dy = 2; - MoveElementsCommand moveCommand = new MoveElementsCommand(model, list, dx, dy); - moveCommand.execute(); + // models should be equal before move + assertEquals(0, modelComparator.compare(model, model2)); - // after move models should be different - assertTrue(0 != modelComparator.compare(model, model2)); + MoveElementsCommand moveCommand = new MoveElementsCommand(model, list, dx, dy); + moveCommand.execute(); - // undo command - moveCommand.undo(); + // after move models should be different + assertTrue(0 != modelComparator.compare(model, model2)); - // after undo they should be the same again - assertEquals(0, modelComparator.compare(model, model2)); + // undo command + moveCommand.undo(); - moveCommand.redo(); + // after undo they should be the same again + assertEquals(0, modelComparator.compare(model, model2)); - // after redo they should be different again - assertTrue(0 != modelComparator.compare(model, model2)); + moveCommand.redo(); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + // after redo they should be different again + assertTrue(0 != modelComparator.compare(model, model2)); } @Test public void testGetAffectedRegion() throws Exception { - try { - Model model = getModelForFile("testFiles/spliting_test_Case.xml", false); - Element alias = model.getElementByElementId("sa2"); - - List<BioEntity> list = new ArrayList<>(); - list.add(alias); - double x = alias.getX(); - double y = alias.getY(); - - double dx = 10; - double dy = 2; - - double minx = x; - double maxx = alias.getWidth() + x + dx; - - double miny = y; - double maxy = alias.getHeight() + y + dy; - - MoveElementsCommand moveCommand = new MoveElementsCommand(model, list, dx, dy); - assertNull(moveCommand.getAffectedRegion()); - moveCommand.execute(); - assertNotNull(moveCommand.getAffectedRegion()); - Rectangle2D affectedRegion = moveCommand.getAffectedRegion(); - assertEquals(minx, affectedRegion.getX(), Configuration.EPSILON); - assertEquals(miny, affectedRegion.getY(), Configuration.EPSILON); - assertEquals(maxx, affectedRegion.getX() + affectedRegion.getWidth(), Configuration.EPSILON); - assertEquals(maxy, affectedRegion.getY() + affectedRegion.getHeight(), Configuration.EPSILON); - - moveCommand.undo(); - - affectedRegion = moveCommand.getAffectedRegion(); - assertEquals(minx, affectedRegion.getX(), Configuration.EPSILON); - assertEquals(miny, affectedRegion.getY(), Configuration.EPSILON); - assertEquals(maxx, affectedRegion.getX() + affectedRegion.getWidth(), Configuration.EPSILON); - assertEquals(maxy, affectedRegion.getY() + affectedRegion.getHeight(), Configuration.EPSILON); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Model model = getModelForFile("testFiles/spliting_test_Case.xml", false); + Element alias = model.getElementByElementId("sa2"); + + List<BioEntity> list = new ArrayList<>(); + list.add(alias); + double x = alias.getX(); + double y = alias.getY(); + + double dx = 10; + double dy = 2; + + double minx = x; + double maxx = alias.getWidth() + x + dx; + + double miny = y; + double maxy = alias.getHeight() + y + dy; + + MoveElementsCommand moveCommand = new MoveElementsCommand(model, list, dx, dy); + assertNull(moveCommand.getAffectedRegion()); + moveCommand.execute(); + assertNotNull(moveCommand.getAffectedRegion()); + Rectangle2D affectedRegion = moveCommand.getAffectedRegion(); + assertEquals(minx, affectedRegion.getX(), Configuration.EPSILON); + assertEquals(miny, affectedRegion.getY(), Configuration.EPSILON); + assertEquals(maxx, affectedRegion.getX() + affectedRegion.getWidth(), Configuration.EPSILON); + assertEquals(maxy, affectedRegion.getY() + affectedRegion.getHeight(), Configuration.EPSILON); + + moveCommand.undo(); + + affectedRegion = moveCommand.getAffectedRegion(); + assertEquals(minx, affectedRegion.getX(), Configuration.EPSILON); + assertEquals(miny, affectedRegion.getY(), Configuration.EPSILON); + assertEquals(maxx, affectedRegion.getX() + affectedRegion.getWidth(), Configuration.EPSILON); + assertEquals(maxy, affectedRegion.getY() + affectedRegion.getHeight(), Configuration.EPSILON); } } diff --git a/model-command/src/test/java/lcsb/mapviewer/commands/SubModelCommandTest.java b/model-command/src/test/java/lcsb/mapviewer/commands/SubModelCommandTest.java index 9eba9df40af74dcbb81f71aa7f649ba7a453b240..881e2d9e3d5849c88104c329a082263094539fab 100644 --- a/model-command/src/test/java/lcsb/mapviewer/commands/SubModelCommandTest.java +++ b/model-command/src/test/java/lcsb/mapviewer/commands/SubModelCommandTest.java @@ -1,15 +1,12 @@ package lcsb.mapviewer.commands; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; +import static org.junit.Assert.*; import java.awt.geom.Path2D; import java.util.Arrays; import java.util.HashSet; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import lcsb.mapviewer.model.map.model.Model; import lcsb.mapviewer.model.map.model.ModelComparator; @@ -28,203 +25,158 @@ public class SubModelCommandTest extends CommandTestFunctions { @Test public void testGetSubmodel1() throws Exception { - try { - Model model = getModelForFile("testFiles/spliting_test_Case.xml", true); + Model model = getModelForFile("testFiles/spliting_test_Case.xml", true); - Path2D polygon = new Path2D.Double(); - polygon.moveTo(0, 0); - polygon.lineTo(0, 100); - polygon.lineTo(100, 100); - polygon.lineTo(100, 0); - polygon.closePath(); + Path2D polygon = new Path2D.Double(); + polygon.moveTo(0, 0); + polygon.lineTo(0, 100); + polygon.lineTo(100, 100); + polygon.lineTo(100, 0); + polygon.closePath(); - Model copy = new SubModelCommand(model, polygon).execute(); + Model copy = new SubModelCommand(model, polygon).execute(); - assertEquals(2, copy.getElements().size()); - assertEquals(0, copy.getReactions().size()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(2, copy.getElements().size()); + assertEquals(0, copy.getReactions().size()); } @Test public void testGetSubmodel2() throws Exception { - try { - Model model = getModelForFile("testFiles/spliting_test_Case.xml", true); - - Path2D polygon = new Path2D.Double(); - polygon.moveTo(50, 50); - polygon.lineTo(350, 50); - polygon.lineTo(350, 200); - polygon.lineTo(50, 200); - polygon.closePath(); + Model model = getModelForFile("testFiles/spliting_test_Case.xml", true); - Model copy = new SubModelCommand(model, polygon).execute(); + Path2D polygon = new Path2D.Double(); + polygon.moveTo(50, 50); + polygon.lineTo(350, 50); + polygon.lineTo(350, 200); + polygon.lineTo(50, 200); + polygon.closePath(); - assertEquals(9, copy.getElements().size()); - assertEquals(1, copy.getReactions().size()); + Model copy = new SubModelCommand(model, polygon).execute(); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(9, copy.getElements().size()); + assertEquals(1, copy.getReactions().size()); } @Test public void testGetSubmodel3() throws Exception { - try { - Model model = getModelForFile("testFiles/spliting_test_Case.xml", true); + Model model = getModelForFile("testFiles/spliting_test_Case.xml", true); - Path2D polygon = new Path2D.Double(); - polygon.moveTo(0, 200); - polygon.lineTo(350, 200); - polygon.lineTo(350, 400); - polygon.lineTo(0, 400); - polygon.closePath(); + Path2D polygon = new Path2D.Double(); + polygon.moveTo(0, 200); + polygon.lineTo(350, 200); + polygon.lineTo(350, 400); + polygon.lineTo(0, 400); + polygon.closePath(); - Model copy = new SubModelCommand(model, polygon).execute(); + Model copy = new SubModelCommand(model, polygon).execute(); - double dx = 10; - double dy = -10; + double dx = 10; + double dy = -10; - new MoveCommand(copy, dx, dy).execute(); + new MoveCommand(copy, dx, dy).execute(); - assertEquals(model.getElementByElementId("sa3").getCenterX(), copy.getElementByElementId("sa3").getCenterX() - dx, - EPSILON); - assertEquals(model.getElementByElementId("sa3").getCenterY(), copy.getElementByElementId("sa3").getCenterY() - dy, - EPSILON); + assertEquals(model.getElementByElementId("sa3").getCenterX(), copy.getElementByElementId("sa3").getCenterX() - dx, + EPSILON); + assertEquals(model.getElementByElementId("sa3").getCenterY(), copy.getElementByElementId("sa3").getCenterY() - dy, + EPSILON); - assertEquals(model.getReactionByReactionId("re3").getLines().get(0).getX2(), - copy.getReactionByReactionId("re3").getLines().get(0).getX2() - dx, EPSILON); - assertEquals(model.getReactionByReactionId("re3").getLines().get(0).getY2(), - copy.getReactionByReactionId("re3").getLines().get(0).getY2() - dy, EPSILON); + assertEquals(model.getReactionByReactionId("re3").getLines().get(0).getX2(), + copy.getReactionByReactionId("re3").getLines().get(0).getX2() - dx, EPSILON); + assertEquals(model.getReactionByReactionId("re3").getLines().get(0).getY2(), + copy.getReactionByReactionId("re3").getLines().get(0).getY2() - dy, EPSILON); - Model copy2 = serializeViaCellDesigner(copy); + Model copy2 = serializeViaCellDesigner(copy); - // check if after conversion to xml everything works - assertEquals(0, comparator.compare(copy, copy2)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + // check if after conversion to xml everything works + assertEquals(0, comparator.compare(copy, copy2)); } @Test public void testGetSubmodelWithoutCompartments() throws Exception { - try { - Model model = getModelForFile("testFiles/compartments.xml", true); - - Path2D polygon = new Path2D.Double(); - polygon.moveTo(0, 10); - polygon.lineTo(10, 10); - polygon.lineTo(10, 0); - polygon.lineTo(0, 0); - polygon.closePath(); - - Model copy = new SubModelCommand(model, polygon).execute(); - - // we should cut off some of compartmets - assertFalse(model.getLayers().iterator().next().getTexts().size() == copy.getLayers().iterator().next().getTexts() - .size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Model model = getModelForFile("testFiles/compartments.xml", true); + + Path2D polygon = new Path2D.Double(); + polygon.moveTo(0, 10); + polygon.lineTo(10, 10); + polygon.lineTo(10, 0); + polygon.lineTo(0, 0); + polygon.closePath(); + + Model copy = new SubModelCommand(model, polygon).execute(); + + // we should cut off some of compartments + assertFalse(model.getLayers().iterator().next().getTexts().size() == copy.getLayers().iterator().next().getTexts() + .size()); } @Test public void testGetSubmodelWithoutCompartments2() throws Exception { - try { - Model model = getModelForFile("testFiles/problematic/cutting_without_compartment.xml", true); + Model model = getModelForFile("testFiles/problematic/cutting_without_compartment.xml", true); - Path2D polygon = new Path2D.Double(); - polygon.moveTo(0, 0); - polygon.lineTo(0, 500); - polygon.lineTo(300, 500); - polygon.lineTo(300, 0); - polygon.closePath(); + Path2D polygon = new Path2D.Double(); + polygon.moveTo(0, 0); + polygon.lineTo(0, 500); + polygon.lineTo(300, 500); + polygon.lineTo(300, 0); + polygon.closePath(); - Model copy = new SubModelCommand(model, polygon).execute(); + Model copy = new SubModelCommand(model, polygon).execute(); - Model model2 = serializeViaCellDesigner(copy); + Model model2 = serializeViaCellDesigner(copy); - assertEquals(0, comparator.compare(copy, model2)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, comparator.compare(copy, model2)); } @Test public void testGetSubmodelWithElementIds() throws Exception { - try { - Model model = getModelForFile("testFiles/spliting_test_Case.xml", false); - - Path2D polygon = new Path2D.Double(); - polygon.moveTo(0, 0); - polygon.lineTo(0, 1000); - polygon.lineTo(1000, 1000); - polygon.lineTo(1000, 0); - polygon.closePath(); - model.getElementByElementId("sa2").setId(-2); - - Model copy = new SubModelCommand(model, polygon, new HashSet<>(Arrays.asList(-2)), new HashSet<>()).execute(); - - assertEquals(1, copy.getElements().size()); - assertEquals(0, copy.getReactions().size()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Model model = getModelForFile("testFiles/spliting_test_Case.xml", false); + + Path2D polygon = new Path2D.Double(); + polygon.moveTo(0, 0); + polygon.lineTo(0, 1000); + polygon.lineTo(1000, 1000); + polygon.lineTo(1000, 0); + polygon.closePath(); + model.getElementByElementId("sa2").setId(-2); + + Model copy = new SubModelCommand(model, polygon, new HashSet<>(Arrays.asList(-2)), new HashSet<>()).execute(); + + assertEquals(1, copy.getElements().size()); + assertEquals(0, copy.getReactions().size()); } @Test public void testGetSubmodelWithEmptyElementIds() throws Exception { - try { - Model model = getModelForFile("testFiles/spliting_test_Case.xml", true); + Model model = getModelForFile("testFiles/spliting_test_Case.xml", true); - Path2D polygon = new Path2D.Double(); - polygon.moveTo(0, 0); - polygon.lineTo(0, 1000); - polygon.lineTo(1000, 1000); - polygon.lineTo(1000, 0); - polygon.closePath(); + Path2D polygon = new Path2D.Double(); + polygon.moveTo(0, 0); + polygon.lineTo(0, 1000); + polygon.lineTo(1000, 1000); + polygon.lineTo(1000, 0); + polygon.closePath(); - Model copy = new SubModelCommand(model, polygon, new HashSet<>(), new HashSet<>()).execute(); + Model copy = new SubModelCommand(model, polygon, new HashSet<>(), new HashSet<>()).execute(); - assertEquals(12, copy.getElements().size()); - assertEquals(3, copy.getReactions().size()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(12, copy.getElements().size()); + assertEquals(3, copy.getReactions().size()); } @Test public void testGetSubmodelWithReactionIds() throws Exception { - try { - Model model = getModelForFile("testFiles/spliting_test_Case.xml", false); - - Path2D polygon = new Path2D.Double(); - polygon.moveTo(0, 0); - polygon.lineTo(0, 1000); - polygon.lineTo(1000, 1000); - polygon.lineTo(1000, 0); - polygon.closePath(); - model.getReactions().iterator().next().setId(-2); + Model model = getModelForFile("testFiles/spliting_test_Case.xml", false); - Model copy = new SubModelCommand(model, polygon, new HashSet<>(), new HashSet<>(Arrays.asList(-2))).execute(); + Path2D polygon = new Path2D.Double(); + polygon.moveTo(0, 0); + polygon.lineTo(0, 1000); + polygon.lineTo(1000, 1000); + polygon.lineTo(1000, 0); + polygon.closePath(); + model.getReactions().iterator().next().setId(-2); - assertEquals(1, copy.getReactions().size()); + Model copy = new SubModelCommand(model, polygon, new HashSet<>(), new HashSet<>(Arrays.asList(-2))).execute(); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(1, copy.getReactions().size()); } } diff --git a/model-command/src/test/java/lcsb/mapviewer/commands/layout/ApplySimpleLayoutModelCommandTest.java b/model-command/src/test/java/lcsb/mapviewer/commands/layout/ApplySimpleLayoutModelCommandTest.java index dd03de11c56133a579030f0fe0e1f94f795cb202..5f7b6931d716bd37b45a727205b2098a0f6ceb53 100644 --- a/model-command/src/test/java/lcsb/mapviewer/commands/layout/ApplySimpleLayoutModelCommandTest.java +++ b/model-command/src/test/java/lcsb/mapviewer/commands/layout/ApplySimpleLayoutModelCommandTest.java @@ -1,22 +1,14 @@ package lcsb.mapviewer.commands.layout; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -import java.awt.geom.Dimension2D; -import java.awt.geom.Point2D; -import java.awt.geom.Rectangle2D; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashSet; -import java.util.List; -import java.util.Set; +import static org.junit.Assert.*; + +import java.awt.geom.*; +import java.util.*; import org.junit.Test; import lcsb.mapviewer.commands.CommandExecutionException; +import lcsb.mapviewer.commands.CommandTestFunctions; import lcsb.mapviewer.common.Configuration; import lcsb.mapviewer.common.geometry.DoubleDimension; import lcsb.mapviewer.model.map.BioEntity; @@ -24,18 +16,12 @@ import lcsb.mapviewer.model.map.compartment.Compartment; import lcsb.mapviewer.model.map.compartment.SquareCompartment; import lcsb.mapviewer.model.map.model.Model; import lcsb.mapviewer.model.map.model.ModelFullIndexed; -import lcsb.mapviewer.model.map.reaction.Product; -import lcsb.mapviewer.model.map.reaction.Reactant; -import lcsb.mapviewer.model.map.reaction.Reaction; +import lcsb.mapviewer.model.map.reaction.*; import lcsb.mapviewer.model.map.reaction.type.TransportReaction; -import lcsb.mapviewer.model.map.species.Complex; -import lcsb.mapviewer.model.map.species.Element; -import lcsb.mapviewer.model.map.species.GenericProtein; -import lcsb.mapviewer.model.map.species.Protein; -import lcsb.mapviewer.model.map.species.Species; +import lcsb.mapviewer.model.map.species.*; import lcsb.mapviewer.model.map.species.field.Residue; -public class ApplySimpleLayoutModelCommandTest { +public class ApplySimpleLayoutModelCommandTest extends CommandTestFunctions { private int counter; @@ -382,26 +368,20 @@ public class ApplySimpleLayoutModelCommandTest { @Test public void testApplyLayoutForReaction() throws CommandExecutionException { - try { - Model model = new ModelFullIndexed(null); - Protein protein = createProtein(); - model.addElement(protein); - Protein protein2 = createProtein(); - model.addElement(protein2); - - Reaction reaction = createReaction(protein, protein2); - model.addReaction(reaction); - - ApplySimpleLayoutModelCommand layoutModelCommand = new ApplySimpleLayoutModelCommand(model); - layoutModelCommand.execute(); - assertNotNull("Reactant doesn't have line", reaction.getReactants().get(0).getLine()); - assertNotNull("Product doesn't have line", reaction.getProducts().get(0).getLine()); - assertNotNull("Reaction doesn't have line", reaction.getLine()); - } catch (CommandExecutionException e) { - e.printStackTrace(); - throw e; - } + Model model = new ModelFullIndexed(null); + Protein protein = createProtein(); + model.addElement(protein); + Protein protein2 = createProtein(); + model.addElement(protein2); + Reaction reaction = createReaction(protein, protein2); + model.addReaction(reaction); + + ApplySimpleLayoutModelCommand layoutModelCommand = new ApplySimpleLayoutModelCommand(model); + layoutModelCommand.execute(); + assertNotNull("Reactant doesn't have line", reaction.getReactants().get(0).getLine()); + assertNotNull("Product doesn't have line", reaction.getProducts().get(0).getLine()); + assertNotNull("Reaction doesn't have line", reaction.getLine()); } private Reaction createReaction(Protein protein, Protein protein2) { diff --git a/model-command/src/test/java/lcsb/mapviewer/commands/properties/ChangeElementAbbreviationCommandTest.java b/model-command/src/test/java/lcsb/mapviewer/commands/properties/ChangeElementAbbreviationCommandTest.java index 9ae8adbad767d8a5eb104893b6aff595dafd6537..14844186d5710806a44cd9c770e1a170766f63e1 100644 --- a/model-command/src/test/java/lcsb/mapviewer/commands/properties/ChangeElementAbbreviationCommandTest.java +++ b/model-command/src/test/java/lcsb/mapviewer/commands/properties/ChangeElementAbbreviationCommandTest.java @@ -1,75 +1,62 @@ package lcsb.mapviewer.commands.properties; import static org.junit.Assert.*; + +import org.junit.*; + import lcsb.mapviewer.commands.CommandTestFunctions; import lcsb.mapviewer.model.map.model.Model; import lcsb.mapviewer.model.map.model.ModelComparator; import lcsb.mapviewer.model.map.species.Element; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -public class ChangeElementAbbreviationCommandTest extends CommandTestFunctions{ - - Model model; - - ModelComparator modelComparator= new ModelComparator(); - - @Before - public void setUp() throws Exception { - model = createSimpleModel(); - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testChangeAliasAbbreviation() throws Exception { - try { - Element alias = model.getElementByElementId("alias_id"); - ChangeElementAbbreviationCommand command = new ChangeElementAbbreviationCommand(model, alias, "test"); - assertFalse("test".equalsIgnoreCase(alias.getAbbreviation())); - command.execute(); - assertTrue(alias.getAbbreviation().equalsIgnoreCase("test")); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testUndo() throws Exception { - try { - Model model2 = createSimpleModel(); - Element alias = model.getElementByElementId("alias_id"); - - // models should be equal before move - assertEquals(0, modelComparator.compare(model, model2)); - - ChangeElementAbbreviationCommand command = new ChangeElementAbbreviationCommand(model, alias, "test"); - command.execute(); - - // after move models should be different - assertTrue(0 != modelComparator.compare(model, model2)); - - // undo command - command.undo(); - - // after undo they should be the same again - assertEquals(0, modelComparator.compare(model, model2)); - - command.redo(); - - // after redo they should be different again - assertTrue(0 != modelComparator.compare(model, model2)); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } +public class ChangeElementAbbreviationCommandTest extends CommandTestFunctions { + + Model model; + + ModelComparator modelComparator = new ModelComparator(); + + @Before + public void setUp() throws Exception { + model = createSimpleModel(); + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testChangeAliasAbbreviation() throws Exception { + Element alias = model.getElementByElementId("alias_id"); + ChangeElementAbbreviationCommand command = new ChangeElementAbbreviationCommand(model, alias, "test"); + assertFalse("test".equalsIgnoreCase(alias.getAbbreviation())); + command.execute(); + assertTrue(alias.getAbbreviation().equalsIgnoreCase("test")); + } + + @Test + public void testUndo() throws Exception { + Model model2 = createSimpleModel(); + Element alias = model.getElementByElementId("alias_id"); + + // models should be equal before move + assertEquals(0, modelComparator.compare(model, model2)); + + ChangeElementAbbreviationCommand command = new ChangeElementAbbreviationCommand(model, alias, "test"); + command.execute(); + + // after move models should be different + assertTrue(0 != modelComparator.compare(model, model2)); + + // undo command + command.undo(); + + // after undo they should be the same again + assertEquals(0, modelComparator.compare(model, model2)); + + command.redo(); + + // after redo they should be different again + assertTrue(0 != modelComparator.compare(model, model2)); + } } diff --git a/model-command/src/test/java/lcsb/mapviewer/commands/properties/ChangeElementColorCommandTest.java b/model-command/src/test/java/lcsb/mapviewer/commands/properties/ChangeElementColorCommandTest.java index f8e0b3c3190ee7107cd93f70ed68bd3bb58f603c..38fe93c7bbe7c51f2b88613796e9353fe9bb1f29 100644 --- a/model-command/src/test/java/lcsb/mapviewer/commands/properties/ChangeElementColorCommandTest.java +++ b/model-command/src/test/java/lcsb/mapviewer/commands/properties/ChangeElementColorCommandTest.java @@ -4,75 +4,61 @@ import static org.junit.Assert.*; import java.awt.Color; +import org.junit.*; + import lcsb.mapviewer.commands.CommandTestFunctions; import lcsb.mapviewer.model.map.model.Model; import lcsb.mapviewer.model.map.model.ModelComparator; import lcsb.mapviewer.model.map.species.Element; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - public class ChangeElementColorCommandTest extends CommandTestFunctions { - Model model; - - ModelComparator modelComparator = new ModelComparator(); - - @Before - public void setUp() throws Exception { - model = createSimpleModel(); - } + Model model; - @After - public void tearDown() throws Exception { - } + ModelComparator modelComparator = new ModelComparator(); - @Test - public void testChangeAliasColor() throws Exception { - try { - Element alias = model.getElementByElementId("alias_id"); - ChangeElementColorCommand command = new ChangeElementColorCommand(model, alias, Color.PINK); - assertFalse(alias.getColor().equals(Color.PINK)); - command.execute(); - assertTrue(alias.getColor().equals(Color.PINK)); + @Before + public void setUp() throws Exception { + model = createSimpleModel(); + } - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } + @After + public void tearDown() throws Exception { + } - @Test - public void testUndo() throws Exception { - try { - Model model2 = createSimpleModel(); - Element alias = model.getElementByElementId("alias_id"); + @Test + public void testChangeAliasColor() throws Exception { + Element alias = model.getElementByElementId("alias_id"); + ChangeElementColorCommand command = new ChangeElementColorCommand(model, alias, Color.PINK); + assertFalse(alias.getColor().equals(Color.PINK)); + command.execute(); + assertTrue(alias.getColor().equals(Color.PINK)); + } - // models should be equal before move - assertEquals(0, modelComparator.compare(model, model2)); + @Test + public void testUndo() throws Exception { + Model model2 = createSimpleModel(); + Element alias = model.getElementByElementId("alias_id"); - ChangeElementColorCommand command = new ChangeElementColorCommand(model, alias, Color.PINK); - command.execute(); + // models should be equal before move + assertEquals(0, modelComparator.compare(model, model2)); - // after move models should be different - assertTrue(0 != modelComparator.compare(model, model2)); + ChangeElementColorCommand command = new ChangeElementColorCommand(model, alias, Color.PINK); + command.execute(); - // undo command - command.undo(); + // after move models should be different + assertTrue(0 != modelComparator.compare(model, model2)); - // after undo they should be the same again - assertEquals(0, modelComparator.compare(model, model2)); + // undo command + command.undo(); - command.redo(); + // after undo they should be the same again + assertEquals(0, modelComparator.compare(model, model2)); - // after redo they should be different again - assertTrue(0 != modelComparator.compare(model, model2)); + command.redo(); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } + // after redo they should be different again + assertTrue(0 != modelComparator.compare(model, model2)); + } } diff --git a/model-command/src/test/java/lcsb/mapviewer/commands/properties/ChangeElementFontSizeCommandTest.java b/model-command/src/test/java/lcsb/mapviewer/commands/properties/ChangeElementFontSizeCommandTest.java index 29a6e22e2185209d5779e87b28808e5c8d84dac8..d5f86ca396180b3842148f2c773aaddb2f71933f 100644 --- a/model-command/src/test/java/lcsb/mapviewer/commands/properties/ChangeElementFontSizeCommandTest.java +++ b/model-command/src/test/java/lcsb/mapviewer/commands/properties/ChangeElementFontSizeCommandTest.java @@ -1,75 +1,62 @@ package lcsb.mapviewer.commands.properties; import static org.junit.Assert.*; + +import org.junit.*; + import lcsb.mapviewer.commands.CommandTestFunctions; import lcsb.mapviewer.model.map.model.Model; import lcsb.mapviewer.model.map.model.ModelComparator; import lcsb.mapviewer.model.map.species.Element; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -public class ChangeElementFontSizeCommandTest extends CommandTestFunctions{ - - Model model; - - ModelComparator modelComparator= new ModelComparator(); - - @Before - public void setUp() throws Exception { - model = createSimpleModel(); - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testChangeAliasFontSize() throws Exception { - try { - Element alias = model.getElementByElementId("alias_id"); - ChangeElementFontSizeCommand command = new ChangeElementFontSizeCommand(model, alias, 15.0); - assertFalse(alias.getFontSize().equals(15.0)); - command.execute(); - assertTrue(alias.getFontSize().equals(15.0)); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testUndo() throws Exception { - try { - Model model2 = createSimpleModel(); - Element alias = model.getElementByElementId("alias_id"); - - // models should be equal before move - assertEquals(0, modelComparator.compare(model, model2)); - - ChangeElementFontSizeCommand command = new ChangeElementFontSizeCommand(model, alias, 15.0); - command.execute(); - - // after move models should be different - assertTrue(0 != modelComparator.compare(model, model2)); - - // undo command - command.undo(); - - // after undo they should be the same again - assertEquals(0, modelComparator.compare(model, model2)); - - command.redo(); - - // after redo they should be different again - assertTrue(0 != modelComparator.compare(model, model2)); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } +public class ChangeElementFontSizeCommandTest extends CommandTestFunctions { + + Model model; + + ModelComparator modelComparator = new ModelComparator(); + + @Before + public void setUp() throws Exception { + model = createSimpleModel(); + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testChangeAliasFontSize() throws Exception { + Element alias = model.getElementByElementId("alias_id"); + ChangeElementFontSizeCommand command = new ChangeElementFontSizeCommand(model, alias, 15.0); + assertFalse(alias.getFontSize().equals(15.0)); + command.execute(); + assertTrue(alias.getFontSize().equals(15.0)); + } + + @Test + public void testUndo() throws Exception { + Model model2 = createSimpleModel(); + Element alias = model.getElementByElementId("alias_id"); + + // models should be equal before move + assertEquals(0, modelComparator.compare(model, model2)); + + ChangeElementFontSizeCommand command = new ChangeElementFontSizeCommand(model, alias, 15.0); + command.execute(); + + // after move models should be different + assertTrue(0 != modelComparator.compare(model, model2)); + + // undo command + command.undo(); + + // after undo they should be the same again + assertEquals(0, modelComparator.compare(model, model2)); + + command.redo(); + + // after redo they should be different again + assertTrue(0 != modelComparator.compare(model, model2)); + } } diff --git a/model-command/src/test/java/lcsb/mapviewer/commands/properties/ChangeElementFormerSymbolCommandTest.java b/model-command/src/test/java/lcsb/mapviewer/commands/properties/ChangeElementFormerSymbolCommandTest.java index 3d96d5e87d697f90c7b911e02d5999a2f9b341a0..74762f248b27b0aea9ac2764a2aae0ac6867a6fd 100644 --- a/model-command/src/test/java/lcsb/mapviewer/commands/properties/ChangeElementFormerSymbolCommandTest.java +++ b/model-command/src/test/java/lcsb/mapviewer/commands/properties/ChangeElementFormerSymbolCommandTest.java @@ -1,44 +1,37 @@ package lcsb.mapviewer.commands.properties; import static org.junit.Assert.*; + +import org.junit.*; + import lcsb.mapviewer.commands.CommandTestFunctions; import lcsb.mapviewer.model.map.model.Model; import lcsb.mapviewer.model.map.model.ModelComparator; import lcsb.mapviewer.model.map.species.Element; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - public class ChangeElementFormerSymbolCommandTest extends CommandTestFunctions { - Model model; - - ModelComparator modelComparator = new ModelComparator(); - - @Before - public void setUp() throws Exception { - model = createSimpleModel(); - } + Model model; - @After - public void tearDown() throws Exception { - } + ModelComparator modelComparator = new ModelComparator(); + @Before + public void setUp() throws Exception { + model = createSimpleModel(); + } - @Test - public void testChangeToTheSame() throws Exception { - try { - Element alias = model.getElementByElementId("alias_id"); - ChangeElementFormerSymbolCommand command = new ChangeElementFormerSymbolCommand(model, alias, "f_symbol","f_symbol"); - assertTrue(alias.getFormerSymbols().contains("f_symbol")); - command.execute(); - assertTrue(alias.getFormerSymbols().contains("f_symbol")); + @After + public void tearDown() throws Exception { + } - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } + @Test + public void testChangeToTheSame() throws Exception { + Element alias = model.getElementByElementId("alias_id"); + ChangeElementFormerSymbolCommand command = new ChangeElementFormerSymbolCommand(model, alias, "f_symbol", + "f_symbol"); + assertTrue(alias.getFormerSymbols().contains("f_symbol")); + command.execute(); + assertTrue(alias.getFormerSymbols().contains("f_symbol")); + } } diff --git a/model-command/src/test/java/lcsb/mapviewer/commands/properties/ChangeElementFormulaCommandTest.java b/model-command/src/test/java/lcsb/mapviewer/commands/properties/ChangeElementFormulaCommandTest.java index d4a9b62beb06b759e5fd743f0ebbd06f67eda8ca..82dc9333043851cc2531d637e9adadf964d5866a 100644 --- a/model-command/src/test/java/lcsb/mapviewer/commands/properties/ChangeElementFormulaCommandTest.java +++ b/model-command/src/test/java/lcsb/mapviewer/commands/properties/ChangeElementFormulaCommandTest.java @@ -1,75 +1,62 @@ package lcsb.mapviewer.commands.properties; import static org.junit.Assert.*; + +import org.junit.*; + import lcsb.mapviewer.commands.CommandTestFunctions; import lcsb.mapviewer.model.map.model.Model; import lcsb.mapviewer.model.map.model.ModelComparator; import lcsb.mapviewer.model.map.species.Element; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -public class ChangeElementFormulaCommandTest extends CommandTestFunctions{ - - Model model; - - ModelComparator modelComparator= new ModelComparator(); - - @Before - public void setUp() throws Exception { - model = createSimpleModel(); - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testChangeAliasFormula() throws Exception { - try { - Element alias = model.getElementByElementId("alias_id"); - ChangeElementFormulaCommand command = new ChangeElementFormulaCommand(model, alias, "test"); - assertFalse("test".equals(alias.getFormula())); - command.execute(); - assertTrue(alias.getFormula().equalsIgnoreCase("test")); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testUndo() throws Exception { - try { - Model model2 = createSimpleModel(); - Element alias = model.getElementByElementId("alias_id"); - - // models should be equal before move - assertEquals(0, modelComparator.compare(model, model2)); - - ChangeElementFormulaCommand command = new ChangeElementFormulaCommand(model, alias, "test"); - command.execute(); - - // after move models should be different - assertTrue(0 != modelComparator.compare(model, model2)); - - // undo command - command.undo(); - - // after undo they should be the same again - assertEquals(0, modelComparator.compare(model, model2)); - - command.redo(); - - // after redo they should be different again - assertTrue(0 != modelComparator.compare(model, model2)); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } +public class ChangeElementFormulaCommandTest extends CommandTestFunctions { + + Model model; + + ModelComparator modelComparator = new ModelComparator(); + + @Before + public void setUp() throws Exception { + model = createSimpleModel(); + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testChangeAliasFormula() throws Exception { + Element alias = model.getElementByElementId("alias_id"); + ChangeElementFormulaCommand command = new ChangeElementFormulaCommand(model, alias, "test"); + assertFalse("test".equals(alias.getFormula())); + command.execute(); + assertTrue(alias.getFormula().equalsIgnoreCase("test")); + } + + @Test + public void testUndo() throws Exception { + Model model2 = createSimpleModel(); + Element alias = model.getElementByElementId("alias_id"); + + // models should be equal before move + assertEquals(0, modelComparator.compare(model, model2)); + + ChangeElementFormulaCommand command = new ChangeElementFormulaCommand(model, alias, "test"); + command.execute(); + + // after move models should be different + assertTrue(0 != modelComparator.compare(model, model2)); + + // undo command + command.undo(); + + // after undo they should be the same again + assertEquals(0, modelComparator.compare(model, model2)); + + command.redo(); + + // after redo they should be different again + assertTrue(0 != modelComparator.compare(model, model2)); + } } diff --git a/model-command/src/test/java/lcsb/mapviewer/commands/properties/ChangeElementFullNameCommandTest.java b/model-command/src/test/java/lcsb/mapviewer/commands/properties/ChangeElementFullNameCommandTest.java index 48647ec2c7fd37bf85274819599f04e31b80c046..47736a862eb5187281dd8e71d514d3323c0ab924 100644 --- a/model-command/src/test/java/lcsb/mapviewer/commands/properties/ChangeElementFullNameCommandTest.java +++ b/model-command/src/test/java/lcsb/mapviewer/commands/properties/ChangeElementFullNameCommandTest.java @@ -1,75 +1,62 @@ package lcsb.mapviewer.commands.properties; import static org.junit.Assert.*; + +import org.junit.*; + import lcsb.mapviewer.commands.CommandTestFunctions; import lcsb.mapviewer.model.map.model.Model; import lcsb.mapviewer.model.map.model.ModelComparator; import lcsb.mapviewer.model.map.species.Element; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -public class ChangeElementFullNameCommandTest extends CommandTestFunctions{ - - Model model; - - ModelComparator modelComparator= new ModelComparator(); - - @Before - public void setUp() throws Exception { - model = createSimpleModel(); - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testChangeAliasFullName() throws Exception { - try { - Element alias = model.getElementByElementId("alias_id"); - ChangeElementFullNameCommand command = new ChangeElementFullNameCommand(model, alias, "test"); - assertFalse("test".equals(alias.getFullName())); - command.execute(); - assertTrue(alias.getFullName().equalsIgnoreCase("test")); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testUndo() throws Exception { - try { - Model model2 = createSimpleModel(); - Element alias = model.getElementByElementId("alias_id"); - - // models should be equal before move - assertEquals(0, modelComparator.compare(model, model2)); - - ChangeElementFullNameCommand command = new ChangeElementFullNameCommand(model, alias, "test"); - command.execute(); - - // after move models should be different - assertTrue(0 != modelComparator.compare(model, model2)); - - // undo command - command.undo(); - - // after undo they should be the same again - assertEquals(0, modelComparator.compare(model, model2)); - - command.redo(); - - // after redo they should be different again - assertTrue(0 != modelComparator.compare(model, model2)); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } +public class ChangeElementFullNameCommandTest extends CommandTestFunctions { + + Model model; + + ModelComparator modelComparator = new ModelComparator(); + + @Before + public void setUp() throws Exception { + model = createSimpleModel(); + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testChangeAliasFullName() throws Exception { + Element alias = model.getElementByElementId("alias_id"); + ChangeElementFullNameCommand command = new ChangeElementFullNameCommand(model, alias, "test"); + assertFalse("test".equals(alias.getFullName())); + command.execute(); + assertTrue(alias.getFullName().equalsIgnoreCase("test")); + } + + @Test + public void testUndo() throws Exception { + Model model2 = createSimpleModel(); + Element alias = model.getElementByElementId("alias_id"); + + // models should be equal before move + assertEquals(0, modelComparator.compare(model, model2)); + + ChangeElementFullNameCommand command = new ChangeElementFullNameCommand(model, alias, "test"); + command.execute(); + + // after move models should be different + assertTrue(0 != modelComparator.compare(model, model2)); + + // undo command + command.undo(); + + // after undo they should be the same again + assertEquals(0, modelComparator.compare(model, model2)); + + command.redo(); + + // after redo they should be different again + assertTrue(0 != modelComparator.compare(model, model2)); + } } diff --git a/model-command/src/test/java/lcsb/mapviewer/commands/properties/ChangeElementMiriamDataCommandTest.java b/model-command/src/test/java/lcsb/mapviewer/commands/properties/ChangeElementMiriamDataCommandTest.java index b00c1a09197831026b5e33f9468d767a2a61ed36..a0b467ff2f01f0979469df0b9aca7c6d8f922d7b 100644 --- a/model-command/src/test/java/lcsb/mapviewer/commands/properties/ChangeElementMiriamDataCommandTest.java +++ b/model-command/src/test/java/lcsb/mapviewer/commands/properties/ChangeElementMiriamDataCommandTest.java @@ -1,6 +1,9 @@ package lcsb.mapviewer.commands.properties; import static org.junit.Assert.*; + +import org.junit.*; + import lcsb.mapviewer.commands.CommandExecutionException; import lcsb.mapviewer.commands.CommandTestFunctions; import lcsb.mapviewer.model.map.MiriamData; @@ -8,81 +11,59 @@ import lcsb.mapviewer.model.map.MiriamType; import lcsb.mapviewer.model.map.model.Model; import lcsb.mapviewer.model.map.species.Element; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - public class ChangeElementMiriamDataCommandTest extends CommandTestFunctions { - Model model; - - @Before - public void setUp() throws Exception { - model = createSimpleModel(); - } + Model model; - @After - public void tearDown() throws Exception { - } + @Before + public void setUp() throws Exception { + model = createSimpleModel(); + } - @Test - public void testWithoutChange() throws Exception { - try { - Element alias = model.getElementByElementId("alias_id"); - MiriamData md = new MiriamData(MiriamType.HGNC_SYMBOL, "SNCA"); - MiriamData md2 = new MiriamData(MiriamType.HGNC_SYMBOL, "SNCA"); - alias.addMiriamData(md); - ChangeElementMiriamDataCommand command = new ChangeElementMiriamDataCommand(model, alias, md2, md); - command.execute(); - assertTrue(alias.getMiriamData().contains(md2)); - assertEquals(1, alias.getMiriamData().size()); + @After + public void tearDown() throws Exception { + } - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } + @Test + public void testWithoutChange() throws Exception { + Element alias = model.getElementByElementId("alias_id"); + MiriamData md = new MiriamData(MiriamType.HGNC_SYMBOL, "SNCA"); + MiriamData md2 = new MiriamData(MiriamType.HGNC_SYMBOL, "SNCA"); + alias.addMiriamData(md); + ChangeElementMiriamDataCommand command = new ChangeElementMiriamDataCommand(model, alias, md2, md); + command.execute(); + assertTrue(alias.getMiriamData().contains(md2)); + assertEquals(1, alias.getMiriamData().size()); + } - @Test - public void testInvalidChange() throws Exception { - try { - Element alias = model.getElementByElementId("alias_id"); - MiriamData md = new MiriamData(MiriamType.HGNC_SYMBOL, "SNCA"); - MiriamData md2 = new MiriamData(MiriamType.HGNC_SYMBOL, "SNCA2"); - alias.addMiriamData(md); - alias.addMiriamData(md2); - ChangeElementMiriamDataCommand command = new ChangeElementMiriamDataCommand(model, alias, md2, md); - try { - command.execute(); - fail("Exception expected"); - } catch (CommandExecutionException e) { - assertTrue(alias.getMiriamData().contains(md)); - assertTrue(alias.getMiriamData().contains(md2)); - } - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - + @Test + public void testInvalidChange() throws Exception { + Element alias = model.getElementByElementId("alias_id"); + MiriamData md = new MiriamData(MiriamType.HGNC_SYMBOL, "SNCA"); + MiriamData md2 = new MiriamData(MiriamType.HGNC_SYMBOL, "SNCA2"); + alias.addMiriamData(md); + alias.addMiriamData(md2); + ChangeElementMiriamDataCommand command = new ChangeElementMiriamDataCommand(model, alias, md2, md); + try { + command.execute(); + fail("Exception expected"); + } catch (CommandExecutionException e) { + assertTrue(alias.getMiriamData().contains(md)); + assertTrue(alias.getMiriamData().contains(md2)); + } + } - @Test - public void testChange() throws Exception { - try { - Element alias = model.getElementByElementId("alias_id"); - MiriamData md = new MiriamData(MiriamType.HGNC_SYMBOL, "SNCA"); - MiriamData md2 = new MiriamData(MiriamType.HGNC_SYMBOL, "SNCA2"); - MiriamData md3 = new MiriamData(MiriamType.HGNC_SYMBOL, "SNCA"); - alias.addMiriamData(md); - ChangeElementMiriamDataCommand command = new ChangeElementMiriamDataCommand(model, alias, md2, md); - command.execute(); - assertTrue(alias.getMiriamData().contains(md2)); - assertFalse(alias.getMiriamData().contains(md3)); + @Test + public void testChange() throws Exception { + Element alias = model.getElementByElementId("alias_id"); + MiriamData md = new MiriamData(MiriamType.HGNC_SYMBOL, "SNCA"); + MiriamData md2 = new MiriamData(MiriamType.HGNC_SYMBOL, "SNCA2"); + MiriamData md3 = new MiriamData(MiriamType.HGNC_SYMBOL, "SNCA"); + alias.addMiriamData(md); + ChangeElementMiriamDataCommand command = new ChangeElementMiriamDataCommand(model, alias, md2, md); + command.execute(); + assertTrue(alias.getMiriamData().contains(md2)); + assertFalse(alias.getMiriamData().contains(md3)); + } - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - } diff --git a/model-command/src/test/java/lcsb/mapviewer/commands/properties/ChangeElementNameCommandTest.java b/model-command/src/test/java/lcsb/mapviewer/commands/properties/ChangeElementNameCommandTest.java index a8d6643ba8b40d526014b4f1b6344e453835271d..6540c45d91d9e93d69ca9ff63e02b295391f468d 100644 --- a/model-command/src/test/java/lcsb/mapviewer/commands/properties/ChangeElementNameCommandTest.java +++ b/model-command/src/test/java/lcsb/mapviewer/commands/properties/ChangeElementNameCommandTest.java @@ -1,77 +1,62 @@ package lcsb.mapviewer.commands.properties; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.Assert.*; + +import org.junit.*; + import lcsb.mapviewer.commands.CommandTestFunctions; import lcsb.mapviewer.model.map.model.Model; import lcsb.mapviewer.model.map.model.ModelComparator; import lcsb.mapviewer.model.map.species.Element; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - public class ChangeElementNameCommandTest extends CommandTestFunctions { - - Model model; - - ModelComparator modelComparator= new ModelComparator(); - - @Before - public void setUp() throws Exception { - model = createSimpleModel(); - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testChangeAliasName() throws Exception { - try { - Element alias = model.getElementByElementId("alias_id"); - ChangeElementNameCommand command = new ChangeElementNameCommand(model, alias, "test"); - assertFalse(alias.getName().equalsIgnoreCase("test")); - command.execute(); - assertTrue(alias.getName().equalsIgnoreCase("test")); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testUndo() throws Exception { - try { - Model model2 = createSimpleModel(); - Element alias = model.getElementByElementId("alias_id"); - - // models should be equal before move - assertEquals(0, modelComparator.compare(model, model2)); - - ChangeElementNameCommand command = new ChangeElementNameCommand(model, alias, "test"); - command.execute(); - - // after move models should be different - assertTrue(0 != modelComparator.compare(model, model2)); - - // undo command - command.undo(); - - // after undo they should be the same again - assertEquals(0, modelComparator.compare(model, model2)); - - command.redo(); - - // after redo they should be different again - assertTrue(0 != modelComparator.compare(model, model2)); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } + + Model model; + + ModelComparator modelComparator = new ModelComparator(); + + @Before + public void setUp() throws Exception { + model = createSimpleModel(); + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testChangeAliasName() throws Exception { + Element alias = model.getElementByElementId("alias_id"); + ChangeElementNameCommand command = new ChangeElementNameCommand(model, alias, "test"); + assertFalse(alias.getName().equalsIgnoreCase("test")); + command.execute(); + assertTrue(alias.getName().equalsIgnoreCase("test")); + } + + @Test + public void testUndo() throws Exception { + Model model2 = createSimpleModel(); + Element alias = model.getElementByElementId("alias_id"); + + // models should be equal before move + assertEquals(0, modelComparator.compare(model, model2)); + + ChangeElementNameCommand command = new ChangeElementNameCommand(model, alias, "test"); + command.execute(); + + // after move models should be different + assertTrue(0 != modelComparator.compare(model, model2)); + + // undo command + command.undo(); + + // after undo they should be the same again + assertEquals(0, modelComparator.compare(model, model2)); + + command.redo(); + + // after redo they should be different again + assertTrue(0 != modelComparator.compare(model, model2)); + } } diff --git a/model-command/src/test/java/lcsb/mapviewer/commands/properties/ChangeElementNotesCommandTest.java b/model-command/src/test/java/lcsb/mapviewer/commands/properties/ChangeElementNotesCommandTest.java index a2189d27ae8e80dbfa085d76ff35726eaa49b87f..1bb0fde0a9cd007543d9adc7e17568fa36ccd2bb 100644 --- a/model-command/src/test/java/lcsb/mapviewer/commands/properties/ChangeElementNotesCommandTest.java +++ b/model-command/src/test/java/lcsb/mapviewer/commands/properties/ChangeElementNotesCommandTest.java @@ -1,75 +1,62 @@ package lcsb.mapviewer.commands.properties; import static org.junit.Assert.*; + +import org.junit.*; + import lcsb.mapviewer.commands.CommandTestFunctions; import lcsb.mapviewer.model.map.model.Model; import lcsb.mapviewer.model.map.model.ModelComparator; import lcsb.mapviewer.model.map.species.Element; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -public class ChangeElementNotesCommandTest extends CommandTestFunctions{ - - Model model; - - ModelComparator modelComparator= new ModelComparator(); - - @Before - public void setUp() throws Exception { - model = createSimpleModel(); - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testChangeAliasNotes() throws Exception { - try { - Element alias = model.getElementByElementId("alias_id"); - ChangeElementNotesCommand command = new ChangeElementNotesCommand(model, alias, "test"); - assertFalse("test".equals(alias.getNotes())); - command.execute(); - assertTrue(alias.getNotes().equalsIgnoreCase("test")); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testUndo() throws Exception { - try { - Model model2 = createSimpleModel(); - Element alias = model.getElementByElementId("alias_id"); - - // models should be equal before move - assertEquals(0, modelComparator.compare(model, model2)); - - ChangeElementNotesCommand command = new ChangeElementNotesCommand(model, alias, "test"); - command.execute(); - - // after move models should be different - assertTrue(0 != modelComparator.compare(model, model2)); - - // undo command - command.undo(); - - // after undo they should be the same again - assertEquals(0, modelComparator.compare(model, model2)); - - command.redo(); - - // after redo they should be different again - assertTrue(0 != modelComparator.compare(model, model2)); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } +public class ChangeElementNotesCommandTest extends CommandTestFunctions { + + Model model; + + ModelComparator modelComparator = new ModelComparator(); + + @Before + public void setUp() throws Exception { + model = createSimpleModel(); + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testChangeAliasNotes() throws Exception { + Element alias = model.getElementByElementId("alias_id"); + ChangeElementNotesCommand command = new ChangeElementNotesCommand(model, alias, "test"); + assertFalse("test".equals(alias.getNotes())); + command.execute(); + assertTrue(alias.getNotes().equalsIgnoreCase("test")); + } + + @Test + public void testUndo() throws Exception { + Model model2 = createSimpleModel(); + Element alias = model.getElementByElementId("alias_id"); + + // models should be equal before move + assertEquals(0, modelComparator.compare(model, model2)); + + ChangeElementNotesCommand command = new ChangeElementNotesCommand(model, alias, "test"); + command.execute(); + + // after move models should be different + assertTrue(0 != modelComparator.compare(model, model2)); + + // undo command + command.undo(); + + // after undo they should be the same again + assertEquals(0, modelComparator.compare(model, model2)); + + command.redo(); + + // after redo they should be different again + assertTrue(0 != modelComparator.compare(model, model2)); + } } diff --git a/model-command/src/test/java/lcsb/mapviewer/commands/properties/ChangeElementSymbolCommandTest.java b/model-command/src/test/java/lcsb/mapviewer/commands/properties/ChangeElementSymbolCommandTest.java index 721358b838bd17521b75adfc2751f16896c6a762..4af595e79681a0722adb9f6390261d8bbaea64a8 100644 --- a/model-command/src/test/java/lcsb/mapviewer/commands/properties/ChangeElementSymbolCommandTest.java +++ b/model-command/src/test/java/lcsb/mapviewer/commands/properties/ChangeElementSymbolCommandTest.java @@ -1,75 +1,62 @@ package lcsb.mapviewer.commands.properties; import static org.junit.Assert.*; + +import org.junit.*; + import lcsb.mapviewer.commands.CommandTestFunctions; import lcsb.mapviewer.model.map.model.Model; import lcsb.mapviewer.model.map.model.ModelComparator; import lcsb.mapviewer.model.map.species.Element; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -public class ChangeElementSymbolCommandTest extends CommandTestFunctions{ - - Model model; - - ModelComparator modelComparator= new ModelComparator(); - - @Before - public void setUp() throws Exception { - model = createSimpleModel(); - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testChangeAliasSymbol() throws Exception { - try { - Element alias = model.getElementByElementId("alias_id"); - ChangeElementSymbolCommand command = new ChangeElementSymbolCommand(model, alias, "test"); - assertFalse("test".equals(alias.getSymbol())); - command.execute(); - assertTrue(alias.getSymbol().equalsIgnoreCase("test")); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testUndo() throws Exception { - try { - Model model2 = createSimpleModel(); - Element alias = model.getElementByElementId("alias_id"); - - // models should be equal before move - assertEquals(0, modelComparator.compare(model, model2)); - - ChangeElementSymbolCommand command = new ChangeElementSymbolCommand(model, alias, "test"); - command.execute(); - - // after move models should be different - assertTrue(0 != modelComparator.compare(model, model2)); - - // undo command - command.undo(); - - // after undo they should be the same again - assertEquals(0, modelComparator.compare(model, model2)); - - command.redo(); - - // after redo they should be different again - assertTrue(0 != modelComparator.compare(model, model2)); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } +public class ChangeElementSymbolCommandTest extends CommandTestFunctions { + + Model model; + + ModelComparator modelComparator = new ModelComparator(); + + @Before + public void setUp() throws Exception { + model = createSimpleModel(); + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testChangeAliasSymbol() throws Exception { + Element alias = model.getElementByElementId("alias_id"); + ChangeElementSymbolCommand command = new ChangeElementSymbolCommand(model, alias, "test"); + assertFalse("test".equals(alias.getSymbol())); + command.execute(); + assertTrue(alias.getSymbol().equalsIgnoreCase("test")); + } + + @Test + public void testUndo() throws Exception { + Model model2 = createSimpleModel(); + Element alias = model.getElementByElementId("alias_id"); + + // models should be equal before move + assertEquals(0, modelComparator.compare(model, model2)); + + ChangeElementSymbolCommand command = new ChangeElementSymbolCommand(model, alias, "test"); + command.execute(); + + // after move models should be different + assertTrue(0 != modelComparator.compare(model, model2)); + + // undo command + command.undo(); + + // after undo they should be the same again + assertEquals(0, modelComparator.compare(model, model2)); + + command.redo(); + + // after redo they should be different again + assertTrue(0 != modelComparator.compare(model, model2)); + } } diff --git a/model-command/src/test/java/lcsb/mapviewer/commands/properties/ChangeElementSynonymCommandTest.java b/model-command/src/test/java/lcsb/mapviewer/commands/properties/ChangeElementSynonymCommandTest.java index 6cad5a9b42bdd70da6329eddf1d935c834aa0212..5268580021c1820ef707a3f3ff860d8222b233a2 100644 --- a/model-command/src/test/java/lcsb/mapviewer/commands/properties/ChangeElementSynonymCommandTest.java +++ b/model-command/src/test/java/lcsb/mapviewer/commands/properties/ChangeElementSynonymCommandTest.java @@ -1,90 +1,71 @@ package lcsb.mapviewer.commands.properties; import static org.junit.Assert.*; + +import org.junit.*; + import lcsb.mapviewer.commands.CommandTestFunctions; import lcsb.mapviewer.model.map.model.Model; import lcsb.mapviewer.model.map.model.ModelComparator; import lcsb.mapviewer.model.map.species.Element; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - public class ChangeElementSynonymCommandTest extends CommandTestFunctions { - Model model; - - ModelComparator modelComparator = new ModelComparator(); - - @Before - public void setUp() throws Exception { - model = createSimpleModel(); - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testChangeAliasSynonym() throws Exception { - try { - Element alias = model.getElementByElementId("alias_id"); - ChangeElementSynonymCommand command = new ChangeElementSynonymCommand(model, alias, "test","synonym"); - assertFalse(alias.getSynonyms().contains("test")); - command.execute(); - assertTrue(alias.getSynonyms().contains("test")); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testChangeToTheSame() throws Exception { - try { - Element alias = model.getElementByElementId("alias_id"); - ChangeElementSynonymCommand command = new ChangeElementSynonymCommand(model, alias, "synonym","synonym"); - assertTrue(alias.getSynonyms().contains("synonym")); - command.execute(); - assertTrue(alias.getSynonyms().contains("synonym")); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testUndo() throws Exception { - try { - Model model2 = createSimpleModel(); - Element alias = model.getElementByElementId("alias_id"); - - // models should be equal before move - assertEquals(0, modelComparator.compare(model, model2)); - - ChangeElementSynonymCommand command = new ChangeElementSynonymCommand(model, alias, "test", "synonym"); - command.execute(); - - // after move models should be different - assertTrue(0 != modelComparator.compare(model, model2)); - - // undo command - command.undo(); - - // after undo they should be the same again - assertEquals(0, modelComparator.compare(model, model2)); - - command.redo(); - - // after redo they should be different again - assertTrue(0 != modelComparator.compare(model, model2)); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } + Model model; + + ModelComparator modelComparator = new ModelComparator(); + + @Before + public void setUp() throws Exception { + model = createSimpleModel(); + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testChangeAliasSynonym() throws Exception { + Element alias = model.getElementByElementId("alias_id"); + ChangeElementSynonymCommand command = new ChangeElementSynonymCommand(model, alias, "test", "synonym"); + assertFalse(alias.getSynonyms().contains("test")); + command.execute(); + assertTrue(alias.getSynonyms().contains("test")); + } + + @Test + public void testChangeToTheSame() throws Exception { + Element alias = model.getElementByElementId("alias_id"); + ChangeElementSynonymCommand command = new ChangeElementSynonymCommand(model, alias, "synonym", "synonym"); + assertTrue(alias.getSynonyms().contains("synonym")); + command.execute(); + assertTrue(alias.getSynonyms().contains("synonym")); + } + + @Test + public void testUndo() throws Exception { + Model model2 = createSimpleModel(); + Element alias = model.getElementByElementId("alias_id"); + + // models should be equal before move + assertEquals(0, modelComparator.compare(model, model2)); + + ChangeElementSynonymCommand command = new ChangeElementSynonymCommand(model, alias, "test", "synonym"); + command.execute(); + + // after move models should be different + assertTrue(0 != modelComparator.compare(model, model2)); + + // undo command + command.undo(); + + // after undo they should be the same again + assertEquals(0, modelComparator.compare(model, model2)); + + command.redo(); + + // after redo they should be different again + assertTrue(0 != modelComparator.compare(model, model2)); + } } diff --git a/model/src/test/java/lcsb/mapviewer/ModelTestFunctions.java b/model/src/test/java/lcsb/mapviewer/ModelTestFunctions.java index 4828f73ee3f45232fc919868e3dd8b75abd79e8c..3a24827753e515b411bba293e10f2502e5b11d6f 100644 --- a/model/src/test/java/lcsb/mapviewer/ModelTestFunctions.java +++ b/model/src/test/java/lcsb/mapviewer/ModelTestFunctions.java @@ -3,13 +3,16 @@ package lcsb.mapviewer; import java.util.List; import org.apache.logging.log4j.core.LogEvent; -import org.junit.After; -import org.junit.Before; +import org.junit.*; import lcsb.mapviewer.common.MinervaLoggerAppender; +import lcsb.mapviewer.common.UnitTestFailedWatcher; public class ModelTestFunctions { + @Rule + public UnitTestFailedWatcher unitTestFailedWatcher = new UnitTestFailedWatcher(); + private MinervaLoggerAppender appender; @Before diff --git a/model/src/test/java/lcsb/mapviewer/model/ProjectTest.java b/model/src/test/java/lcsb/mapviewer/model/ProjectTest.java index 181c7cc548b40131397105dbabeb1fee3400f8a8..6a5fb5d27d39fc98865447438cf36de35737cc71 100644 --- a/model/src/test/java/lcsb/mapviewer/model/ProjectTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/ProjectTest.java @@ -1,32 +1,23 @@ package lcsb.mapviewer.model; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; -import java.util.ArrayList; -import java.util.Calendar; -import java.util.HashSet; -import java.util.List; -import java.util.Set; +import java.util.*; import org.apache.commons.lang3.SerializationUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; +import lcsb.mapviewer.ModelTestFunctions; import lcsb.mapviewer.common.Configuration; import lcsb.mapviewer.common.MinervaLoggerAppender; import lcsb.mapviewer.common.exception.InvalidArgumentException; import lcsb.mapviewer.model.cache.UploadedFileEntry; import lcsb.mapviewer.model.map.MiriamData; -import lcsb.mapviewer.model.map.model.Model; -import lcsb.mapviewer.model.map.model.ModelData; -import lcsb.mapviewer.model.map.model.ModelFullIndexed; +import lcsb.mapviewer.model.map.model.*; -public class ProjectTest { +public class ProjectTest extends ModelTestFunctions { Logger logger = LogManager.getLogger(ProjectTest.class); @Before @@ -39,102 +30,82 @@ public class ProjectTest { @Test public void testSerialization() { - try { - SerializationUtils.serialize(new Project()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + SerializationUtils.serialize(new Project()); } @Test public void testProject() { - try { - Project project = new Project("str"); - assertNotNull(project); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Project project = new Project("str"); + assertNotNull(project); } @Test public void testAddModel() { - try { - Model model = new ModelFullIndexed(null); - Model model2 = new ModelFullIndexed(null); - Project project = new Project(); - assertEquals(0, project.getModels().size()); - project.addModel(model); - assertEquals(1, project.getModels().size()); - project.addModel(model); - assertEquals(1, project.getModels().size()); - project.addModel(model2.getModelData()); - assertEquals(2, project.getModels().size()); - project.removeModel(model2.getModelData()); - assertEquals(1, project.getModels().size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Model model = new ModelFullIndexed(null); + Model model2 = new ModelFullIndexed(null); + Project project = new Project(); + assertEquals(0, project.getModels().size()); + project.addModel(model); + assertEquals(1, project.getModels().size()); + project.addModel(model); + assertEquals(1, project.getModels().size()); + project.addModel(model2.getModelData()); + assertEquals(2, project.getModels().size()); + project.removeModel(model2.getModelData()); + assertEquals(1, project.getModels().size()); } @Test public void testGetters() { - try { - MiriamData organism = new MiriamData(); - int id = 5; - String projectId = "str"; - ProjectStatus status = ProjectStatus.ANNOTATING; - double progress = 4.5; - Set<ModelData> models = new HashSet<>(); - String errors = "eerStr"; - String directory = "dir"; - String name = "name3"; - MiriamData disease = new MiriamData(); - Project project = new Project("str"); - boolean sbgn = true; - - project.setSbgnFormat(sbgn); - assertEquals(sbgn, project.isSbgnFormat()); - - project.setId(id); - assertEquals(id, project.getId()); - - project.setProjectId(projectId); - assertEquals(projectId, project.getProjectId()); - - project.setStatus(status); - assertEquals(status, project.getStatus()); - - project.setProgress(progress); - assertEquals(progress, project.getProgress(), Configuration.EPSILON); - - project.setModels(models); - assertEquals(models, project.getModels()); - - project.setErrors(errors); - assertEquals(errors, project.getErrors()); - - project.setDirectory(directory); - assertEquals(directory, project.getDirectory()); - - project.setName(name); - assertEquals(name, project.getName()); - - project.setDisease(disease); - assertEquals(disease, project.getDisease()); - - UploadedFileEntry entry = new UploadedFileEntry(); - project.setInputData(entry); - assertEquals(entry, project.getInputData()); - - project.setOrganism(organism); - assertEquals(organism, project.getOrganism()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + MiriamData organism = new MiriamData(); + int id = 5; + String projectId = "str"; + ProjectStatus status = ProjectStatus.ANNOTATING; + double progress = 4.5; + Set<ModelData> models = new HashSet<>(); + String errors = "eerStr"; + String directory = "dir"; + String name = "name3"; + MiriamData disease = new MiriamData(); + Project project = new Project("str"); + boolean sbgn = true; + + project.setSbgnFormat(sbgn); + assertEquals(sbgn, project.isSbgnFormat()); + + project.setId(id); + assertEquals(id, project.getId()); + + project.setProjectId(projectId); + assertEquals(projectId, project.getProjectId()); + + project.setStatus(status); + assertEquals(status, project.getStatus()); + + project.setProgress(progress); + assertEquals(progress, project.getProgress(), Configuration.EPSILON); + + project.setModels(models); + assertEquals(models, project.getModels()); + + project.setErrors(errors); + assertEquals(errors, project.getErrors()); + + project.setDirectory(directory); + assertEquals(directory, project.getDirectory()); + + project.setName(name); + assertEquals(name, project.getName()); + + project.setDisease(disease); + assertEquals(disease, project.getDisease()); + + UploadedFileEntry entry = new UploadedFileEntry(); + project.setInputData(entry); + assertEquals(entry, project.getInputData()); + + project.setOrganism(organism); + assertEquals(organism, project.getOrganism()); } @Test @@ -145,123 +116,80 @@ public class ProjectTest { assertEquals(creationDate, project.getCreationDate()); } - @Test + @Test(expected = InvalidArgumentException.class) public void testAddCreationWarning() { - try { - Project md = new Project(); - md.addWarning("text\ntext"); - - fail("Exception expected"); - } catch (InvalidArgumentException e) { - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Project md = new Project(); + md.addWarning("text\ntext"); } @Test public void testAddCreationWarning2() { - try { - Project md = new Project(); - md.addWarning(""); - List<String> warnings = md.getWarnings(); - assertEquals(0, warnings.size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Project md = new Project(); + md.addWarning(""); + List<String> warnings = md.getWarnings(); + assertEquals(0, warnings.size()); } @Test public void testAddCreationWarning3() { - try { - Project md = new Project(); - md.addWarning("xqw"); - List<String> warnings = md.getWarnings(); - assertEquals(1, warnings.size()); - assertEquals("xqw", warnings.get(0)); - - md.addWarning("WER"); - warnings = md.getWarnings(); - assertEquals(2, warnings.size()); - assertEquals("WER", warnings.get(1)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Project md = new Project(); + md.addWarning("xqw"); + List<String> warnings = md.getWarnings(); + assertEquals(1, warnings.size()); + assertEquals("xqw", warnings.get(0)); + + md.addWarning("WER"); + warnings = md.getWarnings(); + assertEquals(2, warnings.size()); + assertEquals("WER", warnings.get(1)); } @Test public void testAddCreationWarnings() { - try { - List<String> warnings = new ArrayList<>(); - warnings.add("xqw"); - warnings.add("aso"); - warnings.add(""); - Project project = new Project(); - project.addWarnings(warnings); - - project.addWarning("WER"); - warnings = project.getWarnings(); - assertEquals(3, warnings.size()); - assertEquals("aso", warnings.get(1)); - - project.addWarnings(warnings); - warnings = project.getWarnings(); - assertEquals(6, warnings.size()); - assertEquals("aso", warnings.get(1)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + List<String> warnings = new ArrayList<>(); + warnings.add("xqw"); + warnings.add("aso"); + warnings.add(""); + Project project = new Project(); + project.addWarnings(warnings); + + project.addWarning("WER"); + warnings = project.getWarnings(); + assertEquals(3, warnings.size()); + assertEquals("aso", warnings.get(1)); + + project.addWarnings(warnings); + warnings = project.getWarnings(); + assertEquals(6, warnings.size()); + assertEquals("aso", warnings.get(1)); } - @Test + @Test(expected = InvalidArgumentException.class) public void testAddCreationWarnings2() { - try { - List<String> warnings = new ArrayList<>(); - warnings.add("xqw\nwer\nt"); - Project md = new Project(); - md.addWarnings(warnings); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + List<String> warnings = new ArrayList<>(); + warnings.add("xqw\nwer\nt"); + Project md = new Project(); + md.addWarnings(warnings); } @Test public void testAddCreationWarnings3() { - try { - List<String> warnings = new ArrayList<>(); - Project md = new Project(); - md.addWarnings(warnings); - assertEquals(0, md.getWarnings().size()); - } catch (InvalidArgumentException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + List<String> warnings = new ArrayList<>(); + Project md = new Project(); + md.addWarnings(warnings); + assertEquals(0, md.getWarnings().size()); } @Test public void testAddLoggingInfo() { - try { - Project project = new Project(); - MinervaLoggerAppender appender = MinervaLoggerAppender.createAppender(); - logger.warn("test"); - logger.warn("test2"); - MinervaLoggerAppender.unregisterLogEventStorage(appender); - - project.addLoggingInfo(appender); - assertEquals(2, project.getWarnings().size()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Project project = new Project(); + MinervaLoggerAppender appender = MinervaLoggerAppender.createAppender(); + logger.warn("test"); + logger.warn("test2"); + MinervaLoggerAppender.unregisterLogEventStorage(appender); + + project.addLoggingInfo(appender); + assertEquals(2, project.getWarnings().size()); } } diff --git a/model/src/test/java/lcsb/mapviewer/model/cache/BigFileEntryTest.java b/model/src/test/java/lcsb/mapviewer/model/cache/BigFileEntryTest.java index 08e0eb23536563c3e8dab496c139621cfbc6733f..049e72efca99b7ab1c7a43bbd240a8ef39377338 100644 --- a/model/src/test/java/lcsb/mapviewer/model/cache/BigFileEntryTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/cache/BigFileEntryTest.java @@ -1,66 +1,59 @@ package lcsb.mapviewer.model.cache; -import static org.junit.Assert.assertEquals; +import static org.junit.Assert.*; import java.util.Calendar; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.Test; - -public class BigFileEntryTest { - - @AfterClass - public static void tearDownAfterClass() throws Exception { - } - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testGetters() { - try { - Calendar downloadDate = Calendar.getInstance(); - int id = 120; - double downloadProgress = 4.6; - long downloadThreadId = 6; - String localPath = "C:/"; - boolean removed = true; - String url = "www.google.com"; - String filename = "tmp"; - byte[] content = new byte[] { 1, 2 }; - - BigFileEntry element = new BigFileEntry(); - element.setDownloadDate(downloadDate); - element.setDownloadProgress(downloadProgress); - element.setDownloadThreadId(downloadThreadId); - element.setId(id); - element.setLocalPath(localPath); - element.setRemoved(removed); - element.setUrl(url); - element.setOriginalFileName(filename); - element.setFileContent(content); - - assertEquals(downloadDate, element.getDownloadDate()); - assertEquals((Double) downloadProgress, element.getDownloadProgress()); - assertEquals((Long) downloadThreadId, element.getDownloadThreadId()); - assertEquals(id, element.getId()); - assertEquals(localPath, element.getLocalPath()); - assertEquals(removed, element.isRemoved()); - assertEquals(url, element.getUrl()); - assertEquals(content, element.getFileContent()); - assertEquals(filename, element.getOriginalFileName()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } +import org.junit.*; + +import lcsb.mapviewer.ModelTestFunctions; + +public class BigFileEntryTest extends ModelTestFunctions { + + @AfterClass + public static void tearDownAfterClass() throws Exception { + } + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testGetters() { + Calendar downloadDate = Calendar.getInstance(); + int id = 120; + double downloadProgress = 4.6; + long downloadThreadId = 6; + String localPath = "C:/"; + boolean removed = true; + String url = "www.google.com"; + String filename = "tmp"; + byte[] content = new byte[] { 1, 2 }; + + BigFileEntry element = new BigFileEntry(); + element.setDownloadDate(downloadDate); + element.setDownloadProgress(downloadProgress); + element.setDownloadThreadId(downloadThreadId); + element.setId(id); + element.setLocalPath(localPath); + element.setRemoved(removed); + element.setUrl(url); + element.setOriginalFileName(filename); + element.setFileContent(content); + + assertEquals(downloadDate, element.getDownloadDate()); + assertEquals((Double) downloadProgress, element.getDownloadProgress()); + assertEquals((Long) downloadThreadId, element.getDownloadThreadId()); + assertEquals(id, element.getId()); + assertEquals(localPath, element.getLocalPath()); + assertEquals(removed, element.isRemoved()); + assertEquals(url, element.getUrl()); + assertEquals(content, element.getFileContent()); + assertEquals(filename, element.getOriginalFileName()); + } } diff --git a/model/src/test/java/lcsb/mapviewer/model/cache/CacheQueryTest.java b/model/src/test/java/lcsb/mapviewer/model/cache/CacheQueryTest.java index ce9a2d4a94a908a7bb9977849f384530a29708be..8c1daeff2493042514d863cb0d6dd892eb651d7c 100644 --- a/model/src/test/java/lcsb/mapviewer/model/cache/CacheQueryTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/cache/CacheQueryTest.java @@ -1,69 +1,58 @@ package lcsb.mapviewer.model.cache; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.Assert.*; import java.util.Calendar; import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -public class CacheQueryTest { - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testSerialization() { - try { - SerializationUtils.serialize(new CacheQuery()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testGetters() { - try { - Calendar expires = Calendar.getInstance(); - expires.add(Calendar.DATE, 1); - Calendar accessed = Calendar.getInstance(); - accessed.add(Calendar.DATE, 10); - int id = 120; - String query = "query1"; - int type = 34; - int type2 = 45; - String value = "val"; - CacheType ctype = new CacheType(); - ctype.setId(type2); - - CacheQuery cq = new CacheQuery(); - cq.setAccessed(accessed); - assertTrue(accessed.equals(cq.getAccessed())); - cq.setExpires(expires); - assertTrue(expires.equals(cq.getExpires())); - cq.setId(id); - assertEquals(id, cq.getId()); - cq.setQuery(query); - assertEquals(query, cq.getQuery()); - cq.setType(ctype); - assertEquals((Integer) type2, cq.getType()); - cq.setType(type); - assertEquals((Integer) type, cq.getType()); - cq.setValue(value); - assertEquals(value, cq.getValue()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } +import org.junit.*; + +import lcsb.mapviewer.ModelTestFunctions; + +public class CacheQueryTest extends ModelTestFunctions { + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testSerialization() { + SerializationUtils.serialize(new CacheQuery()); + } + + @Test + public void testGetters() { + Calendar expires = Calendar.getInstance(); + expires.add(Calendar.DATE, 1); + Calendar accessed = Calendar.getInstance(); + accessed.add(Calendar.DATE, 10); + int id = 120; + String query = "query1"; + int type = 34; + int type2 = 45; + String value = "val"; + CacheType ctype = new CacheType(); + ctype.setId(type2); + + CacheQuery cq = new CacheQuery(); + cq.setAccessed(accessed); + assertTrue(accessed.equals(cq.getAccessed())); + cq.setExpires(expires); + assertTrue(expires.equals(cq.getExpires())); + cq.setId(id); + assertEquals(id, cq.getId()); + cq.setQuery(query); + assertEquals(query, cq.getQuery()); + cq.setType(ctype); + assertEquals((Integer) type2, cq.getType()); + cq.setType(type); + assertEquals((Integer) type, cq.getType()); + cq.setValue(value); + assertEquals(value, cq.getValue()); + } } diff --git a/model/src/test/java/lcsb/mapviewer/model/cache/CacheTypeTest.java b/model/src/test/java/lcsb/mapviewer/model/cache/CacheTypeTest.java index fe634b21ce8ec215deab74c4e9d4f50f6a6d73d2..77bd9d8eccc9769720348266aa8cd04f9434d8db 100644 --- a/model/src/test/java/lcsb/mapviewer/model/cache/CacheTypeTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/cache/CacheTypeTest.java @@ -1,50 +1,39 @@ package lcsb.mapviewer.model.cache; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.*; import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -public class CacheTypeTest { - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testSerialization() { - try { - SerializationUtils.serialize(new CacheType()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testGetters() { - try { - int id = 4; - int validity = 12; - String className = "cname"; - CacheType ct = new CacheType(); - ct.setId(id); - ct.setClassName(className); - ct.setValidity(validity); - assertEquals(id, ct.getId()); - assertEquals(className, ct.getClassName()); - assertEquals(validity, ct.getValidity()); - assertNotNull(ct.toString()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } +import org.junit.*; + +import lcsb.mapviewer.ModelTestFunctions; + +public class CacheTypeTest extends ModelTestFunctions { + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testSerialization() { + SerializationUtils.serialize(new CacheType()); + } + + @Test + public void testGetters() { + int id = 4; + int validity = 12; + String className = "cname"; + CacheType ct = new CacheType(); + ct.setId(id); + ct.setClassName(className); + ct.setValidity(validity); + assertEquals(id, ct.getId()); + assertEquals(className, ct.getClassName()); + assertEquals(validity, ct.getValidity()); + assertNotNull(ct.toString()); + } } diff --git a/model/src/test/java/lcsb/mapviewer/model/cache/UploadedFileEntryTest.java b/model/src/test/java/lcsb/mapviewer/model/cache/UploadedFileEntryTest.java index ed6588fe6229d6b552295d7527a1e7ec420c2191..1380a2bd54c36dc41db9b9fc113b980e21fe771a 100644 --- a/model/src/test/java/lcsb/mapviewer/model/cache/UploadedFileEntryTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/cache/UploadedFileEntryTest.java @@ -1,33 +1,27 @@ package lcsb.mapviewer.model.cache; import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.Test; - -public class UploadedFileEntryTest { - - @AfterClass - public static void tearDownAfterClass() throws Exception { - } - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testSerialization() { - try { - SerializationUtils.serialize(new UploadedFileEntry()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } +import org.junit.*; + +import lcsb.mapviewer.ModelTestFunctions; + +public class UploadedFileEntryTest extends ModelTestFunctions { + + @AfterClass + public static void tearDownAfterClass() throws Exception { + } + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testSerialization() { + SerializationUtils.serialize(new UploadedFileEntry()); + } } diff --git a/model/src/test/java/lcsb/mapviewer/model/graphics/ArrowTypeDataComparatorTest.java b/model/src/test/java/lcsb/mapviewer/model/graphics/ArrowTypeDataComparatorTest.java index 1a15ccf54c3a1aa2bb4682df8877cbfbc6023451..764446834e5334987f1d98d48390211e7768feac 100644 --- a/model/src/test/java/lcsb/mapviewer/model/graphics/ArrowTypeDataComparatorTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/graphics/ArrowTypeDataComparatorTest.java @@ -1,72 +1,58 @@ package lcsb.mapviewer.model.graphics; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -public class ArrowTypeDataComparatorTest { - ArrowTypeDataComparator comparator = new ArrowTypeDataComparator(); - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testCompareEquals() { - try { - assertEquals(0, comparator.compare(null, null)); - assertEquals(0, comparator.compare(new ArrowTypeData(), new ArrowTypeData())); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testCompareDifferent() { - try { - assertTrue(comparator.compare(new ArrowTypeData(), null) != 0); - assertTrue(comparator.compare(null, new ArrowTypeData()) != 0); - assertTrue(comparator.compare(new ArrowTypeData() { - private static final long serialVersionUID = 1L; - }, new ArrowTypeData()) != 0); - - ArrowTypeData atd1 = new ArrowTypeData(); - ArrowTypeData atd2 = new ArrowTypeData(); - - atd1.setArrowType(ArrowType.CROSSBAR); - assertTrue(comparator.compare(atd1, atd2)!=0); - - atd1 = new ArrowTypeData(); - atd2 = new ArrowTypeData(); - - atd1.setArrowLineType(LineType.DOUBLE); - assertTrue(comparator.compare(atd1, atd2)!=0); - - atd1 = new ArrowTypeData(); - atd2 = new ArrowTypeData(); - - atd1.setLen(2.0); - assertTrue(comparator.compare(atd1, atd2)!=0); - - - atd1 = new ArrowTypeData(); - atd2 = new ArrowTypeData(); - - atd1.setAngle(3.4); - assertTrue(comparator.compare(atd1, atd2)!=0); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } +import static org.junit.Assert.*; + +import org.junit.*; +import org.mockito.Mockito; + +import lcsb.mapviewer.ModelTestFunctions; + +public class ArrowTypeDataComparatorTest extends ModelTestFunctions { + ArrowTypeDataComparator comparator = new ArrowTypeDataComparator(); + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testCompareEquals() { + assertEquals(0, comparator.compare(null, null)); + assertEquals(0, comparator.compare(new ArrowTypeData(), new ArrowTypeData())); + } + + @Test + public void testCompareDifferent() { + assertTrue(comparator.compare(new ArrowTypeData(), null) != 0); + assertTrue(comparator.compare(null, new ArrowTypeData()) != 0); + assertTrue(comparator.compare(Mockito.spy(ArrowTypeData.class), new ArrowTypeData()) != 0); + + ArrowTypeData atd1 = new ArrowTypeData(); + ArrowTypeData atd2 = new ArrowTypeData(); + + atd1.setArrowType(ArrowType.CROSSBAR); + assertTrue(comparator.compare(atd1, atd2) != 0); + + atd1 = new ArrowTypeData(); + atd2 = new ArrowTypeData(); + + atd1.setArrowLineType(LineType.DOUBLE); + assertTrue(comparator.compare(atd1, atd2) != 0); + + atd1 = new ArrowTypeData(); + atd2 = new ArrowTypeData(); + + atd1.setLen(2.0); + assertTrue(comparator.compare(atd1, atd2) != 0); + + atd1 = new ArrowTypeData(); + atd2 = new ArrowTypeData(); + + atd1.setAngle(3.4); + assertTrue(comparator.compare(atd1, atd2) != 0); + } } diff --git a/model/src/test/java/lcsb/mapviewer/model/graphics/ArrowTypeDataTest.java b/model/src/test/java/lcsb/mapviewer/model/graphics/ArrowTypeDataTest.java index f89b73ee81e678b24f014e6331c498bd5c2d92b2..6a5dc9213eb25cb07afe3620dd0a334698b92289 100644 --- a/model/src/test/java/lcsb/mapviewer/model/graphics/ArrowTypeDataTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/graphics/ArrowTypeDataTest.java @@ -1,17 +1,15 @@ package lcsb.mapviewer.model.graphics; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; +import org.mockito.Mockito; +import lcsb.mapviewer.ModelTestFunctions; import lcsb.mapviewer.common.exception.NotImplementedException; -public class ArrowTypeDataTest { +public class ArrowTypeDataTest extends ModelTestFunctions { @Before public void setUp() throws Exception { @@ -23,57 +21,28 @@ public class ArrowTypeDataTest { @Test public void testSerialization() { - try { - SerializationUtils.serialize(new ArrowTypeData()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + SerializationUtils.serialize(new ArrowTypeData()); } @Test public void testCopy() { - try { - ArrowTypeData original = new ArrowTypeData(); - ArrowTypeData degraded = original.copy(); - assertNotNull(degraded); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + ArrowTypeData original = new ArrowTypeData(); + ArrowTypeData degraded = original.copy(); + assertNotNull(degraded); } @Test public void testEquals() { - try { - ArrowTypeData original = new ArrowTypeData(); - original.setAngle(12); - ArrowTypeData copy = original.copy(); + ArrowTypeData original = new ArrowTypeData(); + original.setAngle(12); + ArrowTypeData copy = original.copy(); - assertTrue(original.equals(copy)); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertTrue(original.equals(copy)); } - @Test + @Test(expected = NotImplementedException.class) public void testInvalidCopy() { - try { - new ArrowTypeData() { - - /** - * - */ - private static final long serialVersionUID = 1L; - }.copy(); - fail("Exception expected"); - } catch (NotImplementedException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Mockito.spy(ArrowTypeData.class).copy(); } } diff --git a/model/src/test/java/lcsb/mapviewer/model/graphics/PolylineDataComparatorTest.java b/model/src/test/java/lcsb/mapviewer/model/graphics/PolylineDataComparatorTest.java index 4abcb430fdaef34efb4afa4fe3e56298811a13e1..e01b64d290ba515ab82c83c12e4baef972859940 100644 --- a/model/src/test/java/lcsb/mapviewer/model/graphics/PolylineDataComparatorTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/graphics/PolylineDataComparatorTest.java @@ -1,112 +1,90 @@ package lcsb.mapviewer.model.graphics; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import java.awt.Color; import java.awt.geom.Point2D; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; +import org.mockito.Mockito; +import lcsb.mapviewer.ModelTestFunctions; import lcsb.mapviewer.common.exception.NotImplementedException; -public class PolylineDataComparatorTest { - - PolylineDataComparator comparator = new PolylineDataComparator(); - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testEquals() { - try { - PolylineData pd1 = new PolylineData(); - PolylineData pd2 = new PolylineData(); - assertEquals(0, comparator.compare(pd1, pd2)); - assertEquals(0, comparator.compare(null, null)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testInvalid() { - try { - class Tmp extends PolylineData { - private static final long serialVersionUID = 1L; - } - Tmp pd1 = new Tmp(); - Tmp pd2 = new Tmp(); - comparator.compare(pd1, pd2); - fail("Exception expected"); - } catch (NotImplementedException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testDifferent() { - try { - PolylineData pd1 = new PolylineData(); - PolylineData pd2 = new PolylineData(); - - assertTrue(comparator.compare(pd2, null) != 0); - assertTrue(comparator.compare(null, pd1) != 0); - - pd1 = new PolylineData(); - pd2 = new PolylineData(); - pd2.addPoint(new Point2D.Double(1, 2)); - pd2.addPoint(new Point2D.Double(1, 3)); - assertTrue(comparator.compare(pd1, pd2) != 0); - assertTrue(comparator.compare(pd2, pd1) != 0); - - pd1 = new PolylineData(); - pd2 = new PolylineData(); - ArrowTypeData atd = new ArrowTypeData(); - atd.setLen(34); - pd2.setBeginAtd(atd); - assertTrue(comparator.compare(pd1, pd2) != 0); - assertTrue(comparator.compare(pd2, pd1) != 0); - - pd1 = new PolylineData(); - pd2 = new PolylineData(); - atd = new ArrowTypeData(); - atd.setLen(34); - pd2.setEndAtd(atd); - assertTrue(comparator.compare(pd1, pd2) != 0); - assertTrue(comparator.compare(pd2, pd1) != 0); - - pd1 = new PolylineData(); - pd2 = new PolylineData(); - pd2.setColor(Color.BLUE); - assertTrue(comparator.compare(pd1, pd2) != 0); - assertTrue(comparator.compare(pd2, pd1) != 0); - - pd1 = new PolylineData(); - pd2 = new PolylineData(); - pd2.setType(LineType.DASHED); - assertTrue(comparator.compare(pd1, pd2) != 0); - assertTrue(comparator.compare(pd2, pd1) != 0); - - assertTrue(comparator.compare(pd2, new PolylineData() { - private static final long serialVersionUID = 1L; - }) != 0); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } +public class PolylineDataComparatorTest extends ModelTestFunctions { + + PolylineDataComparator comparator = new PolylineDataComparator(); + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testEquals() { + PolylineData pd1 = new PolylineData(); + PolylineData pd2 = new PolylineData(); + assertEquals(0, comparator.compare(pd1, pd2)); + assertEquals(0, comparator.compare(null, null)); + } + + @Test(expected = NotImplementedException.class) + public void testInvalid() { + class Tmp extends PolylineData { + private static final long serialVersionUID = 1L; + } + Tmp pd1 = new Tmp(); + Tmp pd2 = new Tmp(); + comparator.compare(pd1, pd2); + } + + @Test + public void testDifferent() { + PolylineData pd1 = new PolylineData(); + PolylineData pd2 = new PolylineData(); + + assertTrue(comparator.compare(pd2, null) != 0); + assertTrue(comparator.compare(null, pd1) != 0); + + pd1 = new PolylineData(); + pd2 = new PolylineData(); + pd2.addPoint(new Point2D.Double(1, 2)); + pd2.addPoint(new Point2D.Double(1, 3)); + assertTrue(comparator.compare(pd1, pd2) != 0); + assertTrue(comparator.compare(pd2, pd1) != 0); + + pd1 = new PolylineData(); + pd2 = new PolylineData(); + ArrowTypeData atd = new ArrowTypeData(); + atd.setLen(34); + pd2.setBeginAtd(atd); + assertTrue(comparator.compare(pd1, pd2) != 0); + assertTrue(comparator.compare(pd2, pd1) != 0); + + pd1 = new PolylineData(); + pd2 = new PolylineData(); + atd = new ArrowTypeData(); + atd.setLen(34); + pd2.setEndAtd(atd); + assertTrue(comparator.compare(pd1, pd2) != 0); + assertTrue(comparator.compare(pd2, pd1) != 0); + + pd1 = new PolylineData(); + pd2 = new PolylineData(); + pd2.setColor(Color.BLUE); + assertTrue(comparator.compare(pd1, pd2) != 0); + assertTrue(comparator.compare(pd2, pd1) != 0); + + pd1 = new PolylineData(); + pd2 = new PolylineData(); + pd2.setType(LineType.DASHED); + assertTrue(comparator.compare(pd1, pd2) != 0); + assertTrue(comparator.compare(pd2, pd1) != 0); + + assertTrue(comparator.compare(pd2, Mockito.spy(PolylineData.class)) != 0); + } } diff --git a/model/src/test/java/lcsb/mapviewer/model/graphics/PolylineDataTest.java b/model/src/test/java/lcsb/mapviewer/model/graphics/PolylineDataTest.java index b9bcd4583cfb48e3b80a954e9da95fa8794f173c..c2478f76a915a878c5180f68da425c950df2f41f 100644 --- a/model/src/test/java/lcsb/mapviewer/model/graphics/PolylineDataTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/graphics/PolylineDataTest.java @@ -1,30 +1,25 @@ package lcsb.mapviewer.model.graphics; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import java.awt.Color; -import java.awt.geom.AffineTransform; -import java.awt.geom.GeneralPath; -import java.awt.geom.PathIterator; -import java.awt.geom.Point2D; +import java.awt.geom.*; import java.util.ArrayList; import java.util.List; import org.apache.commons.lang3.SerializationUtils; -import org.apache.logging.log4j.*; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.junit.*; +import org.mockito.Mockito; +import lcsb.mapviewer.ModelTestFunctions; import lcsb.mapviewer.common.Configuration; import lcsb.mapviewer.common.exception.InvalidArgumentException; import lcsb.mapviewer.common.exception.NotImplementedException; import lcsb.mapviewer.common.geometry.PointTransformation; -public class PolylineDataTest { +public class PolylineDataTest extends ModelTestFunctions { Logger logger = LogManager.getLogger(PolylineDataTest.class); PointTransformation pr = new PointTransformation(); @@ -39,436 +34,267 @@ public class PolylineDataTest { @Test public void testConstructor() throws Exception { - try { - PolylineData pd = new PolylineData(new Point2D.Double(0, 0), new Point2D.Double(10, 10)); - assertNotNull(pd); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + PolylineData pd = new PolylineData(new Point2D.Double(0, 0), new Point2D.Double(10, 10)); + assertNotNull(pd); } @Test public void testConstructor2() throws Exception { - try { - PolylineData pd = new PolylineData(new Point2D.Double(0, 0), new Point2D.Double(10, 10)); - PolylineData pd2 = new PolylineData(pd); - assertNotNull(pd2); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + PolylineData pd = new PolylineData(new Point2D.Double(0, 0), new Point2D.Double(10, 10)); + PolylineData pd2 = new PolylineData(pd); + assertNotNull(pd2); } @Test public void testConstructor3() throws Exception { - try { - List<Point2D> points = new ArrayList<>(); - points.add(new Point2D.Double(1, 1)); - points.add(new Point2D.Double(5, 1)); - points.add(new Point2D.Double(5, 5)); - PolylineData pd2 = new PolylineData(points); - assertNotNull(pd2); - assertEquals(points.size(), pd2.getPoints().size()); - assertEquals(8, pd2.length(), Configuration.EPSILON); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + List<Point2D> points = new ArrayList<>(); + points.add(new Point2D.Double(1, 1)); + points.add(new Point2D.Double(5, 1)); + points.add(new Point2D.Double(5, 5)); + PolylineData pd2 = new PolylineData(points); + assertNotNull(pd2); + assertEquals(points.size(), pd2.getPoints().size()); + assertEquals(8, pd2.length(), Configuration.EPSILON); } @Test public void testAddPoint() throws Exception { - try { - PolylineData pd = new PolylineData(new Point2D.Double(0, 0), new Point2D.Double(10, 10)); - pd.addPoint(0, new Point2D.Double(-10, -10)); - assertEquals(3, pd.getPoints().size()); - assertTrue(pd.getPoints().get(0).getX() < 0); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + PolylineData pd = new PolylineData(new Point2D.Double(0, 0), new Point2D.Double(10, 10)); + pd.addPoint(0, new Point2D.Double(-10, -10)); + assertEquals(3, pd.getPoints().size()); + assertTrue(pd.getPoints().get(0).getX() < 0); } - @Test + @Test(expected = InvalidArgumentException.class) public void testAddInvalidPoint() throws Exception { - try { - PolylineData pd = new PolylineData(new Point2D.Double(0, 0), new Point2D.Double(10, 10)); - pd.addPoint(0, new Point2D.Double(Double.NEGATIVE_INFINITY, -10)); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + PolylineData pd = new PolylineData(new Point2D.Double(0, 0), new Point2D.Double(10, 10)); + pd.addPoint(0, new Point2D.Double(Double.NEGATIVE_INFINITY, -10)); } @Test public void testSetPoint() throws Exception { - try { - PolylineData pd = new PolylineData(new Point2D.Double(0, 0), new Point2D.Double(10, 10)); - pd.setPoint(0, new Point2D.Double(-10, -10)); - assertEquals(2, pd.getPoints().size()); - assertTrue(pd.getPoints().get(0).getX() < 0); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + PolylineData pd = new PolylineData(new Point2D.Double(0, 0), new Point2D.Double(10, 10)); + pd.setPoint(0, new Point2D.Double(-10, -10)); + assertEquals(2, pd.getPoints().size()); + assertTrue(pd.getPoints().get(0).getX() < 0); } - @Test + @Test(expected = InvalidArgumentException.class) public void testSetInvalidPoint() throws Exception { - try { - PolylineData pd = new PolylineData(new Point2D.Double(0, 0), new Point2D.Double(10, 10)); - pd.setPoint(0, new Point2D.Double(Double.NEGATIVE_INFINITY, -10)); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + PolylineData pd = new PolylineData(new Point2D.Double(0, 0), new Point2D.Double(10, 10)); + pd.setPoint(0, new Point2D.Double(Double.NEGATIVE_INFINITY, -10)); } @Test public void testGetLines() throws Exception { - try { - List<Point2D> points = new ArrayList<>(); - points.add(new Point2D.Double(1, 1)); - points.add(new Point2D.Double(5, 1)); - points.add(new Point2D.Double(5, 5)); - PolylineData pd2 = new PolylineData(points); - assertEquals(2, pd2.getLines().size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + List<Point2D> points = new ArrayList<>(); + points.add(new Point2D.Double(1, 1)); + points.add(new Point2D.Double(5, 1)); + points.add(new Point2D.Double(5, 5)); + PolylineData pd2 = new PolylineData(points); + assertEquals(2, pd2.getLines().size()); } - @Test + @Test(expected = InvalidArgumentException.class) public void testInvaliArgument() throws Exception { - try { - new PolylineData(new Point2D.Double(0, 0), new Point2D.Double(10, Double.NaN)); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + new PolylineData(new Point2D.Double(0, 0), new Point2D.Double(10, Double.NaN)); } @Test public void testSerialization() { - try { - SerializationUtils.serialize(new PolylineData()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + SerializationUtils.serialize(new PolylineData()); } @Test public void testGetSubline() throws Exception { - try { - List<Point2D> points = new ArrayList<>(); - points.add(new Point2D.Double(1, 1)); - points.add(new Point2D.Double(5, 1)); - points.add(new Point2D.Double(5, 5)); - PolylineData pd = new PolylineData(points); - PolylineData pd2 = pd.getSubline(0, 2); - assertNotNull(pd2); - assertEquals(2, pd2.getPoints().size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + List<Point2D> points = new ArrayList<>(); + points.add(new Point2D.Double(1, 1)); + points.add(new Point2D.Double(5, 1)); + points.add(new Point2D.Double(5, 5)); + PolylineData pd = new PolylineData(points); + PolylineData pd2 = pd.getSubline(0, 2); + assertNotNull(pd2); + assertEquals(2, pd2.getPoints().size()); } @Test public void testSetEndPoint() throws Exception { - try { - PolylineData pd = new PolylineData(new Point2D.Double(0, 0), new Point2D.Double(10, 10)); - pd.setEndPoint(new Point2D.Double(-10, -10)); - assertEquals(2, pd.getPoints().size()); - assertTrue(pd.getEndPoint().getX() < 0); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + PolylineData pd = new PolylineData(new Point2D.Double(0, 0), new Point2D.Double(10, 10)); + pd.setEndPoint(new Point2D.Double(-10, -10)); + assertEquals(2, pd.getPoints().size()); + assertTrue(pd.getEndPoint().getX() < 0); } - @Test + @Test(expected = InvalidArgumentException.class) public void testSetInvalidEndPoint() throws Exception { - try { - PolylineData pd = new PolylineData(new Point2D.Double(0, 0), new Point2D.Double(10, 10)); - pd.setEndPoint(new Point2D.Double(Double.NEGATIVE_INFINITY, -10)); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + PolylineData pd = new PolylineData(new Point2D.Double(0, 0), new Point2D.Double(10, 10)); + pd.setEndPoint(new Point2D.Double(Double.NEGATIVE_INFINITY, -10)); } @Test public void testSetStartPoint() throws Exception { - try { - PolylineData pd = new PolylineData(new Point2D.Double(0, 0), new Point2D.Double(10, 10)); - pd.setStartPoint(new Point2D.Double(-10, -10)); - assertEquals(2, pd.getPoints().size()); - assertTrue(pd.getBeginPoint().getX() < 0); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + PolylineData pd = new PolylineData(new Point2D.Double(0, 0), new Point2D.Double(10, 10)); + pd.setStartPoint(new Point2D.Double(-10, -10)); + assertEquals(2, pd.getPoints().size()); + assertTrue(pd.getBeginPoint().getX() < 0); } - @Test + @Test(expected = InvalidArgumentException.class) public void testSetInvalidStartPoint() throws Exception { - try { - PolylineData pd = new PolylineData(new Point2D.Double(0, 0), new Point2D.Double(10, 10)); - pd.setStartPoint(new Point2D.Double(Double.NEGATIVE_INFINITY, -10)); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + PolylineData pd = new PolylineData(new Point2D.Double(0, 0), new Point2D.Double(10, 10)); + pd.setStartPoint(new Point2D.Double(Double.NEGATIVE_INFINITY, -10)); } @Test public void testToGeneralPath() throws Exception { - try { - List<Point2D> points = new ArrayList<>(); - points.add(new Point2D.Double(1, 1)); - points.add(new Point2D.Double(5, 1)); - points.add(new Point2D.Double(5, 5)); - PolylineData pd = new PolylineData(points); - GeneralPath gp = pd.toGeneralPath(); - PathIterator pi = gp.getPathIterator(new AffineTransform()); - int count = 0; - while (!pi.isDone()) { - count++; - pi.next(); - } - assertEquals(3, count); - } catch (Exception e) { - e.printStackTrace(); - throw e; + List<Point2D> points = new ArrayList<>(); + points.add(new Point2D.Double(1, 1)); + points.add(new Point2D.Double(5, 1)); + points.add(new Point2D.Double(5, 5)); + PolylineData pd = new PolylineData(points); + GeneralPath gp = pd.toGeneralPath(); + PathIterator pi = gp.getPathIterator(new AffineTransform()); + int count = 0; + while (!pi.isDone()) { + count++; + pi.next(); } + assertEquals(3, count); } @Test public void testTrimEnd() throws Exception { - try { - List<Point2D> points = new ArrayList<>(); - points.add(new Point2D.Double(1, 1)); - points.add(new Point2D.Double(11, 1)); - PolylineData pd = new PolylineData(points); - pd.trimEnd(3); - - assertEquals(8, pd.getEndPoint().getX(), Configuration.EPSILON); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + List<Point2D> points = new ArrayList<>(); + points.add(new Point2D.Double(1, 1)); + points.add(new Point2D.Double(11, 1)); + PolylineData pd = new PolylineData(points); + pd.trimEnd(3); + + assertEquals(8, pd.getEndPoint().getX(), Configuration.EPSILON); } @Test public void testTrimEndByNegativeValueOnEmptySegment() throws Exception { - try { - List<Point2D> points = new ArrayList<>(); - points.add(new Point2D.Double(1, 1)); - points.add(new Point2D.Double(1, 1)); - PolylineData pd = new PolylineData(points); - pd.trimEnd(-3); - for (Point2D point : pd.getPoints()) { - assertTrue(pr.isValidPoint(point)); - } - } catch (Exception e) { - e.printStackTrace(); - throw e; + List<Point2D> points = new ArrayList<>(); + points.add(new Point2D.Double(1, 1)); + points.add(new Point2D.Double(1, 1)); + PolylineData pd = new PolylineData(points); + pd.trimEnd(-3); + for (Point2D point : pd.getPoints()) { + assertTrue(pr.isValidPoint(point)); } } @Test public void testTrimEndByNegativeValue() throws Exception { - try { - List<Point2D> points = new ArrayList<>(); - points.add(new Point2D.Double(1, 1)); - points.add(new Point2D.Double(10, 1)); - PolylineData pd = new PolylineData(points); - pd.trimEnd(-3); - for (Point2D point : pd.getPoints()) { - assertTrue(pr.isValidPoint(point)); - } - } catch (Exception e) { - e.printStackTrace(); - throw e; + List<Point2D> points = new ArrayList<>(); + points.add(new Point2D.Double(1, 1)); + points.add(new Point2D.Double(10, 1)); + PolylineData pd = new PolylineData(points); + pd.trimEnd(-3); + for (Point2D point : pd.getPoints()) { + assertTrue(pr.isValidPoint(point)); } } @Test public void testTrimBegin() throws Exception { - try { - List<Point2D> points = new ArrayList<>(); - points.add(new Point2D.Double(1, 1)); - points.add(new Point2D.Double(11, 1)); - PolylineData pd = new PolylineData(points); - pd.trimBegin(3); - - assertEquals(4, pd.getPoints().get(0).getX(), Configuration.EPSILON); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + List<Point2D> points = new ArrayList<>(); + points.add(new Point2D.Double(1, 1)); + points.add(new Point2D.Double(11, 1)); + PolylineData pd = new PolylineData(points); + pd.trimBegin(3); + + assertEquals(4, pd.getPoints().get(0).getX(), Configuration.EPSILON); } @Test public void testTrimEnd2() throws Exception { - try { - List<Point2D> points = new ArrayList<>(); - points.add(new Point2D.Double(1, 1)); - points.add(new Point2D.Double(11, 1)); - PolylineData pd = new PolylineData(points); - pd.trimEnd(30); - - assertEquals(1, pd.getEndPoint().getX(), Configuration.EPSILON); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + List<Point2D> points = new ArrayList<>(); + points.add(new Point2D.Double(1, 1)); + points.add(new Point2D.Double(11, 1)); + PolylineData pd = new PolylineData(points); + pd.trimEnd(30); + + assertEquals(1, pd.getEndPoint().getX(), Configuration.EPSILON); } @Test public void testTrimBegin2() throws Exception { - try { - List<Point2D> points = new ArrayList<>(); - points.add(new Point2D.Double(1, 1)); - points.add(new Point2D.Double(11, 1)); - PolylineData pd = new PolylineData(points); - pd.trimBegin(30); - - assertEquals(11, pd.getPoints().get(0).getX(), Configuration.EPSILON); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + List<Point2D> points = new ArrayList<>(); + points.add(new Point2D.Double(1, 1)); + points.add(new Point2D.Double(11, 1)); + PolylineData pd = new PolylineData(points); + pd.trimBegin(30); + + assertEquals(11, pd.getPoints().get(0).getX(), Configuration.EPSILON); } @Test public void testReverse() throws Exception { - try { - List<Point2D> points = new ArrayList<>(); - points.add(new Point2D.Double(1, 1)); - points.add(new Point2D.Double(11, 1)); - PolylineData pd = new PolylineData(points); - PolylineData pd2 = pd.reverse(); - assertTrue(pd.getBeginPoint().distance(pd2.getEndPoint()) <= Configuration.EPSILON); - assertTrue(pd2.getBeginPoint().distance(pd.getEndPoint()) <= Configuration.EPSILON); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + List<Point2D> points = new ArrayList<>(); + points.add(new Point2D.Double(1, 1)); + points.add(new Point2D.Double(11, 1)); + PolylineData pd = new PolylineData(points); + PolylineData pd2 = pd.reverse(); + assertTrue(pd.getBeginPoint().distance(pd2.getEndPoint()) <= Configuration.EPSILON); + assertTrue(pd2.getBeginPoint().distance(pd.getEndPoint()) <= Configuration.EPSILON); } @Test public void testEmptyLength() throws Exception { - try { - PolylineData pd = new PolylineData(); - pd.addPoint(new Point2D.Double(0, 0)); - assertEquals(0, pd.length(), Configuration.EPSILON); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + PolylineData pd = new PolylineData(); + pd.addPoint(new Point2D.Double(0, 0)); + assertEquals(0, pd.length(), Configuration.EPSILON); } - @Test + @Test(expected = InvalidArgumentException.class) public void testSetInvalidPoints() throws Exception { - try { - List<Point2D> points = new ArrayList<>(); - points.add(new Point2D.Double(Double.NEGATIVE_INFINITY, -10)); - PolylineData pd = new PolylineData(); - pd.setPoints(points); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + List<Point2D> points = new ArrayList<>(); + points.add(new Point2D.Double(Double.NEGATIVE_INFINITY, -10)); + PolylineData pd = new PolylineData(); + pd.setPoints(points); } @Test public void testGetters() throws Exception { - try { - PolylineData pd = new PolylineData(); - Color color = Color.BLACK; - LineType type = LineType.DASH_DOT; - String strWidth = "12"; - double width = 12.0; - int id = 3; - pd.setColor(color); - pd.setId(id); - pd.setType(type); - pd.setWidth(strWidth); - - assertEquals(id, pd.getId()); - assertEquals(color, pd.getColor()); - assertEquals(width, pd.getWidth(), Configuration.EPSILON); - assertEquals(type, pd.getType()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + PolylineData pd = new PolylineData(); + Color color = Color.BLACK; + LineType type = LineType.DASH_DOT; + String strWidth = "12"; + double width = 12.0; + int id = 3; + pd.setColor(color); + pd.setId(id); + pd.setType(type); + pd.setWidth(strWidth); + + assertEquals(id, pd.getId()); + assertEquals(color, pd.getColor()); + assertEquals(width, pd.getWidth(), Configuration.EPSILON); + assertEquals(type, pd.getType()); } @Test public void testSimpleCopy() throws Exception { - try { - PolylineData pd = new PolylineData(); - PolylineData pd2 = pd.copy(); - - assertNotNull(pd2); + PolylineData pd = new PolylineData(); + PolylineData pd2 = pd.copy(); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertNotNull(pd2); } - @Test + @Test(expected = NotImplementedException.class) public void testInvalidCopy() throws Exception { - try { - PolylineData pd = new PolylineData() { - - /** - * - */ - private static final long serialVersionUID = 1L; - }; - pd.copy(); - fail("Exception expected"); - } catch (NotImplementedException e) { - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Mockito.spy(PolylineData.class).copy(); } @Test public void testAddPointOrder() throws Exception { - try { - PolylineData pd = new PolylineData(); - pd.addPoint(new Point2D.Double(10, 10)); - pd.addPoint(new Point2D.Double(20, 20)); - assertEquals(new Point2D.Double(10, 10), pd.getPoints().get(0)); - assertEquals(new Point2D.Double(20, 20), pd.getPoints().get(1)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + PolylineData pd = new PolylineData(); + pd.addPoint(new Point2D.Double(10, 10)); + pd.addPoint(new Point2D.Double(20, 20)); + assertEquals(new Point2D.Double(10, 10), pd.getPoints().get(0)); + assertEquals(new Point2D.Double(20, 20), pd.getPoints().get(1)); } } diff --git a/model/src/test/java/lcsb/mapviewer/model/map/CommentTest.java b/model/src/test/java/lcsb/mapviewer/model/map/CommentTest.java index 65bdb2a74a9d7cee4f4d8bc9c3dc41cb53d2a81a..c18826c3041b44d8717ecff93b1ef0daf0329411 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/CommentTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/CommentTest.java @@ -1,90 +1,78 @@ package lcsb.mapviewer.model.map; -import static org.junit.Assert.assertEquals; +import static org.junit.Assert.*; import java.awt.geom.Point2D; import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; +import lcsb.mapviewer.ModelTestFunctions; import lcsb.mapviewer.model.map.model.Model; import lcsb.mapviewer.model.map.model.ModelFullIndexed; import lcsb.mapviewer.model.user.User; -public class CommentTest { +public class CommentTest extends ModelTestFunctions { - @Before - public void setUp() throws Exception { - } + @Before + public void setUp() throws Exception { + } - @After - public void tearDown() throws Exception { - } + @After + public void tearDown() throws Exception { + } - @Test - public void testSerialization() { - try { - SerializationUtils.serialize(new Comment()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } + @Test + public void testSerialization() { + SerializationUtils.serialize(new Comment()); + } - @Test - public void testGetters() { - try { - Comment comment = new Comment(); - String content = "c"; - Point2D.Double coordinates = new Point2D.Double(1, 2); - String email = "a"; - boolean deleted = true; - int id = 85; - Model model = new ModelFullIndexed(null); - String name = "n"; - boolean pinned = true; - String removeReason = "rr"; - Model submodel = new ModelFullIndexed(null); - Integer tableId = 5; - Class<?> tableName = Object.class; - User user = new User(); + @Test + public void testGetters() { + Comment comment = new Comment(); + String content = "c"; + Point2D.Double coordinates = new Point2D.Double(1, 2); + String email = "a"; + boolean deleted = true; + int id = 85; + Model model = new ModelFullIndexed(null); + String name = "n"; + boolean pinned = true; + String removeReason = "rr"; + Model submodel = new ModelFullIndexed(null); + Integer tableId = 5; + Class<?> tableName = Object.class; + User user = new User(); - comment.setContent(content); - assertEquals(content, comment.getContent()); - comment.setCoordinates(coordinates); - assertEquals(coordinates, comment.getCoordinates()); - comment.setDeleted(deleted); - assertEquals(deleted, comment.isDeleted()); - comment.setEmail(email); - assertEquals(email, comment.getEmail()); - comment.setId(id); - assertEquals(id, comment.getId()); - comment.setModel(model); - assertEquals(model, comment.getModelData().getModel()); - comment.setModelData(model.getModelData()); - assertEquals(model.getModelData(), comment.getModelData()); - comment.setName(name); - assertEquals(name, comment.getName()); - comment.setPinned(pinned); - assertEquals(pinned, comment.isPinned()); - comment.setRemoveReason(removeReason); - assertEquals(removeReason, comment.getRemoveReason()); - comment.setSubmodel(submodel); - assertEquals(submodel, comment.getSubmodel()); - comment.setSubmodelData(submodel.getModelData()); - assertEquals(submodel.getModelData(), comment.getSubmodelData()); - comment.setTableId(tableId); - assertEquals(tableId, comment.getTableId()); - comment.setTableName(tableName); - assertEquals(tableName, comment.getTableName()); - comment.setUser(user); - assertEquals(user, comment.getUser()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } + comment.setContent(content); + assertEquals(content, comment.getContent()); + comment.setCoordinates(coordinates); + assertEquals(coordinates, comment.getCoordinates()); + comment.setDeleted(deleted); + assertEquals(deleted, comment.isDeleted()); + comment.setEmail(email); + assertEquals(email, comment.getEmail()); + comment.setId(id); + assertEquals(id, comment.getId()); + comment.setModel(model); + assertEquals(model, comment.getModelData().getModel()); + comment.setModelData(model.getModelData()); + assertEquals(model.getModelData(), comment.getModelData()); + comment.setName(name); + assertEquals(name, comment.getName()); + comment.setPinned(pinned); + assertEquals(pinned, comment.isPinned()); + comment.setRemoveReason(removeReason); + assertEquals(removeReason, comment.getRemoveReason()); + comment.setSubmodel(submodel); + assertEquals(submodel, comment.getSubmodel()); + comment.setSubmodelData(submodel.getModelData()); + assertEquals(submodel.getModelData(), comment.getSubmodelData()); + comment.setTableId(tableId); + assertEquals(tableId, comment.getTableId()); + comment.setTableName(tableName); + assertEquals(tableName, comment.getTableName()); + comment.setUser(user); + assertEquals(user, comment.getUser()); + } } diff --git a/model/src/test/java/lcsb/mapviewer/model/map/ElementInFewParentsExceptionTest.java b/model/src/test/java/lcsb/mapviewer/model/map/ElementInFewParentsExceptionTest.java index ab1f0f351f02e30e59635a3c0a85264a6d46d145..5312d8be9dec8f56211251548db95ceebb282b5d 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/ElementInFewParentsExceptionTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/ElementInFewParentsExceptionTest.java @@ -1,28 +1,23 @@ package lcsb.mapviewer.model.map; import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; -public class ElementInFewParentsExceptionTest { +import lcsb.mapviewer.ModelTestFunctions; - @Before - public void setUp() throws Exception { - } +public class ElementInFewParentsExceptionTest extends ModelTestFunctions { - @After - public void tearDown() throws Exception { - } + @Before + public void setUp() throws Exception { + } - @Test - public void testSerialization() { - try { - SerializationUtils.serialize(new ElementInFewParentsException("")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } + @After + public void tearDown() throws Exception { + } + + @Test + public void testSerialization() { + SerializationUtils.serialize(new ElementInFewParentsException("")); + } } diff --git a/model/src/test/java/lcsb/mapviewer/model/map/InconsistentModelExceptionTest.java b/model/src/test/java/lcsb/mapviewer/model/map/InconsistentModelExceptionTest.java index 604387471b1acb7b9c4947ad8c26381f59362589..7305bdda1c7eb820cd200808be321a9bfad9ce9a 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/InconsistentModelExceptionTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/InconsistentModelExceptionTest.java @@ -1,28 +1,23 @@ package lcsb.mapviewer.model.map; import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; -public class InconsistentModelExceptionTest { +import lcsb.mapviewer.ModelTestFunctions; - @Before - public void setUp() throws Exception { - } +public class InconsistentModelExceptionTest extends ModelTestFunctions { - @After - public void tearDown() throws Exception { - } + @Before + public void setUp() throws Exception { + } - @Test - public void testSerialization() { - try { - SerializationUtils.serialize(new InconsistentModelException("")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } + @After + public void tearDown() throws Exception { + } + + @Test + public void testSerialization() { + SerializationUtils.serialize(new InconsistentModelException("")); + } } diff --git a/model/src/test/java/lcsb/mapviewer/model/map/MiriamDataTest.java b/model/src/test/java/lcsb/mapviewer/model/map/MiriamDataTest.java index a8dca2f41f418114c68e6e7bd2fe050e0168a95f..285e42aa66ec2005d30198761fdfcc51733bfcc4 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/MiriamDataTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/MiriamDataTest.java @@ -1,135 +1,82 @@ package lcsb.mapviewer.model.map; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; +import lcsb.mapviewer.ModelTestFunctions; import lcsb.mapviewer.common.exception.InvalidArgumentException; -public class MiriamDataTest { - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testSerialization() { - try { - SerializationUtils.serialize(new MiriamData()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testInvalidConstructor1() { - try { - new MiriamData(null, null); - fail("Exception expection"); - } catch (InvalidArgumentException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testInvalidConstructor2() { - try { - new MiriamData(null, MiriamType.CAS, null); - fail("Exception expection"); - } catch (InvalidArgumentException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testGetIdFromIdentifier() { - try { - assertEquals("id", MiriamData.getIdFromIdentifier("name:id")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testGetters() { - try { - int id = 6; - MiriamData md = new MiriamData(); - md.setResource(null); - assertNull(md.getResource()); - - md.setId(id); - assertEquals(id, md.getId()); - - md.setAnnotator(this.getClass()); - assertEquals(this.getClass(), md.getAnnotator()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testToString() { - try { - assertNotNull(new MiriamData().toString()); - assertNotNull(new MiriamData(MiriamType.CAS, "a").toString()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testEqual() { - try { - MiriamData md = new MiriamData(); - assertFalse(md.equals(new Object())); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testCompareTo() { - try { - MiriamData md = new MiriamData(); - assertTrue(md.compareTo(new MiriamData(MiriamType.CAS, "a")) != 0); - - MiriamData md1 = new MiriamData(MiriamType.CAS, "a"); - MiriamData md2 = new MiriamData(MiriamType.CAS, "a"); - assertTrue(md1.compareTo(md2) == 0); - - md1.setAnnotator(Integer.class); - assertTrue(md1.compareTo(md2) != 0); - - md2.setAnnotator(Integer.class); - assertTrue(md1.compareTo(md2) == 0); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } +public class MiriamDataTest extends ModelTestFunctions { + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testSerialization() { + SerializationUtils.serialize(new MiriamData()); + } + + @Test(expected = InvalidArgumentException.class) + public void testInvalidConstructor1() { + new MiriamData(null, null); + } + + @Test(expected = InvalidArgumentException.class) + public void testInvalidConstructor2() { + new MiriamData(null, MiriamType.CAS, null); + } + + @Test + public void testGetIdFromIdentifier() { + assertEquals("id", MiriamData.getIdFromIdentifier("name:id")); + } + + @Test + public void testGetters() { + int id = 6; + MiriamData md = new MiriamData(); + md.setResource(null); + assertNull(md.getResource()); + + md.setId(id); + assertEquals(id, md.getId()); + + md.setAnnotator(this.getClass()); + assertEquals(this.getClass(), md.getAnnotator()); + } + + @Test + public void testToString() { + assertNotNull(new MiriamData().toString()); + assertNotNull(new MiriamData(MiriamType.CAS, "a").toString()); + } + + @Test + public void testEqual() { + MiriamData md = new MiriamData(); + assertFalse(md.equals(new Object())); + } + + @Test + public void testCompareTo() { + MiriamData md = new MiriamData(); + assertTrue(md.compareTo(new MiriamData(MiriamType.CAS, "a")) != 0); + + MiriamData md1 = new MiriamData(MiriamType.CAS, "a"); + MiriamData md2 = new MiriamData(MiriamType.CAS, "a"); + assertTrue(md1.compareTo(md2) == 0); + + md1.setAnnotator(Integer.class); + assertTrue(md1.compareTo(md2) != 0); + + md2.setAnnotator(Integer.class); + assertTrue(md1.compareTo(md2) == 0); + } } diff --git a/model/src/test/java/lcsb/mapviewer/model/map/MiriamTypeNameComparatorTest.java b/model/src/test/java/lcsb/mapviewer/model/map/MiriamTypeNameComparatorTest.java index 8dba86059018e90b5ad36d8eef0078d535aae4ec..647b22bcc3fa33b941a019fd4823d3d74d95d7c4 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/MiriamTypeNameComparatorTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/MiriamTypeNameComparatorTest.java @@ -1,46 +1,35 @@ package lcsb.mapviewer.model.map; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -public class MiriamTypeNameComparatorTest { - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testCompareNulls() { - try { - MiriamTypeNameComparator comparator = new MiriamTypeNameComparator(); - assertEquals(0, comparator.compare(null, null)); - assertTrue(comparator.compare(null, MiriamType.CAS) != 0); - assertTrue(comparator.compare(MiriamType.CAS, null) != 0); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testCompare() { - try { - MiriamTypeNameComparator comparator = new MiriamTypeNameComparator(); - assertTrue(comparator.compare(MiriamType.CHEBI, MiriamType.CAS) < 0); - assertTrue(comparator.compare(MiriamType.CAS, MiriamType.CHEBI) > 0); - assertTrue(comparator.compare(MiriamType.CAS, MiriamType.CAS) == 0); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } +import static org.junit.Assert.*; + +import org.junit.*; + +import lcsb.mapviewer.ModelTestFunctions; + +public class MiriamTypeNameComparatorTest extends ModelTestFunctions { + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testCompareNulls() { + MiriamTypeNameComparator comparator = new MiriamTypeNameComparator(); + assertEquals(0, comparator.compare(null, null)); + assertTrue(comparator.compare(null, MiriamType.CAS) != 0); + assertTrue(comparator.compare(MiriamType.CAS, null) != 0); + } + + @Test + public void testCompare() { + MiriamTypeNameComparator comparator = new MiriamTypeNameComparator(); + assertTrue(comparator.compare(MiriamType.CHEBI, MiriamType.CAS) < 0); + assertTrue(comparator.compare(MiriamType.CAS, MiriamType.CHEBI) > 0); + assertTrue(comparator.compare(MiriamType.CAS, MiriamType.CAS) == 0); + } } diff --git a/model/src/test/java/lcsb/mapviewer/model/map/MiriamTypeTest.java b/model/src/test/java/lcsb/mapviewer/model/map/MiriamTypeTest.java index bbb763b3e4920054c4bb2b1e6cbd90587e270780..5b4ae3f30980d935ff3801d0436cb78d60ac0672 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/MiriamTypeTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/MiriamTypeTest.java @@ -1,22 +1,18 @@ package lcsb.mapviewer.model.map; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import java.util.HashMap; import java.util.Map; -import org.apache.logging.log4j.*; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.junit.*; +import lcsb.mapviewer.ModelTestFunctions; import lcsb.mapviewer.common.exception.InvalidArgumentException; -public class MiriamTypeTest { +public class MiriamTypeTest extends ModelTestFunctions { Logger logger = LogManager.getLogger(MiriamDataTest.class); @Before @@ -29,24 +25,19 @@ public class MiriamTypeTest { @Test public void testIdUniqness() { - try { - Map<String, MiriamType> ids = new HashMap<>(); - for (MiriamType mt : MiriamType.values()) { - assertNull(mt.getCommonName() + " doesn't have a unique key", ids.get(mt.getRegistryIdentifier())); - ids.put(mt.getRegistryIdentifier(), mt); - - // coverage tests - assertNotNull(MiriamType.valueOf(mt.name())); - assertNotNull(mt.getUris()); - assertNotNull(mt.getValidClass()); - assertNotNull(mt.getRequiredClass()); - if (mt != MiriamType.UNKNOWN) { - assertNotNull("No homepage for: " + mt, mt.getDbHomepage()); - } + Map<String, MiriamType> ids = new HashMap<>(); + for (MiriamType mt : MiriamType.values()) { + assertNull(mt.getCommonName() + " doesn't have a unique key", ids.get(mt.getRegistryIdentifier())); + ids.put(mt.getRegistryIdentifier(), mt); + + // coverage tests + assertNotNull(MiriamType.valueOf(mt.name())); + assertNotNull(mt.getUris()); + assertNotNull(mt.getValidClass()); + assertNotNull(mt.getRequiredClass()); + if (mt != MiriamType.UNKNOWN) { + assertNotNull("No homepage for: " + mt, mt.getDbHomepage()); } - } catch (Exception e) { - e.printStackTrace(); - throw e; } } @@ -56,24 +47,14 @@ public class MiriamTypeTest { assertEquals(new MiriamData(MiriamType.HGNC_SYMBOL, "SNCA"), md); } - @Test + @Test(expected = InvalidArgumentException.class) public void testGetMiriamDataFromInvalidIdentifier() { - try { - MiriamType.getMiriamDataFromIdentifier("xyz:SNCA"); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - - } + MiriamType.getMiriamDataFromIdentifier("xyz:SNCA"); } - @Test + @Test(expected = InvalidArgumentException.class) public void testGetMiriamDataFromInvalidIdentifier2() { - try { - MiriamType.getMiriamDataFromIdentifier("xyz"); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - - } + MiriamType.getMiriamDataFromIdentifier("xyz"); } @Test @@ -90,58 +71,31 @@ public class MiriamTypeTest { @Test public void testGetMiriamByUri1() throws Exception { - try { - MiriamData md = MiriamType.getMiriamByUri("urn:miriam:panther.family:PTHR19384:SF5"); - assertTrue(new MiriamData(MiriamType.PANTHER, "PTHR19384:SF5").equals(md)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + MiriamData md = MiriamType.getMiriamByUri("urn:miriam:panther.family:PTHR19384:SF5"); + assertTrue(new MiriamData(MiriamType.PANTHER, "PTHR19384:SF5").equals(md)); } @Test public void testGetMiriamForVmhMetabolite() throws Exception { - try { - MiriamData md = MiriamType.getMiriamByUri("urn:miriam:vmhmetabolite:o2"); - assertNotNull(md); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + MiriamData md = MiriamType.getMiriamByUri("urn:miriam:vmhmetabolite:o2"); + assertNotNull(md); } @Test public void testGetMiriamByUri2() throws Exception { - try { - MiriamData md = MiriamType.getMiriamByUri("urn:miriam:panther.family:PTHR19384%3ASF5"); - assertTrue(new MiriamData(MiriamType.PANTHER, "PTHR19384:SF5").equals(md)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + MiriamData md = MiriamType.getMiriamByUri("urn:miriam:panther.family:PTHR19384%3ASF5"); + assertTrue(new MiriamData(MiriamType.PANTHER, "PTHR19384:SF5").equals(md)); } @Test public void testGetMiriamByUri3() throws Exception { - try { - MiriamData md = MiriamType.getMiriamByUri("urn:miriam:panther.family%3APTHR19384%3ASF5"); - assertTrue(new MiriamData(MiriamType.PANTHER, "PTHR19384:SF5").equals(md)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + MiriamData md = MiriamType.getMiriamByUri("urn:miriam:panther.family%3APTHR19384%3ASF5"); + assertTrue(new MiriamData(MiriamType.PANTHER, "PTHR19384:SF5").equals(md)); } - @Test + @Test(expected = InvalidArgumentException.class) public void testGetMiriamByInvalidUri() throws Exception { - try { - MiriamType.getMiriamByUri("invalid_uri"); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + MiriamType.getMiriamByUri("invalid_uri"); } @Test @@ -152,9 +106,6 @@ public class MiriamTypeTest { MiriamType.getMiriamByUri(uri); fail("Exception expected"); } catch (InvalidArgumentException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; } } } diff --git a/model/src/test/java/lcsb/mapviewer/model/map/OverviewImageComparatorTest.java b/model/src/test/java/lcsb/mapviewer/model/map/OverviewImageComparatorTest.java index 7bbbc7a1bcc1c91d0c4ee4d3f5db20e355078169..3dd25d449137ee1207fc624c3d3dfd0abf0b4963 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/OverviewImageComparatorTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/OverviewImageComparatorTest.java @@ -1,92 +1,80 @@ package lcsb.mapviewer.model.map; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.Assert.*; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; +import org.mockito.Mockito; -public class OverviewImageComparatorTest { +import lcsb.mapviewer.ModelTestFunctions; +import lcsb.mapviewer.model.map.layout.graphics.Layer; - @Before - public void setUp() throws Exception { - } +public class OverviewImageComparatorTest extends ModelTestFunctions { - @After - public void tearDown() throws Exception { - } + @Before + public void setUp() throws Exception { + } - @Test - public void testEqual() throws Exception { - try { - OverviewImageComparator oic = new OverviewImageComparator(); + @After + public void tearDown() throws Exception { + } - OverviewImage oi = new OverviewImage(); - OverviewImage oi2 = new OverviewImage(); + @Test + public void testEqual() throws Exception { + OverviewImageComparator oic = new OverviewImageComparator(); - assertEquals(0, oic.compare(oi, oi2)); - assertEquals(0, oic.compare(null, null)); + OverviewImage oi = new OverviewImage(); + OverviewImage oi2 = new OverviewImage(); - oi.addLink(new OverviewImageLink()); - oi2.addLink(new OverviewImageLink()); - assertEquals(0, oic.compare(oi, oi2)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } + assertEquals(0, oic.compare(oi, oi2)); + assertEquals(0, oic.compare(null, null)); - @Test - public void testDifferent() throws Exception { - try { - OverviewImageComparator oic = new OverviewImageComparator(); + oi.addLink(new OverviewImageLink()); + oi2.addLink(new OverviewImageLink()); + assertEquals(0, oic.compare(oi, oi2)); + } - OverviewImage oi = new OverviewImage(); + @Test + public void testDifferent() throws Exception { + OverviewImageComparator oic = new OverviewImageComparator(); - OverviewImage oi2 = new OverviewImage(); - oi2.setFilename("x"); + OverviewImage oi = new OverviewImage(); - assertTrue(0 != oic.compare(oi, oi2)); + OverviewImage oi2 = new OverviewImage(); + oi2.setFilename("x"); - oi2 = new OverviewImage(); - oi2.setHeight(1); + assertTrue(0 != oic.compare(oi, oi2)); - assertTrue(0 != oic.compare(oi, oi2)); + oi2 = new OverviewImage(); + oi2.setHeight(1); - oi2 = new OverviewImage(); - oi2.setWidth(2); - ; + assertTrue(0 != oic.compare(oi, oi2)); - assertTrue(0 != oic.compare(oi, oi2)); + oi2 = new OverviewImage(); + oi2.setWidth(2); + ; - oi2 = new OverviewImage(); - oi2.addLink(new OverviewModelLink()); + assertTrue(0 != oic.compare(oi, oi2)); - assertTrue(0 != oic.compare(oi, oi2)); + oi2 = new OverviewImage(); + oi2.addLink(new OverviewModelLink()); - assertTrue(0 != oic.compare(oi, null)); - assertTrue(0 != oic.compare(null, oi2)); + assertTrue(0 != oic.compare(oi, oi2)); - assertTrue(0 != oic.compare(new OverviewImage() { - private static final long serialVersionUID = 1L; - }, oi2)); - - oi = new OverviewImage(); - oi2 = new OverviewImage(); - OverviewImageLink link= new OverviewImageLink(); - link.setPolygon("1,1"); - oi.addLink(link); - link= new OverviewImageLink(); - link.setPolygon("1,2"); - oi2.addLink(link); + assertTrue(0 != oic.compare(oi, null)); + assertTrue(0 != oic.compare(null, oi2)); - assertTrue(0 != oic.compare(oi, oi2)); + assertTrue(0 != oic.compare(Mockito.spy(OverviewImage.class), oi2)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } + oi = new OverviewImage(); + oi2 = new OverviewImage(); + OverviewImageLink link = new OverviewImageLink(); + link.setPolygon("1,1"); + oi.addLink(link); + link = new OverviewImageLink(); + link.setPolygon("1,2"); + oi2.addLink(link); + + assertTrue(0 != oic.compare(oi, oi2)); + } } diff --git a/model/src/test/java/lcsb/mapviewer/model/map/OverviewImageLinkComparatorTest.java b/model/src/test/java/lcsb/mapviewer/model/map/OverviewImageLinkComparatorTest.java index 858b560e521e2737581d75fb33824493be5c2403..03730632489f53d43591c267fbf40839400c4b7e 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/OverviewImageLinkComparatorTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/OverviewImageLinkComparatorTest.java @@ -2,11 +2,13 @@ package lcsb.mapviewer.model.map; import static org.junit.Assert.*; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; +import org.mockito.Mockito; -public class OverviewImageLinkComparatorTest { +import lcsb.mapviewer.ModelTestFunctions; +import lcsb.mapviewer.model.map.layout.graphics.Layer; + +public class OverviewImageLinkComparatorTest extends ModelTestFunctions { @Before public void setUp() throws Exception { @@ -18,80 +20,56 @@ public class OverviewImageLinkComparatorTest { @Test public void testEqual() throws Exception { - try { - OverviewImageLinkComparator oic = new OverviewImageLinkComparator(); - - OverviewImageLink oi = new OverviewImageLink(); - OverviewImageLink oi2 = new OverviewImageLink(); + OverviewImageLinkComparator oic = new OverviewImageLinkComparator(); - assertEquals(0, oic.compare(oi, oi2)); - assertEquals(0, oic.compare(null, null)); + OverviewImageLink oi = new OverviewImageLink(); + OverviewImageLink oi2 = new OverviewImageLink(); - oi2.setLinkedOverviewImage(new OverviewImage()); - oi.setLinkedOverviewImage(new OverviewImage()); - assertEquals(0, oic.compare(oi, oi2)); + assertEquals(0, oic.compare(oi, oi2)); + assertEquals(0, oic.compare(null, null)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + oi2.setLinkedOverviewImage(new OverviewImage()); + oi.setLinkedOverviewImage(new OverviewImage()); + assertEquals(0, oic.compare(oi, oi2)); } @Test public void testDifferent() throws Exception { - try { - OverviewImageLinkComparator oic = new OverviewImageLinkComparator(); - - OverviewImageLink oi = new OverviewImageLink(); + OverviewImageLinkComparator oic = new OverviewImageLinkComparator(); - OverviewImageLink oi2 = new OverviewImageLink(); - oi2.setLinkedOverviewImage(new OverviewImage()); + OverviewImageLink oi = new OverviewImageLink(); - assertTrue(0 != oic.compare(oi, oi2)); - assertTrue(0 != oic.compare(oi2, oi)); + OverviewImageLink oi2 = new OverviewImageLink(); + oi2.setLinkedOverviewImage(new OverviewImage()); - oi2 = new OverviewImageLink(); - oi2.setLinkedOverviewImage(new OverviewImage()); + assertTrue(0 != oic.compare(oi, oi2)); + assertTrue(0 != oic.compare(oi2, oi)); - assertTrue(0 != oic.compare(oi, oi2)); - assertTrue(0 != oic.compare(oi2, oi)); + oi2 = new OverviewImageLink(); + oi2.setLinkedOverviewImage(new OverviewImage()); - oi2 = new OverviewImageLink(); - oi2.setPolygon("AS"); + assertTrue(0 != oic.compare(oi, oi2)); + assertTrue(0 != oic.compare(oi2, oi)); - assertTrue(0 != oic.compare(oi, oi2)); - assertTrue(0 != oic.compare(oi, null)); - assertTrue(0 != oic.compare(null, oi2)); - assertTrue(0 != oic.compare(new OverviewImageLink() { + oi2 = new OverviewImageLink(); + oi2.setPolygon("AS"); - /** - * - */ - private static final long serialVersionUID = 1L; - }, oi2)); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertTrue(0 != oic.compare(oi, oi2)); + assertTrue(0 != oic.compare(oi, null)); + assertTrue(0 != oic.compare(null, oi2)); + assertTrue(0 != oic.compare(Mockito.spy(OverviewImageLink.class), oi2)); } @Test public void testDifferentPolygon() throws Exception { - try { - OverviewImageLinkComparator comparator = new OverviewImageLinkComparator(); - - OverviewImageLink iml1 = new OverviewImageLink(); - OverviewImageLink iml2 = new OverviewImageLink(); - iml2.setPolygon("1,2"); + OverviewImageLinkComparator comparator = new OverviewImageLinkComparator(); - assertTrue(0 != comparator.compare(iml1, iml2)); - assertTrue(0 != comparator.compare(iml2, iml1)); + OverviewImageLink iml1 = new OverviewImageLink(); + OverviewImageLink iml2 = new OverviewImageLink(); + iml2.setPolygon("1,2"); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertTrue(0 != comparator.compare(iml1, iml2)); + assertTrue(0 != comparator.compare(iml2, iml1)); } } diff --git a/model/src/test/java/lcsb/mapviewer/model/map/OverviewImageLinkTest.java b/model/src/test/java/lcsb/mapviewer/model/map/OverviewImageLinkTest.java index 5fbc34240070f0bdddf707cba226a4dd4b9045c0..7d03e3da8f6b55109e31a3f0677fc65eb52ba26e 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/OverviewImageLinkTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/OverviewImageLinkTest.java @@ -1,63 +1,40 @@ package lcsb.mapviewer.model.map; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; +import org.mockito.Mockito; +import lcsb.mapviewer.ModelTestFunctions; import lcsb.mapviewer.common.exception.NotImplementedException; - -public class OverviewImageLinkTest { - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testSerialization() { - try { - SerializationUtils.serialize(new OverviewImageLink()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testCopy() { - try { - OverviewImageLink original = new OverviewImageLink(); - OverviewImageLink degraded = original.copy(); - assertNotNull(degraded); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testInvalidCopy() { - try { - new OverviewImageLink() { - - /** - * - */ - private static final long serialVersionUID = 1L; - }.copy(); - fail("Exception expected"); - } catch (NotImplementedException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } +import lcsb.mapviewer.model.map.layout.graphics.Layer; + +public class OverviewImageLinkTest extends ModelTestFunctions { + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testSerialization() { + SerializationUtils.serialize(new OverviewImageLink()); + } + + @Test + public void testCopy() { + OverviewImageLink original = new OverviewImageLink(); + OverviewImageLink degraded = original.copy(); + assertNotNull(degraded); + } + + @Test(expected = NotImplementedException.class) + public void testInvalidCopy() { + Mockito.spy(OverviewImageLink.class).copy(); + } } diff --git a/model/src/test/java/lcsb/mapviewer/model/map/OverviewImageTest.java b/model/src/test/java/lcsb/mapviewer/model/map/OverviewImageTest.java index eccd4f9b06c11fb0965610b2fe1ee1c11975781f..3de5cdfaae8edacd6270939912df6b56a42e9b5e 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/OverviewImageTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/OverviewImageTest.java @@ -1,82 +1,53 @@ package lcsb.mapviewer.model.map; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import java.util.ArrayList; import java.util.List; import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; +import org.mockito.Mockito; +import lcsb.mapviewer.ModelTestFunctions; import lcsb.mapviewer.common.exception.NotImplementedException; - -public class OverviewImageTest { - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testSerialization() { - try { - SerializationUtils.serialize(new OverviewImage()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testCopy() { - try { - OverviewImage original = new OverviewImage(); - original.addLink(new OverviewImageLink()); - OverviewImage degraded = original.copy(); - assertNotNull(degraded); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testSetters() { - try { - OverviewImage original = new OverviewImage(); - List<OverviewLink> links = new ArrayList<>(); - original.setLinks(links); - - assertEquals(links, original.getLinks()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testInvalidCopy() { - try { - new OverviewImage() { - - /** - * - */ - private static final long serialVersionUID = 1L; - }.copy(); - fail("Exception expected"); - } catch (NotImplementedException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } +import lcsb.mapviewer.model.map.layout.graphics.Layer; + +public class OverviewImageTest extends ModelTestFunctions { + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testSerialization() { + SerializationUtils.serialize(new OverviewImage()); + } + + @Test + public void testCopy() { + OverviewImage original = new OverviewImage(); + original.addLink(new OverviewImageLink()); + OverviewImage degraded = original.copy(); + assertNotNull(degraded); + } + + @Test + public void testSetters() { + OverviewImage original = new OverviewImage(); + List<OverviewLink> links = new ArrayList<>(); + original.setLinks(links); + + assertEquals(links, original.getLinks()); + } + + @Test(expected = NotImplementedException.class) + public void testInvalidCopy() { + Mockito.spy(OverviewImage.class).copy(); + } } diff --git a/model/src/test/java/lcsb/mapviewer/model/map/OverviewLinkComparatorTest.java b/model/src/test/java/lcsb/mapviewer/model/map/OverviewLinkComparatorTest.java index ccd5ca3c3fc19edacfcc09dfcede6dcde12e3105..acd59e7d1aabd4f335bd0255ef904ee62c0f1a3b 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/OverviewLinkComparatorTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/OverviewLinkComparatorTest.java @@ -1,18 +1,15 @@ package lcsb.mapviewer.model.map; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; +import lcsb.mapviewer.ModelTestFunctions; import lcsb.mapviewer.common.exception.NotImplementedException; import lcsb.mapviewer.model.map.model.ModelData; import lcsb.mapviewer.model.map.model.ModelFullIndexed; -public class OverviewLinkComparatorTest { +public class OverviewLinkComparatorTest extends ModelTestFunctions { @Before public void setUp() throws Exception { @@ -24,70 +21,50 @@ public class OverviewLinkComparatorTest { @Test public void testEqual() throws Exception { - try { - OverviewLinkComparator omlc = new OverviewLinkComparator(); + OverviewLinkComparator omlc = new OverviewLinkComparator(); - OverviewModelLink oml = new OverviewModelLink(); - OverviewModelLink oml2 = new OverviewModelLink(); + OverviewModelLink oml = new OverviewModelLink(); + OverviewModelLink oml2 = new OverviewModelLink(); - assertEquals(0, omlc.compare(oml, oml2)); - assertEquals(0, omlc.compare(null, null)); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, omlc.compare(oml, oml2)); + assertEquals(0, omlc.compare(null, null)); } - @Test + @Test(expected = NotImplementedException.class) public void testInvalid() throws Exception { - try { - class Tmp extends OverviewLink { - private static final long serialVersionUID = 1L; - - @Override - public OverviewLink copy() { - return null; - } - } - ; - OverviewLinkComparator omlc = new OverviewLinkComparator(); + class Tmp extends OverviewLink { + private static final long serialVersionUID = 1L; - OverviewLink oml = new Tmp(); - OverviewLink oml2 = new Tmp(); + @Override + public OverviewLink copy() { + return null; + } + } + ; + OverviewLinkComparator omlc = new OverviewLinkComparator(); - omlc.compare(oml, oml2); + OverviewLink oml = new Tmp(); + OverviewLink oml2 = new Tmp(); - fail("Exception expected"); - } catch (NotImplementedException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + omlc.compare(oml, oml2); } @Test public void testDifferent() throws Exception { - try { - OverviewLinkComparator omlc = new OverviewLinkComparator(); + OverviewLinkComparator omlc = new OverviewLinkComparator(); - OverviewModelLink oml = new OverviewModelLink(); - OverviewImageLink iml = new OverviewImageLink(); + OverviewModelLink oml = new OverviewModelLink(); + OverviewImageLink iml = new OverviewImageLink(); - assertTrue(0 != omlc.compare(oml, iml)); - assertTrue(0 != omlc.compare(oml, null)); - assertTrue(0 != omlc.compare(null, iml)); + assertTrue(0 != omlc.compare(oml, iml)); + assertTrue(0 != omlc.compare(oml, null)); + assertTrue(0 != omlc.compare(null, iml)); - oml = new OverviewModelLink(); - OverviewModelLink oml2 = new OverviewModelLink(); - oml2.setLinkedModel(new ModelFullIndexed(new ModelData())); + oml = new OverviewModelLink(); + OverviewModelLink oml2 = new OverviewModelLink(); + oml2.setLinkedModel(new ModelFullIndexed(new ModelData())); - assertTrue(0 != omlc.compare(oml, oml2)); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertTrue(0 != omlc.compare(oml, oml2)); } } diff --git a/model/src/test/java/lcsb/mapviewer/model/map/OverviewLinkTest.java b/model/src/test/java/lcsb/mapviewer/model/map/OverviewLinkTest.java index 7287d170cbf1fc640971e8d68b8a5f1dd2d23aad..fff035e5f80ad85442e1e59c2c3c0eebbd3b6e6f 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/OverviewLinkTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/OverviewLinkTest.java @@ -1,73 +1,41 @@ package lcsb.mapviewer.model.map; -import static org.junit.Assert.assertEquals; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -public class OverviewLinkTest { - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testGetPolygonCoord() { - try { - OverviewLink link = new OverviewLink() { - - /** - * - */ - private static final long serialVersionUID = 1L; - - @Override - public OverviewLink copy() { - // TODO Auto-generated method stub - return null; - } - }; - String polygon = "1,1 2,2 4,0"; - link.setPolygon(polygon); - assertEquals(3, link.getPolygonCoordinates().size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testGetters() { - try { - OverviewLink link = new OverviewLink() { - - /** - * - */ - private static final long serialVersionUID = 1L; - - @Override - public OverviewLink copy() { - // TODO Auto-generated method stub - return null; - } - }; - OverviewImage image= new OverviewImage(); - int id = 309; - link.setOverviewImage(image); - link.setId(id); - - assertEquals(image, link.getOverviewImage()); - assertEquals(id, link.getId()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } +import static org.junit.Assert.*; + +import org.junit.*; +import org.mockito.Mockito; + +import lcsb.mapviewer.ModelTestFunctions; +import lcsb.mapviewer.model.map.layout.graphics.Layer; + +public class OverviewLinkTest extends ModelTestFunctions { + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testGetPolygonCoord() { + OverviewLink link = Mockito.spy(OverviewLink.class); + String polygon = "1,1 2,2 4,0"; + link.setPolygon(polygon); + assertEquals(3, link.getPolygonCoordinates().size()); + } + + @Test + public void testGetters() { + OverviewLink link = Mockito.spy(OverviewLink.class); + OverviewImage image = new OverviewImage(); + int id = 309; + link.setOverviewImage(image); + link.setId(id); + + assertEquals(image, link.getOverviewImage()); + assertEquals(id, link.getId()); + } } diff --git a/model/src/test/java/lcsb/mapviewer/model/map/OverviewModelLinkComparatorTest.java b/model/src/test/java/lcsb/mapviewer/model/map/OverviewModelLinkComparatorTest.java index 38b6e3b8a6c2fbf7ebde4800b7fa88107328b419..b6a85d55f20b04e526769068d4757efec6d8f96c 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/OverviewModelLinkComparatorTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/OverviewModelLinkComparatorTest.java @@ -2,106 +2,86 @@ package lcsb.mapviewer.model.map; import static org.junit.Assert.*; +import org.junit.*; +import org.mockito.Mockito; + +import lcsb.mapviewer.ModelTestFunctions; import lcsb.mapviewer.model.map.model.Model; import lcsb.mapviewer.model.map.model.ModelFullIndexed; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -public class OverviewModelLinkComparatorTest { - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testEqual() throws Exception { - try { - OverviewModelLinkComparator oic = new OverviewModelLinkComparator(); +public class OverviewModelLinkComparatorTest extends ModelTestFunctions { - OverviewModelLink oi = new OverviewModelLink(); - OverviewModelLink oi2 = new OverviewModelLink(); + @Before + public void setUp() throws Exception { + } - assertEquals(0, oic.compare(oi, oi2)); - assertEquals(0, oic.compare(null, null)); + @After + public void tearDown() throws Exception { + } - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } + @Test + public void testEqual() throws Exception { + OverviewModelLinkComparator oic = new OverviewModelLinkComparator(); - @Test - public void testDifferent() throws Exception { - try { - OverviewModelLinkComparator oic = new OverviewModelLinkComparator(); + OverviewModelLink oi = new OverviewModelLink(); + OverviewModelLink oi2 = new OverviewModelLink(); - OverviewModelLink oi = new OverviewModelLink(); + assertEquals(0, oic.compare(oi, oi2)); + assertEquals(0, oic.compare(null, null)); + } - OverviewModelLink oi2 = new OverviewModelLink(); - oi2.setLinkedModel(new ModelFullIndexed(null)); + @Test + public void testDifferent() throws Exception { + OverviewModelLinkComparator oic = new OverviewModelLinkComparator(); - assertTrue(0 != oic.compare(oi, oi2)); - assertTrue(0 != oic.compare(oi2, oi)); - assertTrue(0 != oic.compare(oi, null)); - assertTrue(0 != oic.compare(null, oi2)); + OverviewModelLink oi = new OverviewModelLink(); - Model model = new ModelFullIndexed(null); - model.setId(1); - oi.setLinkedModel(model); - assertTrue(0 != oic.compare(oi, oi2)); + OverviewModelLink oi2 = new OverviewModelLink(); + oi2.setLinkedModel(new ModelFullIndexed(null)); - oi2 = new OverviewModelLink(); - oi2.setPolygon("AS"); + assertTrue(0 != oic.compare(oi, oi2)); + assertTrue(0 != oic.compare(oi2, oi)); + assertTrue(0 != oic.compare(oi, null)); + assertTrue(0 != oic.compare(null, oi2)); - assertTrue(0 != oic.compare(oi, oi2)); + Model model = new ModelFullIndexed(null); + model.setId(1); + oi.setLinkedModel(model); + assertTrue(0 != oic.compare(oi, oi2)); - oi2 = new OverviewModelLink(); - oi2.setxCoord(12); + oi2 = new OverviewModelLink(); + oi2.setPolygon("AS"); - assertTrue(0 != oic.compare(oi, oi2)); + assertTrue(0 != oic.compare(oi, oi2)); - oi2 = new OverviewModelLink(); - oi2.setyCoord(13); + oi2 = new OverviewModelLink(); + oi2.setxCoord(12); - assertTrue(0 != oic.compare(oi, oi2)); + assertTrue(0 != oic.compare(oi, oi2)); - oi2 = new OverviewModelLink(); - oi2.setZoomLevel(345); + oi2 = new OverviewModelLink(); + oi2.setyCoord(13); - assertTrue(0 != oic.compare(oi, oi2)); + assertTrue(0 != oic.compare(oi, oi2)); - assertTrue(0 != oic.compare(oi, new OverviewModelLink() { - private static final long serialVersionUID = 1L; - })); + oi2 = new OverviewModelLink(); + oi2.setZoomLevel(345); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } + assertTrue(0 != oic.compare(oi, oi2)); - @Test - public void testDifferentPolygon() throws Exception { - try { - OverviewModelLinkComparator comparator = new OverviewModelLinkComparator(); + assertTrue(0 != oic.compare(oi, Mockito.spy(OverviewModelLink.class))); + } - OverviewModelLink iml1 = new OverviewModelLink(); - OverviewModelLink iml2 = new OverviewModelLink(); - iml2.setPolygon("1,2"); + @Test + public void testDifferentPolygon() throws Exception { + OverviewModelLinkComparator comparator = new OverviewModelLinkComparator(); - assertTrue(0 != comparator.compare(iml1, iml2)); - assertTrue(0 != comparator.compare(iml2, iml1)); + OverviewModelLink iml1 = new OverviewModelLink(); + OverviewModelLink iml2 = new OverviewModelLink(); + iml2.setPolygon("1,2"); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } + assertTrue(0 != comparator.compare(iml1, iml2)); + assertTrue(0 != comparator.compare(iml2, iml1)); + } } diff --git a/model/src/test/java/lcsb/mapviewer/model/map/OverviewModelLinkTest.java b/model/src/test/java/lcsb/mapviewer/model/map/OverviewModelLinkTest.java index f2044c6d788df8654a9bedf56438fbafbe898ce1..e78eff0a670ab81b6cc65086cad6efa463548b79 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/OverviewModelLinkTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/OverviewModelLinkTest.java @@ -1,98 +1,62 @@ package lcsb.mapviewer.model.map; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; +import org.mockito.Mockito; +import lcsb.mapviewer.ModelTestFunctions; import lcsb.mapviewer.common.exception.NotImplementedException; -public class OverviewModelLinkTest { - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testSerialization() { - try { - SerializationUtils.serialize(new OverviewModelLink()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testConstructor() { - try { - OverviewModelLink link = new OverviewModelLink(new OverviewModelLink()); - assertNotNull(link); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testSetters() { - try { - OverviewModelLink link = new OverviewModelLink(); - link.setLinkedModel(null); - assertNull(link.getLinkedModel()); - - link.setxCoord(2.0); - link.setyCoord(3.0); - - assertEquals((Integer) 2, link.getxCoord()); - assertEquals((Integer) 3, link.getyCoord()); - - link.setxCoord((Double) null); - link.setyCoord((Double) null); - assertNull(link.getxCoord()); - assertNull(link.getyCoord()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testCopy() { - try { - OverviewModelLink degraded = new OverviewModelLink().copy(); - assertNotNull(degraded); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testInvalidCopy() { - try { - new OverviewModelLink() { - - /** - * - */ - private static final long serialVersionUID = 1L; - }.copy(); - fail("Exception expected"); - } catch (NotImplementedException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } +public class OverviewModelLinkTest extends ModelTestFunctions { + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testSerialization() { + SerializationUtils.serialize(new OverviewModelLink()); + } + + @Test + public void testConstructor() { + OverviewModelLink link = new OverviewModelLink(new OverviewModelLink()); + assertNotNull(link); + } + + @Test + public void testSetters() { + OverviewModelLink link = new OverviewModelLink(); + link.setLinkedModel(null); + assertNull(link.getLinkedModel()); + + link.setxCoord(2.0); + link.setyCoord(3.0); + + assertEquals((Integer) 2, link.getxCoord()); + assertEquals((Integer) 3, link.getyCoord()); + + link.setxCoord((Double) null); + link.setyCoord((Double) null); + assertNull(link.getxCoord()); + assertNull(link.getyCoord()); + } + + @Test + public void testCopy() { + OverviewModelLink degraded = new OverviewModelLink().copy(); + assertNotNull(degraded); + } + + @Test(expected = NotImplementedException.class) + public void testInvalidCopy() { + Mockito.spy(OverviewModelLink.class).copy(); + } } diff --git a/model/src/test/java/lcsb/mapviewer/model/map/OverviewSearchLinkTest.java b/model/src/test/java/lcsb/mapviewer/model/map/OverviewSearchLinkTest.java index 58f77f773d22605551aed84fa054e080225e4347..7cb33dff1a6f5ea087cfb92730ca7b5acc92aa76 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/OverviewSearchLinkTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/OverviewSearchLinkTest.java @@ -1,87 +1,52 @@ package lcsb.mapviewer.model.map; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; +import org.mockito.Mockito; +import lcsb.mapviewer.ModelTestFunctions; import lcsb.mapviewer.common.exception.NotImplementedException; -public class OverviewSearchLinkTest { - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testSerialization() { - try { - SerializationUtils.serialize(new OverviewSearchLink()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testConstructor() { - try { - OverviewSearchLink osl = new OverviewSearchLink(new OverviewSearchLink()); - assertNotNull(osl); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testGetters() { - try { - OverviewSearchLink osl = new OverviewSearchLink(new OverviewSearchLink()); - String query = "st"; - osl.setQuery(query); - assertEquals(query, osl.getQuery()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testCopy() { - try { - OverviewSearchLink degraded = new OverviewSearchLink().copy(); - assertNotNull(degraded); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testInvalidCopy() { - try { - new OverviewSearchLink() { - - /** - * - */ - private static final long serialVersionUID = 1L; - }.copy(); - fail("Exception expected"); - } catch (NotImplementedException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } +public class OverviewSearchLinkTest extends ModelTestFunctions { + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testSerialization() { + SerializationUtils.serialize(new OverviewSearchLink()); + } + + @Test + public void testConstructor() { + OverviewSearchLink osl = new OverviewSearchLink(new OverviewSearchLink()); + assertNotNull(osl); + } + + @Test + public void testGetters() { + OverviewSearchLink osl = new OverviewSearchLink(new OverviewSearchLink()); + String query = "st"; + osl.setQuery(query); + assertEquals(query, osl.getQuery()); + } + + @Test + public void testCopy() { + OverviewSearchLink degraded = new OverviewSearchLink().copy(); + assertNotNull(degraded); + } + + @Test(expected = NotImplementedException.class) + public void testInvalidCopy() { + Mockito.spy(OverviewSearchLink.class).copy(); + } } diff --git a/model/src/test/java/lcsb/mapviewer/model/map/SearchIndexTest.java b/model/src/test/java/lcsb/mapviewer/model/map/SearchIndexTest.java index fbae6bb1b44c7e8edfffa5683d0f9a52e934f269..c7475b44e60349d934bb5cb1c0130bcc668c3da6 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/SearchIndexTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/SearchIndexTest.java @@ -1,128 +1,82 @@ package lcsb.mapviewer.model.map; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; +import org.mockito.Mockito; +import lcsb.mapviewer.ModelTestFunctions; import lcsb.mapviewer.common.exception.NotImplementedException; -import lcsb.mapviewer.model.map.SearchIndex; import lcsb.mapviewer.model.map.species.Element; import lcsb.mapviewer.model.map.species.Gene; -public class SearchIndexTest { - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testSerialization() { - try { - SerializationUtils.serialize(new SearchIndex()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testConstructor1() { - try { - SearchIndex index = new SearchIndex("str", 2); - assertEquals("str", index.getValue()); - assertEquals((Integer) 2, index.getWeight()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testConstructor2() { - try { - SearchIndex index = new SearchIndex("str"); - assertEquals("str", index.getValue()); - assertEquals((Integer) 1, index.getWeight()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testConstructor3() { - try { - SearchIndex index = new SearchIndex("str"); - SearchIndex index2 = new SearchIndex(index); - assertNotNull(index2); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testCopy() { - try { - SearchIndex aRna = new SearchIndex().copy(); - assertNotNull(aRna); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testCopyInvalid() { - try { - new SearchIndex() { - /** - * - */ - private static final long serialVersionUID = 1L; - }.copy(); - fail("Exception expected"); - } catch (NotImplementedException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testGetters() { - try { - int id = 54; - int weight = 8; - String value = "val5"; - Element element = new Gene("gene_id"); - - SearchIndex index = new SearchIndex(); - index.setId(id); - assertEquals(id, index.getId()); - - index.setValue(value); - assertEquals(value, index.getValue()); - - index.setSource(element); - assertEquals(element, index.getSource()); - - index.setWeight(weight); - assertEquals((Integer) weight, index.getWeight()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } +public class SearchIndexTest extends ModelTestFunctions { + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testSerialization() { + SerializationUtils.serialize(new SearchIndex()); + } + + @Test + public void testConstructor1() { + SearchIndex index = new SearchIndex("str", 2); + assertEquals("str", index.getValue()); + assertEquals((Integer) 2, index.getWeight()); + } + + @Test + public void testConstructor2() { + SearchIndex index = new SearchIndex("str"); + assertEquals("str", index.getValue()); + assertEquals((Integer) 1, index.getWeight()); + } + + @Test + public void testConstructor3() { + SearchIndex index = new SearchIndex("str"); + SearchIndex index2 = new SearchIndex(index); + assertNotNull(index2); + } + + @Test + public void testCopy() { + SearchIndex aRna = new SearchIndex().copy(); + assertNotNull(aRna); + } + + @Test(expected = NotImplementedException.class) + public void testCopyInvalid() { + Mockito.spy(SearchIndex.class).copy(); + } + + @Test + public void testGetters() { + int id = 54; + int weight = 8; + String value = "val5"; + Element element = new Gene("gene_id"); + + SearchIndex index = new SearchIndex(); + index.setId(id); + assertEquals(id, index.getId()); + + index.setValue(value); + assertEquals(value, index.getValue()); + + index.setSource(element); + assertEquals(element, index.getSource()); + + index.setWeight(weight); + assertEquals((Integer) weight, index.getWeight()); + } } diff --git a/model/src/test/java/lcsb/mapviewer/model/map/compartment/BottomSquareCompartmentTest.java b/model/src/test/java/lcsb/mapviewer/model/map/compartment/BottomSquareCompartmentTest.java index f993b717f5d4aeda0960030f25fa062bce99b06a..6ecb713c7057a0ca06fc1a812bd912d6930a11ed 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/compartment/BottomSquareCompartmentTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/compartment/BottomSquareCompartmentTest.java @@ -1,95 +1,61 @@ package lcsb.mapviewer.model.map.compartment; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.mockito.Mockito; +import lcsb.mapviewer.ModelTestFunctions; import lcsb.mapviewer.common.exception.NotImplementedException; import lcsb.mapviewer.model.map.model.Model; import lcsb.mapviewer.model.map.model.ModelFullIndexed; -public class BottomSquareCompartmentTest { - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testSerialization() { - try { - SerializationUtils.serialize(new BottomSquareCompartment()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testConstructor1() { - try { - BottomSquareCompartment compartment = new BottomSquareCompartment(new Compartment()); - assertNotNull(compartment); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testConstructor3() { - try { - BottomSquareCompartment compartment = new BottomSquareCompartment("id"); - assertNotNull(compartment); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testConstructor2() { - try { - Model model = new ModelFullIndexed(null); - model.setWidth(1); - model.setHeight(1); - BottomSquareCompartment compartment = new BottomSquareCompartment(new Compartment(), model); - assertNotNull(compartment); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testCopy() { - try { - BottomSquareCompartment compartment = new BottomSquareCompartment().copy(); - assertNotNull(compartment); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testInvalidCopy() { - try { - BottomSquareCompartment compartment = Mockito.spy(BottomSquareCompartment.class); - compartment.copy(); - fail("Exception expected"); - } catch (NotImplementedException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } +public class BottomSquareCompartmentTest extends ModelTestFunctions { + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testSerialization() { + SerializationUtils.serialize(new BottomSquareCompartment()); + } + + @Test + public void testConstructor1() { + BottomSquareCompartment compartment = new BottomSquareCompartment(new Compartment()); + assertNotNull(compartment); + } + + @Test + public void testConstructor3() { + BottomSquareCompartment compartment = new BottomSquareCompartment("id"); + assertNotNull(compartment); + } + + @Test + public void testConstructor2() { + Model model = new ModelFullIndexed(null); + model.setWidth(1); + model.setHeight(1); + BottomSquareCompartment compartment = new BottomSquareCompartment(new Compartment(), model); + assertNotNull(compartment); + } + + @Test + public void testCopy() { + BottomSquareCompartment compartment = new BottomSquareCompartment().copy(); + assertNotNull(compartment); + } + + @Test(expected = NotImplementedException.class) + public void testInvalidCopy() { + BottomSquareCompartment compartment = Mockito.spy(BottomSquareCompartment.class); + compartment.copy(); + } } diff --git a/model/src/test/java/lcsb/mapviewer/model/map/compartment/CompartmentComparatorTest.java b/model/src/test/java/lcsb/mapviewer/model/map/compartment/CompartmentComparatorTest.java index c9b26a97110b78460921bef64658affd8758066c..1659c72abfa695d04165081ecd25aea1d22b3661 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/compartment/CompartmentComparatorTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/compartment/CompartmentComparatorTest.java @@ -1,22 +1,20 @@ package lcsb.mapviewer.model.map.compartment; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import java.awt.Color; import java.awt.geom.Point2D; -import org.apache.logging.log4j.*; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.junit.*; +import lcsb.mapviewer.ModelTestFunctions; import lcsb.mapviewer.common.exception.InvalidArgumentException; import lcsb.mapviewer.model.map.species.GenericProtein; import lcsb.mapviewer.model.map.species.Species; -public class CompartmentComparatorTest { +public class CompartmentComparatorTest extends ModelTestFunctions { Logger logger = LogManager.getLogger(CompartmentComparatorTest.class); @@ -32,79 +30,51 @@ public class CompartmentComparatorTest { @Test public void testEquals() { - try { - Compartment compartment1 = createCompartment(); - Compartment compartment2 = createCompartment(); - - assertEquals(0, comparator.compare(compartment1, compartment2)); + Compartment compartment1 = createCompartment(); + Compartment compartment2 = createCompartment(); - assertEquals(0, comparator.compare(null, null)); + assertEquals(0, comparator.compare(compartment1, compartment2)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, comparator.compare(null, null)); } @Test public void testDifferent2() { - try { - Compartment compartment = createCompartment(); - - assertTrue(comparator.compare(compartment, new PathwayCompartment()) != 0); + Compartment compartment = createCompartment(); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertTrue(comparator.compare(compartment, new PathwayCompartment()) != 0); } - @Test + @Test(expected = InvalidArgumentException.class) public void testInvalid() { - try { - Compartment compartment1 = createCompartment(); - Compartment compartment2 = createCompartment(); - - GenericProtein protein = new GenericProtein("1"); - compartment1.getElements().add(protein); - protein = new GenericProtein("1"); - compartment1.getElements().add(protein); - - compartment2.getElements().add(new GenericProtein("b")); - compartment2.getElements().add(new GenericProtein("a")); - - comparator.compare(compartment1, compartment2); - fail("Exception expected"); - - } catch (InvalidArgumentException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Compartment compartment1 = createCompartment(); + Compartment compartment2 = createCompartment(); + + GenericProtein protein = new GenericProtein("1"); + compartment1.getElements().add(protein); + protein = new GenericProtein("1"); + compartment1.getElements().add(protein); + + compartment2.getElements().add(new GenericProtein("b")); + compartment2.getElements().add(new GenericProtein("a")); + + comparator.compare(compartment1, compartment2); } - @Test + @Test(expected = InvalidArgumentException.class) public void testInvalid2() { - try { - Compartment compartment1 = createCompartment(); - Compartment compartment2 = createCompartment(); - - Species protein = new GenericProtein("1"); - compartment1.getElements().add(protein); - protein = new GenericProtein("1"); - compartment1.getElements().add(protein); - - compartment2.getElements().add(new GenericProtein("A")); - compartment2.getElements().add(new GenericProtein("B")); - - comparator.compare(compartment2, compartment1); - fail("Exception expected"); - - } catch (InvalidArgumentException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Compartment compartment1 = createCompartment(); + Compartment compartment2 = createCompartment(); + + Species protein = new GenericProtein("1"); + compartment1.getElements().add(protein); + protein = new GenericProtein("1"); + compartment1.getElements().add(protein); + + compartment2.getElements().add(new GenericProtein("A")); + compartment2.getElements().add(new GenericProtein("B")); + + comparator.compare(compartment2, compartment1); } private Compartment createCompartment() { @@ -154,69 +124,63 @@ public class CompartmentComparatorTest { @Test public void testDifferent() { - try { - Compartment compartment1 = createCompartment(); - Compartment compartment2 = createCompartment(); - - assertTrue(comparator.compare(compartment1, null) != 0); - assertTrue(comparator.compare(null, compartment1) != 0); + Compartment compartment1 = createCompartment(); + Compartment compartment2 = createCompartment(); - compartment1 = createCompartment(); - compartment2 = createCompartment(); + assertTrue(comparator.compare(compartment1, null) != 0); + assertTrue(comparator.compare(null, compartment1) != 0); - compartment1.setThickness(11111); + compartment1 = createCompartment(); + compartment2 = createCompartment(); - assertTrue(comparator.compare(compartment1, compartment2) != 0); - assertTrue(comparator.compare(compartment2, compartment1) != 0); + compartment1.setThickness(11111); - compartment1 = createCompartment(); - compartment2 = createCompartment(); + assertTrue(comparator.compare(compartment1, compartment2) != 0); + assertTrue(comparator.compare(compartment2, compartment1) != 0); - compartment1.setNamePoint(new Point2D.Double(9, 999)); + compartment1 = createCompartment(); + compartment2 = createCompartment(); - assertTrue(comparator.compare(compartment1, compartment2) != 0); - assertTrue(comparator.compare(compartment2, compartment1) != 0); + compartment1.setNamePoint(new Point2D.Double(9, 999)); - compartment1 = createCompartment(); - compartment2 = createCompartment(); + assertTrue(comparator.compare(compartment1, compartment2) != 0); + assertTrue(comparator.compare(compartment2, compartment1) != 0); - compartment1.getElements().iterator().next().setElementId("bnu"); + compartment1 = createCompartment(); + compartment2 = createCompartment(); - assertTrue(comparator.compare(compartment1, compartment2) != 0); - assertTrue(comparator.compare(compartment2, compartment1) != 0); + compartment1.getElements().iterator().next().setElementId("bnu"); - compartment1 = createCompartment(); - compartment2 = createCompartment(); + assertTrue(comparator.compare(compartment1, compartment2) != 0); + assertTrue(comparator.compare(compartment2, compartment1) != 0); - Species species = (Species) compartment1.getElements().iterator().next(); - species.setName("new namne"); + compartment1 = createCompartment(); + compartment2 = createCompartment(); - assertTrue(comparator.compare(compartment1, compartment2) != 0); - assertTrue(comparator.compare(compartment2, compartment1) != 0); + Species species = (Species) compartment1.getElements().iterator().next(); + species.setName("new namne"); - compartment1 = createCompartment(); - compartment2 = createCompartment(); + assertTrue(comparator.compare(compartment1, compartment2) != 0); + assertTrue(comparator.compare(compartment2, compartment1) != 0); - compartment1.setOuterWidth(2); + compartment1 = createCompartment(); + compartment2 = createCompartment(); - assertTrue(comparator.compare(compartment1, compartment2) != 0); - assertTrue(comparator.compare(compartment2, compartment1) != 0); + compartment1.setOuterWidth(2); - compartment1 = createCompartment(); - compartment2 = createCompartment(); + assertTrue(comparator.compare(compartment1, compartment2) != 0); + assertTrue(comparator.compare(compartment2, compartment1) != 0); - compartment1.setInnerWidth(2); + compartment1 = createCompartment(); + compartment2 = createCompartment(); - assertTrue(comparator.compare(compartment1, compartment2) != 0); - assertTrue(comparator.compare(compartment2, compartment1) != 0); + compartment1.setInnerWidth(2); - compartment1 = createCompartment(); - compartment2 = createCompartment(); + assertTrue(comparator.compare(compartment1, compartment2) != 0); + assertTrue(comparator.compare(compartment2, compartment1) != 0); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + compartment1 = createCompartment(); + compartment2 = createCompartment(); } } diff --git a/model/src/test/java/lcsb/mapviewer/model/map/compartment/CompartmentTest.java b/model/src/test/java/lcsb/mapviewer/model/map/compartment/CompartmentTest.java index d5482ab3baab98bd67bf99bf3f4e870136233e6a..59c5cf8432975bd35d3f3af1356aa3ea81715db6 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/compartment/CompartmentTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/compartment/CompartmentTest.java @@ -1,414 +1,313 @@ package lcsb.mapviewer.model.map.compartment; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import java.util.HashSet; import java.util.Set; import org.apache.commons.lang3.SerializationUtils; -import org.apache.logging.log4j.*; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.junit.*; import org.mockito.Mockito; +import lcsb.mapviewer.ModelTestFunctions; import lcsb.mapviewer.common.Configuration; -import lcsb.mapviewer.common.exception.InvalidArgumentException; -import lcsb.mapviewer.common.exception.InvalidStateException; -import lcsb.mapviewer.common.exception.NotImplementedException; +import lcsb.mapviewer.common.exception.*; import lcsb.mapviewer.model.map.model.Model; import lcsb.mapviewer.model.map.model.ModelFullIndexed; -import lcsb.mapviewer.model.map.species.Complex; -import lcsb.mapviewer.model.map.species.Element; -import lcsb.mapviewer.model.map.species.GenericProtein; -import lcsb.mapviewer.model.map.species.SimpleMolecule; -import lcsb.mapviewer.model.map.species.Species; - -public class CompartmentTest { - Logger logger = LogManager.getLogger(CompartmentTest.class); - - int identifierCounter = 1; - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testCross() throws Exception { - try { - Model model = createCrossModel(); - Element ldhb1 = model.getElementByElementId("sa1115"); - Element ldhb2 = model.getElementByElementId("sa1117"); - Element ldhb3 = model.getElementByElementId("sa1119"); - Element ldhb4 = model.getElementByElementId("sa1121"); - - Compartment cytosol = (Compartment) model.getElementByElementId("ca1"); - - assertTrue(cytosol.cross(ldhb1)); - assertTrue(cytosol.cross(ldhb2)); - assertTrue(cytosol.cross(ldhb3)); - assertTrue(cytosol.cross(ldhb4)); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testCrossException() throws Exception { - try { - Compartment compartment = new Compartment(); - Complex complex = new Complex("idd"); - complex.setComplex(complex); - compartment.cross(complex); - - fail("Exception epxected"); - } catch (InvalidStateException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testCross2() throws Exception { - try { - Compartment compartment = new Compartment(); - compartment.setX(10.0); - compartment.setY(10.0); - compartment.setWidth(10.0); - compartment.setHeight(10.0); - Complex complex = new Complex("idd"); - complex.setWidth(10.0); - complex.setHeight(10.0); - complex.setX(5.0); - complex.setY(5.0); - assertTrue(compartment.cross(complex)); - - complex.setX(15.0); - complex.setY(5.0); - assertTrue(compartment.cross(complex)); - - complex.setX(5.0); - complex.setY(15.0); - assertTrue(compartment.cross(complex)); - - complex.setX(15.0); - complex.setY(15.0); - assertTrue(compartment.cross(complex)); - - complex.setWidth(100.0); - complex.setHeight(100.0); - complex.setX(-110.0); - complex.setY(-10.0); - assertFalse(compartment.cross(complex)); - - complex.setX(-10.0); - complex.setY(-110.0); - assertFalse(compartment.cross(complex)); - - complex.setX(40.0); - complex.setY(-10.0); - assertFalse(compartment.cross(complex)); - - complex.setX(-10.0); - complex.setY(40.0); - assertFalse(compartment.cross(complex)); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testContainsIdenticalSpecies() throws Exception { - try { - Compartment compartment = new Compartment(); - - compartment.setName("AS"); - - assertFalse(compartment.containsIdenticalSpecies()); - - Species species = new GenericProtein("idd"); - species.setName("AS"); - - compartment.addElement(species); - - assertTrue(compartment.containsIdenticalSpecies()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testDoesntContainsIdenticalSpecies() throws Exception { - try { - Compartment compartment = new Compartment(); - - compartment.setName("AS"); - - Species species = new GenericProtein("idd"); - species.setName("not identical name"); - - compartment.addElement(species); - - assertFalse(compartment.containsIdenticalSpecies()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - private Model createCrossModel() { - Model model = new ModelFullIndexed(null); - model.addElement(new Compartment("default")); - - model.addElement(createSpecies(3264.8333333333335, 7517.75, 86.0, 46.0, "sa1115")); - model.addElement(createSpecies(3267.6666666666665, 7438.75, 80.0, 40.0, "sa1117")); - model.addElement(createSpecies(3261.6666666666665, 7600.75, 92.0, 52.0, "sa1119")); - model.addElement(createSpecies(3203.666666666667, 7687.75, 98.0, 58.0, "sa1121")); - - Species species = createSpecies(7817.714285714286, 11287.642857142859, 80.0, 40.0, "sa1422"); - Species species2 = createSpecies(8224.964285714286, 11241.392857142859, 80.0, 40.0, "sa1419"); - Complex complex = createComplex(7804.714285714286, 11182.642857142859, 112.0, 172.0, "csa152"); - complex.addSpecies(species); - complex.addSpecies(species2); - species.setComplex(complex); - species2.setComplex(complex); - - model.addElement(species); - model.addElement(species2); - model.addElement(complex); - - model.addElement(createCompartment(1380.0, 416.0, 15893.0, 10866.0, "ca1")); - return model; - } - - private Compartment createCompartment(double x, double y, double width, double height, String elementId) { - Compartment compartment = new Compartment(elementId); - compartment.setElementId(elementId); - compartment.setX(x); - compartment.setY(y); - compartment.setWidth(width); - compartment.setHeight(height); - return compartment; - } - - private Species createSpecies(double x, double y, double width, double height, String elementId) { - SimpleMolecule simpleMolecule = new SimpleMolecule(elementId); - simpleMolecule.setX(x); - simpleMolecule.setY(y); - simpleMolecule.setWidth(width); - simpleMolecule.setHeight(height); - return simpleMolecule; - } - - private Complex createComplex(double x, double y, double width, double height, String elementId) { - Complex complex = new Complex(elementId); - complex.setX(x); - complex.setY(y); - complex.setWidth(width); - complex.setHeight(height); - return complex; - } - - @Test - public void testCrossWithComplexElements() throws Exception { - try { - Model model = createCrossModel(); - Element ldhb1 = model.getElementByElementId("sa1422"); - Element ldhb2 = model.getElementByElementId("sa1419"); - - Compartment cytosol = (Compartment) model.getElementByElementId("ca1"); - - assertTrue(cytosol.cross(ldhb1)); - assertTrue(cytosol.cross(ldhb2)); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testSerialization() { - try { - SerializationUtils.serialize(new Compartment()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testConstructor() { - try { - Compartment compartment = new Compartment(); - compartment.addElement(new GenericProtein("idd")); - Compartment copy = new Compartment(compartment); - assertNotNull(copy); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testGetters() { - try { - Compartment compartment = new Compartment(); - String invalidVal = "a1.6"; - String val = "1.6"; - Double dVal = 1.6; - - compartment.setLineThickness(val); - compartment.setLineOuterWidth(val); - compartment.setLineInnerWidth(val); - - assertEquals(dVal, compartment.getThickness(), Configuration.EPSILON); - assertEquals(dVal, compartment.getOuterWidth(), Configuration.EPSILON); - assertEquals(dVal, compartment.getInnerWidth(), Configuration.EPSILON); - - try { - compartment.setLineThickness(invalidVal); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - } - try { - compartment.setLineOuterWidth(invalidVal); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - } - try { - compartment.setLineInnerWidth(invalidVal); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - } - - compartment.setNamePoint(2, 3); - assertEquals(0, compartment.getNamePoint().distance(2, 3), Configuration.EPSILON); - - Set<Element> elements = new HashSet<>(); - - compartment.setElements(elements); - assertEquals(elements, compartment.getElements()); - - assertNotNull(compartment.getStringType()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testAddElement() { - try { - Compartment compartment = new Compartment(); - - Species child = new GenericProtein("id"); - - compartment.addElement(child); - compartment.addElement(child); - - assertEquals(1, compartment.getElements().size()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testAddInvalidElement() { - try { - Compartment compartment = new Compartment(); - - Species child = new GenericProtein("id"); - Species child2 = new GenericProtein("id"); - - compartment.addElement(child); - compartment.addElement(child2); - - fail("Exception expected"); - - } catch (InvalidArgumentException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testGetAllElements() { - try { - Compartment compartment = new Compartment(); - - Species child = new GenericProtein("id"); - Compartment child2 = new Compartment(); - child2.addElement(child); - compartment.addElement(child2); - - assertEquals(2, compartment.getAllSubElements().size()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testCopy() { - try { - Compartment degraded = new Compartment().copy(); - assertNotNull(degraded); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testRemoveElement() { - try { - Compartment comp = new Compartment(); - Species protein = new GenericProtein("idd"); - comp.addElement(protein); - protein.setCompartment(new Compartment()); - - comp.removeElement(protein); - - assertEquals(0, comp.getElements().size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testInvalidCopy() { - try { - Compartment compartment = Mockito.spy(Compartment.class); - compartment.copy(); - fail("Exception expected"); - } catch (NotImplementedException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } +import lcsb.mapviewer.model.map.species.*; + +public class CompartmentTest extends ModelTestFunctions { + Logger logger = LogManager.getLogger(CompartmentTest.class); + + int identifierCounter = 1; + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testCross() throws Exception { + Model model = createCrossModel(); + Element ldhb1 = model.getElementByElementId("sa1115"); + Element ldhb2 = model.getElementByElementId("sa1117"); + Element ldhb3 = model.getElementByElementId("sa1119"); + Element ldhb4 = model.getElementByElementId("sa1121"); + + Compartment cytosol = (Compartment) model.getElementByElementId("ca1"); + + assertTrue(cytosol.cross(ldhb1)); + assertTrue(cytosol.cross(ldhb2)); + assertTrue(cytosol.cross(ldhb3)); + assertTrue(cytosol.cross(ldhb4)); + } + + @Test(expected = InvalidStateException.class) + public void testCrossException() throws Exception { + Compartment compartment = new Compartment(); + Complex complex = new Complex("idd"); + complex.setComplex(complex); + compartment.cross(complex); + } + + @Test + public void testCross2() throws Exception { + Compartment compartment = new Compartment(); + compartment.setX(10.0); + compartment.setY(10.0); + compartment.setWidth(10.0); + compartment.setHeight(10.0); + Complex complex = new Complex("idd"); + complex.setWidth(10.0); + complex.setHeight(10.0); + complex.setX(5.0); + complex.setY(5.0); + assertTrue(compartment.cross(complex)); + + complex.setX(15.0); + complex.setY(5.0); + assertTrue(compartment.cross(complex)); + + complex.setX(5.0); + complex.setY(15.0); + assertTrue(compartment.cross(complex)); + + complex.setX(15.0); + complex.setY(15.0); + assertTrue(compartment.cross(complex)); + + complex.setWidth(100.0); + complex.setHeight(100.0); + complex.setX(-110.0); + complex.setY(-10.0); + assertFalse(compartment.cross(complex)); + + complex.setX(-10.0); + complex.setY(-110.0); + assertFalse(compartment.cross(complex)); + + complex.setX(40.0); + complex.setY(-10.0); + assertFalse(compartment.cross(complex)); + + complex.setX(-10.0); + complex.setY(40.0); + assertFalse(compartment.cross(complex)); + } + + @Test + public void testContainsIdenticalSpecies() throws Exception { + Compartment compartment = new Compartment(); + + compartment.setName("AS"); + + assertFalse(compartment.containsIdenticalSpecies()); + + Species species = new GenericProtein("idd"); + species.setName("AS"); + + compartment.addElement(species); + + assertTrue(compartment.containsIdenticalSpecies()); + } + + @Test + public void testDoesntContainsIdenticalSpecies() throws Exception { + Compartment compartment = new Compartment(); + + compartment.setName("AS"); + + Species species = new GenericProtein("idd"); + species.setName("not identical name"); + + compartment.addElement(species); + + assertFalse(compartment.containsIdenticalSpecies()); + } + + private Model createCrossModel() { + Model model = new ModelFullIndexed(null); + model.addElement(new Compartment("default")); + + model.addElement(createSpecies(3264.8333333333335, 7517.75, 86.0, 46.0, "sa1115")); + model.addElement(createSpecies(3267.6666666666665, 7438.75, 80.0, 40.0, "sa1117")); + model.addElement(createSpecies(3261.6666666666665, 7600.75, 92.0, 52.0, "sa1119")); + model.addElement(createSpecies(3203.666666666667, 7687.75, 98.0, 58.0, "sa1121")); + + Species species = createSpecies(7817.714285714286, 11287.642857142859, 80.0, 40.0, "sa1422"); + Species species2 = createSpecies(8224.964285714286, 11241.392857142859, 80.0, 40.0, "sa1419"); + Complex complex = createComplex(7804.714285714286, 11182.642857142859, 112.0, 172.0, "csa152"); + complex.addSpecies(species); + complex.addSpecies(species2); + species.setComplex(complex); + species2.setComplex(complex); + + model.addElement(species); + model.addElement(species2); + model.addElement(complex); + + model.addElement(createCompartment(1380.0, 416.0, 15893.0, 10866.0, "ca1")); + return model; + } + + private Compartment createCompartment(double x, double y, double width, double height, String elementId) { + Compartment compartment = new Compartment(elementId); + compartment.setElementId(elementId); + compartment.setX(x); + compartment.setY(y); + compartment.setWidth(width); + compartment.setHeight(height); + return compartment; + } + + private Species createSpecies(double x, double y, double width, double height, String elementId) { + SimpleMolecule simpleMolecule = new SimpleMolecule(elementId); + simpleMolecule.setX(x); + simpleMolecule.setY(y); + simpleMolecule.setWidth(width); + simpleMolecule.setHeight(height); + return simpleMolecule; + } + + private Complex createComplex(double x, double y, double width, double height, String elementId) { + Complex complex = new Complex(elementId); + complex.setX(x); + complex.setY(y); + complex.setWidth(width); + complex.setHeight(height); + return complex; + } + + @Test + public void testCrossWithComplexElements() throws Exception { + Model model = createCrossModel(); + Element ldhb1 = model.getElementByElementId("sa1422"); + Element ldhb2 = model.getElementByElementId("sa1419"); + + Compartment cytosol = (Compartment) model.getElementByElementId("ca1"); + + assertTrue(cytosol.cross(ldhb1)); + assertTrue(cytosol.cross(ldhb2)); + } + + @Test + public void testSerialization() { + SerializationUtils.serialize(new Compartment()); + } + + @Test + public void testConstructor() { + Compartment compartment = new Compartment(); + compartment.addElement(new GenericProtein("idd")); + Compartment copy = new Compartment(compartment); + assertNotNull(copy); + } + + @Test(expected = InvalidArgumentException.class) + public void testSetInvalidThickness() { + Compartment compartment = new Compartment(); + compartment.setLineThickness("a1.6"); + } + + @Test(expected = InvalidArgumentException.class) + public void testSetInvalidLineInnerWidth() { + Compartment compartment = new Compartment(); + compartment.setLineInnerWidth("a1.6"); + } + + @Test(expected = InvalidArgumentException.class) + public void testSetInvalidLineOuterWdth() { + Compartment compartment = new Compartment(); + compartment.setLineOuterWidth("a1.6"); + } + + @Test + public void testGetters() { + Compartment compartment = new Compartment(); + String val = "1.6"; + Double dVal = 1.6; + + compartment.setLineThickness(val); + compartment.setLineOuterWidth(val); + compartment.setLineInnerWidth(val); + + assertEquals(dVal, compartment.getThickness(), Configuration.EPSILON); + assertEquals(dVal, compartment.getOuterWidth(), Configuration.EPSILON); + assertEquals(dVal, compartment.getInnerWidth(), Configuration.EPSILON); + + compartment.setNamePoint(2, 3); + assertEquals(0, compartment.getNamePoint().distance(2, 3), Configuration.EPSILON); + + Set<Element> elements = new HashSet<>(); + + compartment.setElements(elements); + assertEquals(elements, compartment.getElements()); + + assertNotNull(compartment.getStringType()); + } + + @Test + public void testAddElement() { + Compartment compartment = new Compartment(); + + Species child = new GenericProtein("id"); + + compartment.addElement(child); + compartment.addElement(child); + + assertEquals(1, compartment.getElements().size()); + } + + @Test(expected = InvalidArgumentException.class) + public void testAddInvalidElement() { + Compartment compartment = new Compartment(); + + Species child = new GenericProtein("id"); + Species child2 = new GenericProtein("id"); + + compartment.addElement(child); + compartment.addElement(child2); + } + + @Test + public void testGetAllElements() { + Compartment compartment = new Compartment(); + + Species child = new GenericProtein("id"); + Compartment child2 = new Compartment(); + child2.addElement(child); + compartment.addElement(child2); + + assertEquals(2, compartment.getAllSubElements().size()); + } + + @Test + public void testCopy() { + Compartment degraded = new Compartment().copy(); + assertNotNull(degraded); + } + + @Test + public void testRemoveElement() { + Compartment comp = new Compartment(); + Species protein = new GenericProtein("idd"); + comp.addElement(protein); + protein.setCompartment(new Compartment()); + + comp.removeElement(protein); + + assertEquals(0, comp.getElements().size()); + } + + @Test(expected = NotImplementedException.class) + public void testInvalidCopy() { + Compartment compartment = Mockito.spy(Compartment.class); + compartment.copy(); + } } diff --git a/model/src/test/java/lcsb/mapviewer/model/map/compartment/LeftSquareCompartmentTest.java b/model/src/test/java/lcsb/mapviewer/model/map/compartment/LeftSquareCompartmentTest.java index 0237ebeabadd8f9021cb102b4511a9a834b856e8..1b079db050b8160e1fdadd834e1940ef0499d31f 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/compartment/LeftSquareCompartmentTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/compartment/LeftSquareCompartmentTest.java @@ -1,96 +1,62 @@ package lcsb.mapviewer.model.map.compartment; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.mockito.Mockito; +import lcsb.mapviewer.ModelTestFunctions; import lcsb.mapviewer.common.exception.NotImplementedException; import lcsb.mapviewer.model.map.model.Model; import lcsb.mapviewer.model.map.model.ModelFullIndexed; -public class LeftSquareCompartmentTest { - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testSerialization() { - try { - SerializationUtils.serialize(new LeftSquareCompartment()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testConstructor1() { - try { - LeftSquareCompartment compartment = new LeftSquareCompartment(new LeftSquareCompartment()); - assertNotNull(compartment); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testConstructor3() { - try { - LeftSquareCompartment compartment = new LeftSquareCompartment("id"); - assertNotNull(compartment); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testConstructor2() { - try { - Model model = new ModelFullIndexed(null); - model.setWidth(1); - model.setHeight(1); - LeftSquareCompartment compartment = new LeftSquareCompartment(new Compartment(), model); - assertNotNull(compartment); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testCopy() { - try { - LeftSquareCompartment compartment = new LeftSquareCompartment().copy(); - assertNotNull(compartment); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testInvalidCopy() { - try { - LeftSquareCompartment compartment = Mockito.spy(LeftSquareCompartment.class); - compartment.copy(); - fail("Exception expected"); - } catch (NotImplementedException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } +public class LeftSquareCompartmentTest extends ModelTestFunctions { + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testSerialization() { + SerializationUtils.serialize(new LeftSquareCompartment()); + } + + @Test + public void testConstructor1() { + LeftSquareCompartment compartment = new LeftSquareCompartment(new LeftSquareCompartment()); + assertNotNull(compartment); + } + + @Test + public void testConstructor3() { + LeftSquareCompartment compartment = new LeftSquareCompartment("id"); + assertNotNull(compartment); + } + + @Test + public void testConstructor2() { + Model model = new ModelFullIndexed(null); + model.setWidth(1); + model.setHeight(1); + LeftSquareCompartment compartment = new LeftSquareCompartment(new Compartment(), model); + assertNotNull(compartment); + } + + @Test + public void testCopy() { + LeftSquareCompartment compartment = new LeftSquareCompartment().copy(); + assertNotNull(compartment); + } + + @Test(expected = NotImplementedException.class) + public void testInvalidCopy() { + LeftSquareCompartment compartment = Mockito.spy(LeftSquareCompartment.class); + compartment.copy(); + } } diff --git a/model/src/test/java/lcsb/mapviewer/model/map/compartment/OvalCompartmentTest.java b/model/src/test/java/lcsb/mapviewer/model/map/compartment/OvalCompartmentTest.java index d403f5f5754015692e0cdf32bcac32e96f2ee492..afe846f021149b131c21c6e3e1173069b475a824 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/compartment/OvalCompartmentTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/compartment/OvalCompartmentTest.java @@ -1,71 +1,47 @@ package lcsb.mapviewer.model.map.compartment; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.mockito.Mockito; +import lcsb.mapviewer.ModelTestFunctions; import lcsb.mapviewer.common.exception.NotImplementedException; -public class OvalCompartmentTest { - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testSerialization() { - try { - SerializationUtils.serialize(new OvalCompartment()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testConstructor() { - try { - OvalCompartment original = new OvalCompartment(); - OvalCompartment copy = new OvalCompartment(original); - assertNotNull(copy); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testCopy() { - try { - OvalCompartment original = new OvalCompartment(); - OvalCompartment copy = original.copy(); - assertNotNull(copy); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testInvalidCopy() { - try { - OvalCompartment compartment = Mockito.spy(OvalCompartment.class); - compartment.copy(); - fail("Exception expected"); - } catch (NotImplementedException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } +public class OvalCompartmentTest extends ModelTestFunctions { + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testSerialization() { + SerializationUtils.serialize(new OvalCompartment()); + } + + @Test + public void testConstructor() { + OvalCompartment original = new OvalCompartment(); + OvalCompartment copy = new OvalCompartment(original); + assertNotNull(copy); + } + + @Test + public void testCopy() { + OvalCompartment original = new OvalCompartment(); + OvalCompartment copy = original.copy(); + assertNotNull(copy); + } + + @Test(expected = NotImplementedException.class) + public void testInvalidCopy() { + OvalCompartment compartment = Mockito.spy(OvalCompartment.class); + compartment.copy(); + } } diff --git a/model/src/test/java/lcsb/mapviewer/model/map/compartment/PathwayCompartmentTest.java b/model/src/test/java/lcsb/mapviewer/model/map/compartment/PathwayCompartmentTest.java index 32f1d578f4204bfed280d6a456c4467092a612de..a71eeb7e1b57e3aefa4418ad59984a0189d8284f 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/compartment/PathwayCompartmentTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/compartment/PathwayCompartmentTest.java @@ -1,90 +1,56 @@ package lcsb.mapviewer.model.map.compartment; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.mockito.Mockito; +import lcsb.mapviewer.ModelTestFunctions; import lcsb.mapviewer.common.exception.NotImplementedException; -import lcsb.mapviewer.model.map.compartment.Compartment; -import lcsb.mapviewer.model.map.compartment.CompartmentComparator; -import lcsb.mapviewer.model.map.compartment.PathwayCompartment; -public class PathwayCompartmentTest { - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void test() throws Exception { - try { - CompartmentComparator comparator = new CompartmentComparator(); - Compartment pathway = new PathwayCompartment("id"); - Compartment copy = pathway.copy(); - - assertEquals(0, comparator.compare(pathway, copy)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - - } - - @Test - public void testSerialization() { - try { - SerializationUtils.serialize(new PathwayCompartment("id")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testGetters() { - try { - PathwayCompartment pathway = new PathwayCompartment("id"); - String title = "tit27"; - pathway.setName(title); - assertEquals(title, pathway.getName()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testInvalidCopy() { - try { - PathwayCompartment comp = Mockito.spy(PathwayCompartment.class); - comp.copy(); - fail("Exception expected"); - } catch (NotImplementedException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testCopy() { - try { - PathwayCompartment degraded = new PathwayCompartment("id").copy(); - assertNotNull(degraded); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } +public class PathwayCompartmentTest extends ModelTestFunctions { + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void test() throws Exception { + CompartmentComparator comparator = new CompartmentComparator(); + Compartment pathway = new PathwayCompartment("id"); + Compartment copy = pathway.copy(); + + assertEquals(0, comparator.compare(pathway, copy)); + } + + @Test + public void testSerialization() { + SerializationUtils.serialize(new PathwayCompartment("id")); + } + + @Test + public void testGetters() { + PathwayCompartment pathway = new PathwayCompartment("id"); + String title = "tit27"; + pathway.setName(title); + assertEquals(title, pathway.getName()); + } + + @Test(expected = NotImplementedException.class) + public void testInvalidCopy() { + PathwayCompartment comp = Mockito.spy(PathwayCompartment.class); + comp.copy(); + } + + @Test + public void testCopy() { + PathwayCompartment degraded = new PathwayCompartment("id").copy(); + assertNotNull(degraded); + } } diff --git a/model/src/test/java/lcsb/mapviewer/model/map/compartment/RightSquareCompartmentTest.java b/model/src/test/java/lcsb/mapviewer/model/map/compartment/RightSquareCompartmentTest.java index 26fe88ef304d4d3769fe45e27e465e0399817118..bf76defcf6887d59362f53225d020cae56225e01 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/compartment/RightSquareCompartmentTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/compartment/RightSquareCompartmentTest.java @@ -1,109 +1,69 @@ package lcsb.mapviewer.model.map.compartment; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.mockito.Mockito; +import lcsb.mapviewer.ModelTestFunctions; import lcsb.mapviewer.common.exception.NotImplementedException; import lcsb.mapviewer.model.map.model.Model; import lcsb.mapviewer.model.map.model.ModelFullIndexed; -public class RightSquareCompartmentTest { +public class RightSquareCompartmentTest extends ModelTestFunctions { - @Before - public void setUp() throws Exception { - } + @Before + public void setUp() throws Exception { + } - @After - public void tearDown() throws Exception { - } + @After + public void tearDown() throws Exception { + } - @Test - public void testSerialization() { - try { - SerializationUtils.serialize(new RightSquareCompartment()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } + @Test + public void testSerialization() { + SerializationUtils.serialize(new RightSquareCompartment()); + } - @Test - public void testConstructor1() { - try { - RightSquareCompartment compartment = new RightSquareCompartment(new RightSquareCompartment()); - assertNotNull(compartment); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } + @Test + public void testConstructor1() { + RightSquareCompartment compartment = new RightSquareCompartment(new RightSquareCompartment()); + assertNotNull(compartment); + } - @Test - public void testConstructor3() { - try { - RightSquareCompartment compartment = new RightSquareCompartment("id"); - assertNotNull(compartment); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } + @Test + public void testConstructor3() { + RightSquareCompartment compartment = new RightSquareCompartment("id"); + assertNotNull(compartment); + } - @Test - public void testConstructor2() { - try { - Model model = new ModelFullIndexed(null); - model.setWidth(1); - model.setHeight(1); - RightSquareCompartment compartment = new RightSquareCompartment(new Compartment(), model); - assertNotNull(compartment); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } + @Test + public void testConstructor2() { + Model model = new ModelFullIndexed(null); + model.setWidth(1); + model.setHeight(1); + RightSquareCompartment compartment = new RightSquareCompartment(new Compartment(), model); + assertNotNull(compartment); + } - @Test - public void testCopy() { - try { - RightSquareCompartment compartment = new RightSquareCompartment().copy(); - assertNotNull(compartment); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } + @Test + public void testCopy() { + RightSquareCompartment compartment = new RightSquareCompartment().copy(); + assertNotNull(compartment); + } - @Test - public void testSetPoint() { - try { - RightSquareCompartment compartment = new RightSquareCompartment(); - compartment.setPoint("10", "10"); - assertTrue(compartment.getWidth() < 0); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } + @Test + public void testSetPoint() { + RightSquareCompartment compartment = new RightSquareCompartment(); + compartment.setPoint("10", "10"); + assertTrue(compartment.getWidth() < 0); + } - @Test - public void testInvalidCopy() { - try { - RightSquareCompartment compartment = Mockito.spy(RightSquareCompartment.class); - compartment.copy(); - fail("Exception expected"); - } catch (NotImplementedException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } + @Test(expected = NotImplementedException.class) + public void testInvalidCopy() { + RightSquareCompartment compartment = Mockito.spy(RightSquareCompartment.class); + compartment.copy(); + } } diff --git a/model/src/test/java/lcsb/mapviewer/model/map/compartment/SquareCompartmentTest.java b/model/src/test/java/lcsb/mapviewer/model/map/compartment/SquareCompartmentTest.java index 04be65cfe52f909e0a27305a186c9532b64a4a6e..f01d92e601e93a21883da9376b9c6b722ef9c61b 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/compartment/SquareCompartmentTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/compartment/SquareCompartmentTest.java @@ -1,18 +1,15 @@ package lcsb.mapviewer.model.map.compartment; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.mockito.Mockito; +import lcsb.mapviewer.ModelTestFunctions; import lcsb.mapviewer.common.exception.NotImplementedException; -public class SquareCompartmentTest { +public class SquareCompartmentTest extends ModelTestFunctions { @Before public void setUp() throws Exception { @@ -24,51 +21,29 @@ public class SquareCompartmentTest { @Test public void testSerialization() { - try { - SerializationUtils.serialize(new SquareCompartment()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + SerializationUtils.serialize(new SquareCompartment()); } @Test public void testConstructor() { - try { - SquareCompartment original = new SquareCompartment("id"); - original.setName("test name"); - SquareCompartment copy = new SquareCompartment(original); - assertNotNull(copy); - assertEquals("test name", copy.getName()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + SquareCompartment original = new SquareCompartment("id"); + original.setName("test name"); + SquareCompartment copy = new SquareCompartment(original); + assertNotNull(copy); + assertEquals("test name", copy.getName()); } @Test public void testCopy() { - try { - SquareCompartment original = new SquareCompartment(); - SquareCompartment copy = original.copy(); - assertNotNull(copy); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + SquareCompartment original = new SquareCompartment(); + SquareCompartment copy = original.copy(); + assertNotNull(copy); } - @Test + @Test(expected = NotImplementedException.class) public void testInvalidCopy() { - try { - SquareCompartment compartment = Mockito.spy(SquareCompartment.class); - compartment.copy(); - fail("Exception expected"); - } catch (NotImplementedException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + SquareCompartment compartment = Mockito.spy(SquareCompartment.class); + compartment.copy(); } } diff --git a/model/src/test/java/lcsb/mapviewer/model/map/compartment/TopSquareCompartmentTest.java b/model/src/test/java/lcsb/mapviewer/model/map/compartment/TopSquareCompartmentTest.java index 6b56de409e83f92c23e9723f40a3430a83b91851..58d1b1201d7381560de0ef55c33b253eec6493b1 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/compartment/TopSquareCompartmentTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/compartment/TopSquareCompartmentTest.java @@ -1,100 +1,62 @@ package lcsb.mapviewer.model.map.compartment; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.mockito.Mockito; +import lcsb.mapviewer.ModelTestFunctions; import lcsb.mapviewer.common.exception.NotImplementedException; -import lcsb.mapviewer.model.map.compartment.Compartment; -import lcsb.mapviewer.model.map.compartment.TopSquareCompartment; import lcsb.mapviewer.model.map.model.Model; import lcsb.mapviewer.model.map.model.ModelFullIndexed; -public class TopSquareCompartmentTest { +public class TopSquareCompartmentTest extends ModelTestFunctions { + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testSerialization() { + SerializationUtils.serialize(new TopSquareCompartment()); + } + + @Test + public void testConstructor1() { + TopSquareCompartment compartment = new TopSquareCompartment(new TopSquareCompartment()); + assertNotNull(compartment); + } + + @Test + public void testConstructor3() { + TopSquareCompartment compartment = new TopSquareCompartment("id"); + assertNotNull(compartment); + } + + @Test + public void testConstructor2() { + Model model = new ModelFullIndexed(null); + model.setWidth(1); + model.setHeight(1); + TopSquareCompartment compartment = new TopSquareCompartment(new Compartment(), model); + assertNotNull(compartment); + } + + @Test + public void testCopy() { + TopSquareCompartment compartment = new TopSquareCompartment().copy(); + assertNotNull(compartment); + } + + @Test(expected = NotImplementedException.class) + public void testInvalidCopy() { + TopSquareCompartment compartment = Mockito.spy(TopSquareCompartment.class); + compartment.copy(); + } - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testSerialization() { - try { - SerializationUtils.serialize(new TopSquareCompartment()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - - @Test - public void testConstructor1() { - try { - TopSquareCompartment compartment = new TopSquareCompartment(new TopSquareCompartment()); - assertNotNull(compartment); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testConstructor3() { - try { - TopSquareCompartment compartment = new TopSquareCompartment("id"); - assertNotNull(compartment); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testConstructor2() { - try { - Model model = new ModelFullIndexed(null); - model.setWidth(1); - model.setHeight(1); - TopSquareCompartment compartment = new TopSquareCompartment(new Compartment(), model); - assertNotNull(compartment); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testCopy() { - try { - TopSquareCompartment compartment = new TopSquareCompartment().copy(); - assertNotNull(compartment); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testInvalidCopy() { - try { - TopSquareCompartment compartment = Mockito.spy(TopSquareCompartment.class); - compartment.copy(); - fail("Exception expected"); - } catch (NotImplementedException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - } diff --git a/model/src/test/java/lcsb/mapviewer/model/map/layout/ColorSchemaTest.java b/model/src/test/java/lcsb/mapviewer/model/map/layout/ColorSchemaTest.java index 6aa5af479e32e7c7e15cf51ffe545507a8e26c9a..6c57476266323b04c017c4a2bc03ba98ba5fb096 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/layout/ColorSchemaTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/layout/ColorSchemaTest.java @@ -1,24 +1,20 @@ package lcsb.mapviewer.model.map.layout; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.*; import java.awt.Color; import java.util.ArrayList; import java.util.List; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; +import lcsb.mapviewer.ModelTestFunctions; import lcsb.mapviewer.common.Pair; import lcsb.mapviewer.model.map.MiriamData; import lcsb.mapviewer.model.map.MiriamType; -import lcsb.mapviewer.model.map.species.Element; -import lcsb.mapviewer.model.map.species.Protein; -import lcsb.mapviewer.model.map.species.Species; +import lcsb.mapviewer.model.map.species.*; -public class ColorSchemaTest { +public class ColorSchemaTest extends ModelTestFunctions { @Before public void setUp() throws Exception { @@ -30,118 +26,87 @@ public class ColorSchemaTest { @Test public void testSetGetters() throws Exception { - try { - ColorSchema cs = new GenericColorSchema(); - List<String> compartments = new ArrayList<>(); - List<Class<? extends Element>> types = new ArrayList<>(); - String name = "S"; - int matches = 79; - Double lineWidth = 5.89; - String reactionIdentifier = "re id"; - Boolean reverseReaction = true; + ColorSchema cs = new GenericColorSchema(); + List<String> compartments = new ArrayList<>(); + List<Class<? extends Element>> types = new ArrayList<>(); + String name = "S"; + int matches = 79; + Double lineWidth = 5.89; + String reactionIdentifier = "re id"; + Boolean reverseReaction = true; - cs.setName(name); - assertEquals(name, cs.getName()); + cs.setName(name); + assertEquals(name, cs.getName()); - cs.setCompartments(compartments); - assertEquals(compartments, cs.getCompartments()); + cs.setCompartments(compartments); + assertEquals(compartments, cs.getCompartments()); - cs.setTypes(types); - assertEquals(types, cs.getTypes()); + cs.setTypes(types); + assertEquals(types, cs.getTypes()); - cs.setMatches(matches); - assertEquals(matches, cs.getMatches()); + cs.setMatches(matches); + assertEquals(matches, cs.getMatches()); - cs.setLineWidth(lineWidth); - assertEquals(lineWidth, cs.getLineWidth()); + cs.setLineWidth(lineWidth); + assertEquals(lineWidth, cs.getLineWidth()); - cs.setElementId(reactionIdentifier); - assertEquals(reactionIdentifier, cs.getElementId()); + cs.setElementId(reactionIdentifier); + assertEquals(reactionIdentifier, cs.getElementId()); - cs.setReverseReaction(reverseReaction); - assertEquals(reverseReaction, cs.getReverseReaction()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + cs.setReverseReaction(reverseReaction); + assertEquals(reverseReaction, cs.getReverseReaction()); } @Test public void testToString() throws Exception { - try { - ColorSchema cs = new GenericColorSchema(); - assertNotNull(cs.toString()); - cs.setName("gene name"); - cs.addCompartment("A"); - cs.addType(Species.class); - cs.setValue(1.2); - cs.setColor(Color.BLACK); - cs.addMiriamData(new MiriamData(MiriamType.CAS, "X")); - assertNotNull(cs.toString()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + ColorSchema cs = new GenericColorSchema(); + assertNotNull(cs.toString()); + cs.setName("gene name"); + cs.addCompartment("A"); + cs.addType(Species.class); + cs.setValue(1.2); + cs.setColor(Color.BLACK); + cs.addMiriamData(new MiriamData(MiriamType.CAS, "X")); + assertNotNull(cs.toString()); } @Test public void testAddCompartments() throws Exception { - try { - ColorSchema cs = new GenericColorSchema(); - cs.addCompartments(new String[] { "a", "b" }); - assertEquals(2, cs.getCompartments().size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + ColorSchema cs = new GenericColorSchema(); + cs.addCompartments(new String[] { "a", "b" }); + assertEquals(2, cs.getCompartments().size()); } @Test public void testAddCompartments2() throws Exception { - try { - ColorSchema cs = new GenericColorSchema(); - List<String> compartments = new ArrayList<>(); - compartments.add("a"); - compartments.add("b"); - cs.addCompartments(compartments); - assertEquals(2, cs.getCompartments().size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + ColorSchema cs = new GenericColorSchema(); + List<String> compartments = new ArrayList<>(); + compartments.add("a"); + compartments.add("b"); + cs.addCompartments(compartments); + assertEquals(2, cs.getCompartments().size()); } @Test public void testAddIdentifgierColumns() throws Exception { - try { - MiriamData generalIdentifier = new MiriamData(); - ColorSchema cs = new GenericColorSchema(); - List<Pair<MiriamType, String>> compartments = new ArrayList<>(); - compartments.add(new Pair<MiriamType, String>(MiriamType.CAS, "x")); - cs.addMiriamData(generalIdentifier); - - assertEquals(1, cs.getMiriamData().size()); - assertEquals(generalIdentifier, cs.getMiriamData().iterator().next()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + MiriamData generalIdentifier = new MiriamData(); + ColorSchema cs = new GenericColorSchema(); + List<Pair<MiriamType, String>> compartments = new ArrayList<>(); + compartments.add(new Pair<MiriamType, String>(MiriamType.CAS, "x")); + cs.addMiriamData(generalIdentifier); + + assertEquals(1, cs.getMiriamData().size()); + assertEquals(generalIdentifier, cs.getMiriamData().iterator().next()); } @Test public void testAddTypes() throws Exception { - try { - ColorSchema cs = new GenericColorSchema(); - List<Class<? extends Element>> compartments = new ArrayList<>(); - compartments.add(Species.class); - compartments.add(Protein.class); - cs.addTypes(compartments); - assertEquals(2, cs.getTypes().size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + ColorSchema cs = new GenericColorSchema(); + List<Class<? extends Element>> compartments = new ArrayList<>(); + compartments.add(Species.class); + compartments.add(Protein.class); + cs.addTypes(compartments); + assertEquals(2, cs.getTypes().size()); } } diff --git a/model/src/test/java/lcsb/mapviewer/model/map/layout/ElementGroupTest.java b/model/src/test/java/lcsb/mapviewer/model/map/layout/ElementGroupTest.java index 5c8e121c5465ee3122d334e5d6f20cf1962e7f40..c362be4c24dd2e5b9c920f594e6259031ccd41ea 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/layout/ElementGroupTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/layout/ElementGroupTest.java @@ -1,66 +1,49 @@ package lcsb.mapviewer.model.map.layout; -import static org.junit.Assert.assertEquals; +import static org.junit.Assert.*; import java.util.ArrayList; import java.util.List; import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; -import lcsb.mapviewer.model.map.layout.ElementGroup; +import lcsb.mapviewer.ModelTestFunctions; import lcsb.mapviewer.model.map.species.Element; import lcsb.mapviewer.model.map.species.GenericProtein; -public class ElementGroupTest { +public class ElementGroupTest extends ModelTestFunctions { - @Before - public void setUp() throws Exception { - } + @Before + public void setUp() throws Exception { + } - @After - public void tearDown() throws Exception { - } + @After + public void tearDown() throws Exception { + } - @Test - public void testSerialization() { - try { - SerializationUtils.serialize(new ElementGroup()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } + @Test + public void testSerialization() { + SerializationUtils.serialize(new ElementGroup()); + } - @Test - public void testGetters() { - try { - ElementGroup group = new ElementGroup(); - String idGroup = "str"; - List<Element> elements = new ArrayList<>(); + @Test + public void testGetters() { + ElementGroup group = new ElementGroup(); + String idGroup = "str"; + List<Element> elements = new ArrayList<>(); - group.setIdGroup(idGroup); - group.setElements(elements); + group.setIdGroup(idGroup); + group.setElements(elements); - assertEquals(idGroup, group.getIdGroup()); - assertEquals(elements, group.getElements()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } + assertEquals(idGroup, group.getIdGroup()); + assertEquals(elements, group.getElements()); + } - @Test - public void testAddElement() { - try { - ElementGroup group = new ElementGroup(); - group.addElement(new GenericProtein("id")); - assertEquals(1, group.getElements().size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } + @Test + public void testAddElement() { + ElementGroup group = new ElementGroup(); + group.addElement(new GenericProtein("id")); + assertEquals(1, group.getElements().size()); + } } diff --git a/model/src/test/java/lcsb/mapviewer/model/map/layout/GeneVariationColorSchemaTest.java b/model/src/test/java/lcsb/mapviewer/model/map/layout/GeneVariationColorSchemaTest.java index da6babd624efb4f997c14490cd8f5a3fe293a0c2..107745800958e71af79a5acd5ac416f79b5860b8 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/layout/GeneVariationColorSchemaTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/layout/GeneVariationColorSchemaTest.java @@ -6,119 +6,73 @@ import java.util.ArrayList; import java.util.List; import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; +import org.mockito.Mockito; +import lcsb.mapviewer.ModelTestFunctions; import lcsb.mapviewer.common.exception.NotImplementedException; +import lcsb.mapviewer.model.map.layout.graphics.Layer; -public class GeneVariationColorSchemaTest { - - @AfterClass - public static void tearDownAfterClass() throws Exception { - } - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testSerialization() { - try { - SerializationUtils.serialize(new GeneVariationColorSchema()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testConstructor() { - try { - GeneVariationColorSchema schema = new GeneVariationColorSchema(); - schema.setDescription("desc"); - GeneVariationColorSchema copy = new GeneVariationColorSchema(schema); - assertEquals("desc", copy.getDescription()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testCopy() { - try { - GeneVariationColorSchema schema = new GeneVariationColorSchema(); - schema.setDescription("desc"); - GeneVariationColorSchema copy = schema.copy(); - - assertEquals("desc", copy.getDescription()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testGetters() { - try { - - List<GeneVariation> geneVariations = new ArrayList<>(); - - GeneVariationColorSchema schema = new GeneVariationColorSchema(); - schema.setGeneVariations(geneVariations); - - assertEquals(geneVariations, schema.getGeneVariations()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testAddGeneVariations() { - try { - - List<GeneVariation> geneVariations = new ArrayList<>(); - geneVariations.add(new GeneVariation()); - - GeneVariationColorSchema schema = new GeneVariationColorSchema(); - schema.addGeneVariations(geneVariations); - - assertEquals(1, schema.getGeneVariations().size()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testInvalidCopy() { - try { - GeneVariationColorSchema schema = new GeneVariationColorSchema() { - - /** - * - */ - private static final long serialVersionUID = 1L; - }; - schema.copy(); - fail("Exception expected"); - - } catch (NotImplementedException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } +public class GeneVariationColorSchemaTest extends ModelTestFunctions { + + @AfterClass + public static void tearDownAfterClass() throws Exception { + } + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testSerialization() { + SerializationUtils.serialize(new GeneVariationColorSchema()); + } + + @Test + public void testConstructor() { + GeneVariationColorSchema schema = new GeneVariationColorSchema(); + schema.setDescription("desc"); + GeneVariationColorSchema copy = new GeneVariationColorSchema(schema); + assertEquals("desc", copy.getDescription()); + } + + @Test + public void testCopy() { + GeneVariationColorSchema schema = new GeneVariationColorSchema(); + schema.setDescription("desc"); + GeneVariationColorSchema copy = schema.copy(); + + assertEquals("desc", copy.getDescription()); + } + + @Test + public void testGetters() { + List<GeneVariation> geneVariations = new ArrayList<>(); + + GeneVariationColorSchema schema = new GeneVariationColorSchema(); + schema.setGeneVariations(geneVariations); + + assertEquals(geneVariations, schema.getGeneVariations()); + } + + @Test + public void testAddGeneVariations() { + List<GeneVariation> geneVariations = new ArrayList<>(); + geneVariations.add(new GeneVariation()); + + GeneVariationColorSchema schema = new GeneVariationColorSchema(); + schema.addGeneVariations(geneVariations); + + assertEquals(1, schema.getGeneVariations().size()); + } + + @Test(expected = NotImplementedException.class) + public void testInvalidCopy() { + Mockito.spy(GeneVariationColorSchema.class).copy(); + } } diff --git a/model/src/test/java/lcsb/mapviewer/model/map/layout/GeneVariationTest.java b/model/src/test/java/lcsb/mapviewer/model/map/layout/GeneVariationTest.java index 0281c8fb7bddd2d7051bf739890857f25c7081a9..bd9c5b0f5ec3ef52102f14c731ea6b770f063acc 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/layout/GeneVariationTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/layout/GeneVariationTest.java @@ -1,87 +1,60 @@ package lcsb.mapviewer.model.map.layout; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; +import org.mockito.Mockito; +import lcsb.mapviewer.ModelTestFunctions; import lcsb.mapviewer.common.exception.NotImplementedException; -import lcsb.mapviewer.model.map.MiriamData; +import lcsb.mapviewer.model.map.layout.graphics.Layer; -public class GeneVariationTest { +public class GeneVariationTest extends ModelTestFunctions { - @AfterClass - public static void tearDownAfterClass() throws Exception { - } + @AfterClass + public static void tearDownAfterClass() throws Exception { + } - @Before - public void setUp() throws Exception { - } + @Before + public void setUp() throws Exception { + } - @After - public void tearDown() throws Exception { - } + @After + public void tearDown() throws Exception { + } - @Test - public void testGetters() throws Exception { - try { - String modifiedDna = "str"; + @Test + public void testGetters() throws Exception { + String modifiedDna = "str"; - int position = 12; + int position = 12; - GeneVariation gv = new GeneVariation(); + GeneVariation gv = new GeneVariation(); - gv.setModifiedDna(modifiedDna); - assertEquals(modifiedDna, gv.getModifiedDna()); + gv.setModifiedDna(modifiedDna); + assertEquals(modifiedDna, gv.getModifiedDna()); - gv.setPosition(position); + gv.setPosition(position); - assertEquals((long) position, (long) gv.getPosition()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } + assertEquals((long) position, (long) gv.getPosition()); + } - @Test - public void testCopy() throws Exception { - try { - String modifiedDna = "str"; + @Test + public void testCopy() throws Exception { + String modifiedDna = "str"; - GeneVariation gv = new GeneVariation(); + GeneVariation gv = new GeneVariation(); - gv.setModifiedDna(modifiedDna); + gv.setModifiedDna(modifiedDna); - GeneVariation copy = gv.copy(); + GeneVariation copy = gv.copy(); - assertEquals(gv.getModifiedDna(), copy.getModifiedDna()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } + assertEquals(gv.getModifiedDna(), copy.getModifiedDna()); + } - @Test - public void testInvalidCopy() throws Exception { - try { - GeneVariation gv = new GeneVariation() { - - /** - * - */ - private static final long serialVersionUID = 1L; - }; - - gv.copy(); - fail("Exception expected"); - } catch (NotImplementedException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } + @Test(expected = NotImplementedException.class) + public void testInvalidCopy() throws Exception { + Mockito.spy(GeneVariation.class).copy(); + } } diff --git a/model/src/test/java/lcsb/mapviewer/model/map/layout/GenericColorSchemaTest.java b/model/src/test/java/lcsb/mapviewer/model/map/layout/GenericColorSchemaTest.java index 02c2315dc89ec6a9def6257f225199cd285471da..8b8be18c9b5b56a02a2242350520c04ce712834c 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/layout/GenericColorSchemaTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/layout/GenericColorSchemaTest.java @@ -1,81 +1,48 @@ package lcsb.mapviewer.model.map.layout; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; +import org.mockito.Mockito; +import lcsb.mapviewer.ModelTestFunctions; import lcsb.mapviewer.common.exception.NotImplementedException; -public class GenericColorSchemaTest { - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testSerialization() { - try { - SerializationUtils.serialize(new GenericColorSchema()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testConstructor() { - try { - GenericColorSchema schema = new GenericColorSchema(); - schema.setDescription("desc"); - GenericColorSchema copy = new GenericColorSchema(schema); - assertEquals("desc", copy.getDescription()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testCopy() { - try { - GenericColorSchema schema = new GenericColorSchema(); - schema.setDescription("desc"); - GenericColorSchema copy = schema.copy(); - - assertEquals("desc", copy.getDescription()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testInvalidCopy() { - try { - GenericColorSchema schema = new GenericColorSchema() { - - /** - * - */ - private static final long serialVersionUID = 1L; - }; - schema.copy(); - fail("Exception expected"); - - } catch (NotImplementedException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } +public class GenericColorSchemaTest extends ModelTestFunctions { + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testSerialization() { + SerializationUtils.serialize(new GenericColorSchema()); + } + + @Test + public void testConstructor() { + GenericColorSchema schema = new GenericColorSchema(); + schema.setDescription("desc"); + GenericColorSchema copy = new GenericColorSchema(schema); + assertEquals("desc", copy.getDescription()); + } + + @Test + public void testCopy() { + GenericColorSchema schema = new GenericColorSchema(); + schema.setDescription("desc"); + GenericColorSchema copy = schema.copy(); + + assertEquals("desc", copy.getDescription()); + } + + @Test(expected = NotImplementedException.class) + public void testInvalidCopy() { + Mockito.spy(GenericColorSchema.class).copy(); + } } diff --git a/model/src/test/java/lcsb/mapviewer/model/map/layout/InvalidColorSchemaExceptionTest.java b/model/src/test/java/lcsb/mapviewer/model/map/layout/InvalidColorSchemaExceptionTest.java index 24130c2591587c56410a567d979670e44365e75e..ecbf4805329ccc3d6ecfe0e455173db328cc2539 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/layout/InvalidColorSchemaExceptionTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/layout/InvalidColorSchemaExceptionTest.java @@ -3,55 +3,39 @@ package lcsb.mapviewer.model.map.layout; import static org.junit.Assert.*; import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.Test; - -public class InvalidColorSchemaExceptionTest { - - @AfterClass - public static void tearDownAfterClass() throws Exception { - } - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testSerialization() { - try { - SerializationUtils.serialize(new InvalidColorSchemaException("x")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testConstructor1() { - try { - Exception e = new InvalidColorSchemaException(new Exception()); - assertNotNull(e); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testConstructor2() { - try { - Exception e = new InvalidColorSchemaException("message", new Exception()); - assertNotNull(e); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } +import org.junit.*; + +import lcsb.mapviewer.ModelTestFunctions; + +public class InvalidColorSchemaExceptionTest extends ModelTestFunctions { + + @AfterClass + public static void tearDownAfterClass() throws Exception { + } + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testSerialization() { + SerializationUtils.serialize(new InvalidColorSchemaException("x")); + } + + @Test + public void testConstructor1() { + Exception e = new InvalidColorSchemaException(new Exception()); + assertNotNull(e); + } + + @Test + public void testConstructor2() { + Exception e = new InvalidColorSchemaException("message", new Exception()); + assertNotNull(e); + } } diff --git a/model/src/test/java/lcsb/mapviewer/model/map/layout/LayoutTest.java b/model/src/test/java/lcsb/mapviewer/model/map/layout/LayoutTest.java index 7fc3a08cd0a4cc028d262841c87807f7cf105407..c898f57198a97ba5aff9d86a345f0f190d742472 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/layout/LayoutTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/layout/LayoutTest.java @@ -1,20 +1,18 @@ package lcsb.mapviewer.model.map.layout; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; +import org.mockito.Mockito; +import lcsb.mapviewer.ModelTestFunctions; import lcsb.mapviewer.common.Configuration; import lcsb.mapviewer.common.exception.NotImplementedException; import lcsb.mapviewer.model.cache.UploadedFileEntry; +import lcsb.mapviewer.model.map.layout.graphics.Layer; -public class LayoutTest { +public class LayoutTest extends ModelTestFunctions { @Before public void setUp() throws Exception { @@ -26,130 +24,85 @@ public class LayoutTest { @Test public void testSerialization() { - try { - SerializationUtils.serialize(new Layout()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + SerializationUtils.serialize(new Layout()); } @Test public void testConstructor() { - try { - String title = "TIT"; - boolean publicL = true; - Layout layout = new Layout(title, publicL); - assertEquals(title, layout.getTitle()); - assertEquals(publicL, layout.isPublicLayout()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String title = "TIT"; + boolean publicL = true; + Layout layout = new Layout(title, publicL); + assertEquals(title, layout.getTitle()); + assertEquals(publicL, layout.isPublicLayout()); } @Test public void testConstructor2() { - try { - String title = "TIT"; - boolean publicL = true; - Layout layout = new Layout(title, publicL); - Layout layout2 = new Layout(layout); - assertNotNull(layout2); - UploadedFileEntry fileEntry = new UploadedFileEntry(); - fileEntry.setFileContent(new byte[] {}); - - layout.setInputData(fileEntry); - Layout layout3 = new Layout(layout); - assertNotNull(layout3); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String title = "TIT"; + boolean publicL = true; + Layout layout = new Layout(title, publicL); + Layout layout2 = new Layout(layout); + assertNotNull(layout2); + UploadedFileEntry fileEntry = new UploadedFileEntry(); + fileEntry.setFileContent(new byte[] {}); + + layout.setInputData(fileEntry); + Layout layout3 = new Layout(layout); + assertNotNull(layout3); } @Test public void testConstructorWithOrder() { - try { - boolean publicL = true; - Layout overlay1 = new Layout(null, publicL); - overlay1.setOrderIndex(12); - Layout overlay2 = new Layout(overlay1); - assertEquals(overlay1.getOrderIndex(), overlay2.getOrderIndex()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + boolean publicL = true; + Layout overlay1 = new Layout(null, publicL); + overlay1.setOrderIndex(12); + Layout overlay2 = new Layout(overlay1); + assertEquals(overlay1.getOrderIndex(), overlay2.getOrderIndex()); } @Test public void testCopy() { - try { - String title = "TIT"; - boolean publicL = true; - Layout layout = new Layout(title, publicL); - Layout layout2 = layout.copy(); - assertNotNull(layout2); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String title = "TIT"; + boolean publicL = true; + Layout layout = new Layout(title, publicL); + Layout layout2 = layout.copy(); + assertNotNull(layout2); } - @Test + @Test(expected = NotImplementedException.class) public void testInvalidCopy() { - try { - Layout layout = new Layout() { - - /** - * - */ - private static final long serialVersionUID = 1L; - }; - layout.copy(); - fail("Exception expected"); - } catch (NotImplementedException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Mockito.spy(Layout.class).copy(); } @Test public void testGetters() { - try { - boolean hierarchicalView = false; - boolean publicLayout = true; - int id = 62; - String description = "qds"; - String title = "tit"; - LayoutStatus status = LayoutStatus.FAILURE; - double progress = 1.6; - UploadedFileEntry inputData = new UploadedFileEntry(); - Layout layout = new Layout(); - layout.setHierarchicalView(hierarchicalView); - assertEquals(hierarchicalView, layout.isHierarchicalView()); - layout.setId(id); - assertEquals(id, layout.getId()); - layout.setDescription(description); - assertEquals(description, layout.getDescription()); - layout.setTitle(title); - assertEquals(title, layout.getTitle()); - layout.setCreator(null); - assertNull(layout.getCreator()); - layout.setStatus(status); - assertEquals(status, layout.getStatus()); - layout.setProgress(progress); - assertEquals(progress, layout.getProgress(), Configuration.EPSILON); - layout.setInputData(inputData); - assertEquals(inputData, layout.getInputData()); - layout.setPublicLayout(publicLayout); - assertEquals(publicLayout, layout.isPublicLayout()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + boolean hierarchicalView = false; + boolean publicLayout = true; + int id = 62; + String description = "qds"; + String title = "tit"; + LayoutStatus status = LayoutStatus.FAILURE; + double progress = 1.6; + UploadedFileEntry inputData = new UploadedFileEntry(); + Layout layout = new Layout(); + layout.setHierarchicalView(hierarchicalView); + assertEquals(hierarchicalView, layout.isHierarchicalView()); + layout.setId(id); + assertEquals(id, layout.getId()); + layout.setDescription(description); + assertEquals(description, layout.getDescription()); + layout.setTitle(title); + assertEquals(title, layout.getTitle()); + layout.setCreator(null); + assertNull(layout.getCreator()); + layout.setStatus(status); + assertEquals(status, layout.getStatus()); + layout.setProgress(progress); + assertEquals(progress, layout.getProgress(), Configuration.EPSILON); + layout.setInputData(inputData); + assertEquals(inputData, layout.getInputData()); + layout.setPublicLayout(publicLayout); + assertEquals(publicLayout, layout.isPublicLayout()); } } diff --git a/model/src/test/java/lcsb/mapviewer/model/map/layout/ReferenceGenomeGeneMappingTest.java b/model/src/test/java/lcsb/mapviewer/model/map/layout/ReferenceGenomeGeneMappingTest.java index 48aa9f16953e25aa6c2c18a0a3cd51d74e59f779..c914d44e5fe1d53e2f6c92966719df91e2adcb64 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/layout/ReferenceGenomeGeneMappingTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/layout/ReferenceGenomeGeneMappingTest.java @@ -1,54 +1,46 @@ package lcsb.mapviewer.model.map.layout; -import static org.junit.Assert.assertEquals; +import static org.junit.Assert.*; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import lcsb.mapviewer.ModelTestFunctions; import lcsb.mapviewer.common.Configuration; public class ReferenceGenomeGeneMappingTest extends ModelTestFunctions { - @AfterClass - public static void tearDownAfterClass() throws Exception { - } - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testGetters() { - try { - int id = 96; - ReferenceGenome genome = new ReferenceGenome(); - String name = "test_name_97"; - String url = "http://some.url/"; - double progress = 4; - - ReferenceGenomeGeneMapping mapping = new ReferenceGenomeGeneMapping(); - mapping.setId(id); - mapping.setReferenceGenome(genome); - mapping.setName(name); - mapping.setSourceUrl(url); - mapping.setDownloadProgress(progress); - - assertEquals(genome, mapping.getReferenceGenome()); - assertEquals(name, mapping.getName()); - assertEquals(url, mapping.getSourceUrl()); - assertEquals(progress, mapping.getDownloadProgress(), Configuration.EPSILON); - assertEquals(id, mapping.getId()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } + @AfterClass + public static void tearDownAfterClass() throws Exception { + } + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testGetters() { + int id = 96; + ReferenceGenome genome = new ReferenceGenome(); + String name = "test_name_97"; + String url = "http://some.url/"; + double progress = 4; + + ReferenceGenomeGeneMapping mapping = new ReferenceGenomeGeneMapping(); + mapping.setId(id); + mapping.setReferenceGenome(genome); + mapping.setName(name); + mapping.setSourceUrl(url); + mapping.setDownloadProgress(progress); + + assertEquals(genome, mapping.getReferenceGenome()); + assertEquals(name, mapping.getName()); + assertEquals(url, mapping.getSourceUrl()); + assertEquals(progress, mapping.getDownloadProgress(), Configuration.EPSILON); + assertEquals(id, mapping.getId()); + } } diff --git a/model/src/test/java/lcsb/mapviewer/model/map/layout/ReferenceGenomeTest.java b/model/src/test/java/lcsb/mapviewer/model/map/layout/ReferenceGenomeTest.java index d1416e065cc81d4c4d7233431382b534cac3b712..b9182eee56d98e58c067ecf82d22da0fb5c9971e 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/layout/ReferenceGenomeTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/layout/ReferenceGenomeTest.java @@ -6,10 +6,7 @@ import java.util.ArrayList; import java.util.List; import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import lcsb.mapviewer.common.Configuration; import lcsb.mapviewer.model.map.MiriamData; @@ -17,73 +14,58 @@ import lcsb.mapviewer.model.map.MiriamType; public class ReferenceGenomeTest { - @AfterClass - public static void tearDownAfterClass() throws Exception { - } + @AfterClass + public static void tearDownAfterClass() throws Exception { + } - @Before - public void setUp() throws Exception { - } + @Before + public void setUp() throws Exception { + } - @After - public void tearDown() throws Exception { - } + @After + public void tearDown() throws Exception { + } - @Test - public void testSerialization() { - try { - SerializationUtils.serialize(new ReferenceGenome()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } + @Test + public void testSerialization() { + SerializationUtils.serialize(new ReferenceGenome()); + } - @Test - public void testAddReferenceGenomeGeneMapping() { - try { - ReferenceGenome genome = new ReferenceGenome(); - assertEquals(0, genome.getGeneMapping().size()); - genome.addReferenceGenomeGeneMapping(new ReferenceGenomeGeneMapping()); - assertEquals(1, genome.getGeneMapping().size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } + @Test + public void testAddReferenceGenomeGeneMapping() { + ReferenceGenome genome = new ReferenceGenome(); + assertEquals(0, genome.getGeneMapping().size()); + genome.addReferenceGenomeGeneMapping(new ReferenceGenomeGeneMapping()); + assertEquals(1, genome.getGeneMapping().size()); + } - @Test - public void testGetters() { - try { - int id = 16; - MiriamData organism = new MiriamData(MiriamType.TAXONOMY, "9606"); - ReferenceGenomeType type = ReferenceGenomeType.UCSC; - String version = "hg19"; - double downloadProgress = 3.0; - String sourceUrl = "google.pl"; - List<ReferenceGenomeGeneMapping> geneMapping = new ArrayList<>(); + @Test + public void testGetters() { + int id = 16; + MiriamData organism = new MiriamData(MiriamType.TAXONOMY, "9606"); + ReferenceGenomeType type = ReferenceGenomeType.UCSC; + String version = "hg19"; + double downloadProgress = 3.0; + String sourceUrl = "google.pl"; + List<ReferenceGenomeGeneMapping> geneMapping = new ArrayList<>(); - ReferenceGenome genome = new ReferenceGenome(); + ReferenceGenome genome = new ReferenceGenome(); - genome.setDownloadProgress(downloadProgress); - genome.setId(id); - genome.setOrganism(organism); - genome.setSourceUrl(sourceUrl); - genome.setType(type); - genome.setVersion(version); - genome.setGeneMapping(geneMapping); + genome.setDownloadProgress(downloadProgress); + genome.setId(id); + genome.setOrganism(organism); + genome.setSourceUrl(sourceUrl); + genome.setType(type); + genome.setVersion(version); + genome.setGeneMapping(geneMapping); - assertEquals(downloadProgress, genome.getDownloadProgress(), Configuration.EPSILON); - assertEquals(id, genome.getId()); - assertEquals(organism, genome.getOrganism()); - assertEquals(sourceUrl, genome.getSourceUrl()); - assertEquals(type, genome.getType()); - assertEquals(version, genome.getVersion()); - assertEquals(geneMapping, genome.getGeneMapping()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } + assertEquals(downloadProgress, genome.getDownloadProgress(), Configuration.EPSILON); + assertEquals(id, genome.getId()); + assertEquals(organism, genome.getOrganism()); + assertEquals(sourceUrl, genome.getSourceUrl()); + assertEquals(type, genome.getType()); + assertEquals(version, genome.getVersion()); + assertEquals(geneMapping, genome.getGeneMapping()); + } } diff --git a/model/src/test/java/lcsb/mapviewer/model/map/layout/graphics/LayerComparatorTest.java b/model/src/test/java/lcsb/mapviewer/model/map/layout/graphics/LayerComparatorTest.java index f99db67d578063038c52b909f5f8f951473f95f1..70ddddbe4349ba8df81b08b6b32455995a86b2b1 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/layout/graphics/LayerComparatorTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/layout/graphics/LayerComparatorTest.java @@ -1,200 +1,172 @@ package lcsb.mapviewer.model.map.layout.graphics; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; +import org.mockito.Mockito; +import lcsb.mapviewer.ModelTestFunctions; import lcsb.mapviewer.common.exception.NotImplementedException; import lcsb.mapviewer.model.graphics.PolylineData; -public class LayerComparatorTest { - LayerComparator comparator = new LayerComparator(); - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testEquals() { - try { - Layer layer1 = getLayer(); - Layer layer2 = getLayer(); +public class LayerComparatorTest extends ModelTestFunctions { + LayerComparator comparator = new LayerComparator(); - assertEquals(0, comparator.compare(new Layer(), new Layer())); - assertEquals(0, comparator.compare(layer1, layer2)); - assertEquals(0, comparator.compare(layer1, layer1)); - assertEquals(0, comparator.compare(null, null)); + @Before + public void setUp() throws Exception { + } - } catch (Exception e) { - e.printStackTrace(); - fail("Unknown exception"); - } - } + @After + public void tearDown() throws Exception { + } - @Test - public void testInvalid() { - try { - class Tmp extends Layer { - private static final long serialVersionUID = 1L; - } - ; - Tmp layer1 = new Tmp(); - Tmp layer2 = new Tmp(); + @Test + public void testEquals() { + Layer layer1 = getLayer(); + Layer layer2 = getLayer(); - comparator.compare(layer1, layer2); - fail("Exception expected"); - } catch (NotImplementedException e) { + assertEquals(0, comparator.compare(new Layer(), new Layer())); + assertEquals(0, comparator.compare(layer1, layer2)); + assertEquals(0, comparator.compare(layer1, layer1)); + assertEquals(0, comparator.compare(null, null)); + } - } catch (Exception e) { - e.printStackTrace(); - fail("Unknown exception"); - } - } + @Test(expected = NotImplementedException.class) + public void testInvalid() { + class Tmp extends Layer { + private static final long serialVersionUID = 1L; + } + ; + Tmp layer1 = new Tmp(); + Tmp layer2 = new Tmp(); - private Layer getLayer() { - Layer layer = new Layer(); + comparator.compare(layer1, layer2); + } - layer.setLayerId("A"); - layer.setName("B"); - layer.setVisible(true); - layer.setLocked(true); + private Layer getLayer() { + Layer layer = new Layer(); - PolylineData line = new PolylineData(); - layer.addLayerLine(line); + layer.setLayerId("A"); + layer.setName("B"); + layer.setVisible(true); + layer.setLocked(true); - LayerText text = new LayerText(); - text.setWidth(32.1); - text.setNotes("SAda"); - layer.addLayerText(text); + PolylineData line = new PolylineData(); + layer.addLayerLine(line); - LayerRect rect = new LayerRect(); - rect.setHeight(4.3); - layer.addLayerRect(rect); + LayerText text = new LayerText(); + text.setWidth(32.1); + text.setNotes("SAda"); + layer.addLayerText(text); - LayerOval oval = new LayerOval(); - oval.setX(12.0); - layer.addLayerOval(oval); + LayerRect rect = new LayerRect(); + rect.setHeight(4.3); + layer.addLayerRect(rect); - return layer; - } + LayerOval oval = new LayerOval(); + oval.setX(12.0); + layer.addLayerOval(oval); - @Test - public void testDifferent() throws Exception { - try { - Layer layer1 = getLayer(); - Layer layer2 = getLayer(); + return layer; + } - assertTrue(comparator.compare(layer1, new Layer()) != 0); + @Test + public void testDifferent() throws Exception { + Layer layer1 = getLayer(); + Layer layer2 = getLayer(); - assertTrue(comparator.compare(layer1, null) != 0); - assertTrue(comparator.compare(null, layer1) != 0); - assertTrue(comparator.compare(layer1, new Layer() { + assertTrue(comparator.compare(layer1, new Layer()) != 0); - /** - * - */ - private static final long serialVersionUID = 1L; - }) != 0); + assertTrue(comparator.compare(layer1, null) != 0); + assertTrue(comparator.compare(null, layer1) != 0); + assertTrue(comparator.compare(layer1, Mockito.spy(Layer.class)) != 0); - layer1 = getLayer(); - layer2 = getLayer(); + layer1 = getLayer(); + layer2 = getLayer(); - layer1.setName("ASdasdas"); + layer1.setName("ASdasdas"); - assertTrue(comparator.compare(layer1, layer2) != 0); - assertTrue(comparator.compare(layer2, layer1) != 0); + assertTrue(comparator.compare(layer1, layer2) != 0); + assertTrue(comparator.compare(layer2, layer1) != 0); - layer1 = getLayer(); - layer2 = getLayer(); + layer1 = getLayer(); + layer2 = getLayer(); - layer1.getLines().add(new PolylineData()); + layer1.getLines().add(new PolylineData()); - assertTrue(comparator.compare(layer1, layer2) != 0); - assertTrue(comparator.compare(layer2, layer1) != 0); + assertTrue(comparator.compare(layer1, layer2) != 0); + assertTrue(comparator.compare(layer2, layer1) != 0); - layer1 = getLayer(); - layer2 = getLayer(); + layer1 = getLayer(); + layer2 = getLayer(); - layer1.getLines().get(0).setWidth(654); + layer1.getLines().get(0).setWidth(654); - assertTrue(comparator.compare(layer1, layer2) != 0); - assertTrue(comparator.compare(layer2, layer1) != 0); + assertTrue(comparator.compare(layer1, layer2) != 0); + assertTrue(comparator.compare(layer2, layer1) != 0); - layer1 = getLayer(); - layer2 = getLayer(); + layer1 = getLayer(); + layer2 = getLayer(); - layer1.getOvals().add(new LayerOval()); + layer1.getOvals().add(new LayerOval()); - assertTrue(comparator.compare(layer1, layer2) != 0); - assertTrue(comparator.compare(layer2, layer1) != 0); + assertTrue(comparator.compare(layer1, layer2) != 0); + assertTrue(comparator.compare(layer2, layer1) != 0); - layer1 = getLayer(); - layer2 = getLayer(); + layer1 = getLayer(); + layer2 = getLayer(); - layer1.getOvals().get(0).setWidth("654"); + layer1.getOvals().get(0).setWidth("654"); - assertTrue(comparator.compare(layer1, layer2) != 0); - assertTrue(comparator.compare(layer2, layer1) != 0); + assertTrue(comparator.compare(layer1, layer2) != 0); + assertTrue(comparator.compare(layer2, layer1) != 0); - layer1 = getLayer(); - layer2 = getLayer(); + layer1 = getLayer(); + layer2 = getLayer(); - layer1.getRectangles().add(new LayerRect()); + layer1.getRectangles().add(new LayerRect()); - assertTrue(comparator.compare(layer1, layer2) != 0); - assertTrue(comparator.compare(layer2, layer1) != 0); + assertTrue(comparator.compare(layer1, layer2) != 0); + assertTrue(comparator.compare(layer2, layer1) != 0); - layer1 = getLayer(); - layer2 = getLayer(); + layer1 = getLayer(); + layer2 = getLayer(); - layer1.getRectangles().get(0).setWidth("654"); + layer1.getRectangles().get(0).setWidth("654"); - assertTrue(comparator.compare(layer1, layer2) != 0); - assertTrue(comparator.compare(layer2, layer1) != 0); + assertTrue(comparator.compare(layer1, layer2) != 0); + assertTrue(comparator.compare(layer2, layer1) != 0); - layer1 = getLayer(); - layer2 = getLayer(); + layer1 = getLayer(); + layer2 = getLayer(); - layer1.getTexts().add(new LayerText()); + layer1.getTexts().add(new LayerText()); - assertTrue(comparator.compare(layer1, layer2) != 0); - assertTrue(comparator.compare(layer2, layer1) != 0); + assertTrue(comparator.compare(layer1, layer2) != 0); + assertTrue(comparator.compare(layer2, layer1) != 0); - layer1 = getLayer(); - layer2 = getLayer(); + layer1 = getLayer(); + layer2 = getLayer(); - layer1.getTexts().get(0).setWidth("654"); + layer1.getTexts().get(0).setWidth("654"); - assertTrue(comparator.compare(layer1, layer2) != 0); - assertTrue(comparator.compare(layer2, layer1) != 0); + assertTrue(comparator.compare(layer1, layer2) != 0); + assertTrue(comparator.compare(layer2, layer1) != 0); - layer1 = getLayer(); - layer2 = getLayer(); + layer1 = getLayer(); + layer2 = getLayer(); - layer1.setVisible(false); + layer1.setVisible(false); - assertTrue(comparator.compare(layer1, layer2) != 0); - assertTrue(comparator.compare(layer2, layer1) != 0); + assertTrue(comparator.compare(layer1, layer2) != 0); + assertTrue(comparator.compare(layer2, layer1) != 0); - layer1 = getLayer(); - layer2 = getLayer(); + layer1 = getLayer(); + layer2 = getLayer(); - layer1.setLocked(false); + layer1.setLocked(false); - assertTrue(comparator.compare(layer1, layer2) != 0); - assertTrue(comparator.compare(layer2, layer1) != 0); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } + assertTrue(comparator.compare(layer1, layer2) != 0); + assertTrue(comparator.compare(layer2, layer1) != 0); + } } diff --git a/model/src/test/java/lcsb/mapviewer/model/map/layout/graphics/LayerOvalComparatorTest.java b/model/src/test/java/lcsb/mapviewer/model/map/layout/graphics/LayerOvalComparatorTest.java index f95ddfcac4fbb95ac860e852d516ad4b71284510..d6f37724b1066c695758cd1acae7982f30b60855 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/layout/graphics/LayerOvalComparatorTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/layout/graphics/LayerOvalComparatorTest.java @@ -1,18 +1,16 @@ package lcsb.mapviewer.model.map.layout.graphics; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import java.awt.Color; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; +import org.mockito.Mockito; +import lcsb.mapviewer.ModelTestFunctions; import lcsb.mapviewer.common.exception.NotImplementedException; -public class LayerOvalComparatorTest { +public class LayerOvalComparatorTest extends ModelTestFunctions { LayerOvalComparator comparator = new LayerOvalComparator(); @Before @@ -25,19 +23,13 @@ public class LayerOvalComparatorTest { @Test public void testEquals() { - try { - LayerOval layer1 = getLayerOval(); - LayerOval layer2 = getLayerOval(); - - assertEquals(0, comparator.compare(new LayerOval(), new LayerOval())); - assertEquals(0, comparator.compare(layer1, layer2)); - assertEquals(0, comparator.compare(layer1, layer1)); - assertEquals(0, comparator.compare(null, null)); - - } catch (Exception e) { - e.printStackTrace(); - fail("Unknown exception"); - } + LayerOval layer1 = getLayerOval(); + LayerOval layer2 = getLayerOval(); + + assertEquals(0, comparator.compare(new LayerOval(), new LayerOval())); + assertEquals(0, comparator.compare(layer1, layer2)); + assertEquals(0, comparator.compare(layer1, layer1)); + assertEquals(0, comparator.compare(null, null)); } private LayerOval getLayerOval() { @@ -51,110 +43,82 @@ public class LayerOvalComparatorTest { @Test public void testDifferent() { - try { - LayerOval layer1 = getLayerOval(); - LayerOval layer2 = getLayerOval(); - - assertTrue(comparator.compare(layer1, new LayerOval()) != 0); + LayerOval layer1 = getLayerOval(); + LayerOval layer2 = getLayerOval(); - assertTrue(comparator.compare(layer1, null) != 0); - assertTrue(comparator.compare(null, layer1) != 0); + assertTrue(comparator.compare(layer1, new LayerOval()) != 0); - layer1 = getLayerOval(); - layer2 = getLayerOval(); + assertTrue(comparator.compare(layer1, null) != 0); + assertTrue(comparator.compare(null, layer1) != 0); - layer1.setColor(Color.GREEN); + layer1 = getLayerOval(); + layer2 = getLayerOval(); - assertTrue(comparator.compare(layer1, layer2) != 0); - assertTrue(comparator.compare(layer2, layer1) != 0); + layer1.setColor(Color.GREEN); - layer1 = getLayerOval(); - layer2 = getLayerOval(); + assertTrue(comparator.compare(layer1, layer2) != 0); + assertTrue(comparator.compare(layer2, layer1) != 0); - layer1.setHeight(78.0); + layer1 = getLayerOval(); + layer2 = getLayerOval(); - assertTrue(comparator.compare(layer1, layer2) != 0); - assertTrue(comparator.compare(layer2, layer1) != 0); + layer1.setHeight(78.0); - layer1 = getLayerOval(); - layer2 = getLayerOval(); + assertTrue(comparator.compare(layer1, layer2) != 0); + assertTrue(comparator.compare(layer2, layer1) != 0); - layer1.setHeight(1.2); + layer1 = getLayerOval(); + layer2 = getLayerOval(); - assertTrue(comparator.compare(layer1, layer2) != 0); - assertTrue(comparator.compare(layer2, layer1) != 0); + layer1.setHeight(1.2); - layer1 = getLayerOval(); - layer2 = getLayerOval(); + assertTrue(comparator.compare(layer1, layer2) != 0); + assertTrue(comparator.compare(layer2, layer1) != 0); - layer1.setX(33.4); + layer1 = getLayerOval(); + layer2 = getLayerOval(); - assertTrue(comparator.compare(layer1, layer2) != 0); - assertTrue(comparator.compare(layer2, layer1) != 0); + layer1.setX(33.4); - layer1 = getLayerOval(); - layer2 = getLayerOval(); + assertTrue(comparator.compare(layer1, layer2) != 0); + assertTrue(comparator.compare(layer2, layer1) != 0); - layer1.setY(33.4); + layer1 = getLayerOval(); + layer2 = getLayerOval(); - assertTrue(comparator.compare(layer1, layer2) != 0); - assertTrue(comparator.compare(layer2, layer1) != 0); + layer1.setY(33.4); - } catch (Exception e) { - e.printStackTrace(); - fail("Unknown exception"); - } + assertTrue(comparator.compare(layer1, layer2) != 0); + assertTrue(comparator.compare(layer2, layer1) != 0); } @Test public void testDifferentZIndex() { - try { - LayerOval layer1 = getLayerOval(); - LayerOval layer2 = getLayerOval(); - - layer1.setZ(12); + LayerOval layer1 = getLayerOval(); + LayerOval layer2 = getLayerOval(); - assertTrue(comparator.compare(layer1, layer2) != 0); - assertTrue(comparator.compare(layer2, layer1) != 0); + layer1.setZ(12); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertTrue(comparator.compare(layer1, layer2) != 0); + assertTrue(comparator.compare(layer2, layer1) != 0); } @Test public void testDifferent2() { - try { - LayerOval layer1 = getLayerOval(); - - assertTrue(comparator.compare(layer1, new LayerOval() { - private static final long serialVersionUID = 1L; - }) != 0); + LayerOval layer1 = getLayerOval(); - } catch (Exception e) { - e.printStackTrace(); - fail("Unknown exception"); - } + assertTrue(comparator.compare(layer1, Mockito.spy(LayerOval.class)) != 0); } - @Test + @Test(expected = NotImplementedException.class) public void testInvalid() { - try { - class Tmp extends LayerOval { - private static final long serialVersionUID = 1L; - } - Tmp layer1 = new Tmp(); - Tmp layer2 = new Tmp(); - - comparator.compare(layer1, layer2); - fail("Exception expected"); - - } catch (NotImplementedException e) { - } catch (Exception e) { - e.printStackTrace(); - fail("Unknown exception"); + class Tmp extends LayerOval { + private static final long serialVersionUID = 1L; } + Tmp layer1 = new Tmp(); + Tmp layer2 = new Tmp(); + + comparator.compare(layer1, layer2); } } diff --git a/model/src/test/java/lcsb/mapviewer/model/map/layout/graphics/LayerOvalTest.java b/model/src/test/java/lcsb/mapviewer/model/map/layout/graphics/LayerOvalTest.java index 8eb3193486a26e659dd425feb204d90ed8ed5222..971a65b5ba6461b48485bbe2db955eed1303f403 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/layout/graphics/LayerOvalTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/layout/graphics/LayerOvalTest.java @@ -1,22 +1,19 @@ package lcsb.mapviewer.model.map.layout.graphics; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import java.awt.Color; import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; +import org.mockito.Mockito; +import lcsb.mapviewer.ModelTestFunctions; import lcsb.mapviewer.common.Configuration; import lcsb.mapviewer.common.exception.InvalidArgumentException; import lcsb.mapviewer.common.exception.NotImplementedException; -public class LayerOvalTest { +public class LayerOvalTest extends ModelTestFunctions { @Before public void setUp() throws Exception { @@ -28,145 +25,114 @@ public class LayerOvalTest { @Test public void testSerialization() { - try { - SerializationUtils.serialize(createOval()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + SerializationUtils.serialize(createOval()); } @Test public void testConstructor1() { - try { - LayerOval layerOval = createOval(); + LayerOval layerOval = createOval(); - LayerOval copy = new LayerOval(layerOval); + LayerOval copy = new LayerOval(layerOval); - assertNotNull(copy); - assertEquals(0, new LayerOvalComparator().compare(layerOval, copy)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertNotNull(copy); + assertEquals(0, new LayerOvalComparator().compare(layerOval, copy)); } private LayerOval createOval() { - LayerOval result = new LayerOval(); + LayerOval result = new LayerOval(); result.setZ(14); return result; } @Test public void testCopy() { - try { - LayerOval copy = createOval().copy(); - - assertNotNull(copy); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + LayerOval copy = createOval().copy(); + + assertNotNull(copy); } - @Test + @Test(expected = NotImplementedException.class) public void testInvalidCopy() { - try { - new LayerOval() { - - /** - * - */ - private static final long serialVersionUID = 1L; - }.copy(); - - fail("Exception expected"); - } catch (NotImplementedException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Mockito.spy(LayerOval.class).copy(); + } + + @Test(expected = InvalidArgumentException.class) + public void testSetInvalidX() { + LayerOval oval = createOval(); + oval.setX("a1.6"); + } + + @Test(expected = InvalidArgumentException.class) + public void testSetInvalidY() { + LayerOval oval = createOval(); + oval.setY("a1.6"); + } + + @Test(expected = InvalidArgumentException.class) + public void testSetInvalidWidth() { + LayerOval oval = createOval(); + oval.setWidth("a1.6"); + } + + @Test(expected = InvalidArgumentException.class) + public void testSetInvalidHeight() { + LayerOval oval = createOval(); + oval.setHeight("a1.6"); } @Test public void testGetters() { - try { - LayerOval oval = createOval(); - - String yParam = "1.2"; - Double y = 1.2; - - String xParam = "2.2"; - Double x = 2.2; - - String widthParam = "10.2"; - Double width = 10.2; - - String heightParam = "72.2"; - Double height = 72.2; - - String invalidNumberStr = "xxd"; - - int id = 52; - Color color = Color.BLACK; - - oval.setY(yParam); - assertEquals(y, oval.getY(), Configuration.EPSILON); - try { - oval.setY(invalidNumberStr); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - } - oval.setY((Double) null); - assertNull(oval.getY()); - oval.setY(y); - assertEquals(y, oval.getY(), Configuration.EPSILON); - - oval.setX(xParam); - assertEquals(x, oval.getX(), Configuration.EPSILON); - try { - oval.setX(invalidNumberStr); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - } - oval.setX((Double) null); - assertNull(oval.getX()); - oval.setX(x); - assertEquals(x, oval.getX(), Configuration.EPSILON); - - oval.setWidth(widthParam); - assertEquals(width, oval.getWidth(), Configuration.EPSILON); - try { - oval.setWidth(invalidNumberStr); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - } - oval.setWidth((Double) null); - assertNull(oval.getWidth()); - oval.setWidth(width); - assertEquals(width, oval.getWidth(), Configuration.EPSILON); - - oval.setHeight(heightParam); - assertEquals(height, oval.getHeight(), Configuration.EPSILON); - try { - oval.setHeight(invalidNumberStr); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - } - oval.setHeight((Double) null); - assertNull(oval.getHeight()); - oval.setHeight(height); - assertEquals(height, oval.getHeight(), Configuration.EPSILON); - - oval.setId(id); - assertEquals(id, oval.getId()); - oval.setColor(color); - assertEquals(color, oval.getColor()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + LayerOval oval = createOval(); + + String yParam = "1.2"; + Double y = 1.2; + + String xParam = "2.2"; + Double x = 2.2; + + String widthParam = "10.2"; + Double width = 10.2; + + String heightParam = "72.2"; + Double height = 72.2; + + String invalidNumberStr = "xxd"; + + int id = 52; + Color color = Color.BLACK; + + oval.setY(yParam); + assertEquals(y, oval.getY(), Configuration.EPSILON); + oval.setY((Double) null); + assertNull(oval.getY()); + oval.setY(y); + assertEquals(y, oval.getY(), Configuration.EPSILON); + + oval.setX(xParam); + assertEquals(x, oval.getX(), Configuration.EPSILON); + oval.setX((Double) null); + assertNull(oval.getX()); + oval.setX(x); + assertEquals(x, oval.getX(), Configuration.EPSILON); + + oval.setWidth(widthParam); + assertEquals(width, oval.getWidth(), Configuration.EPSILON); + oval.setWidth((Double) null); + assertNull(oval.getWidth()); + oval.setWidth(width); + assertEquals(width, oval.getWidth(), Configuration.EPSILON); + + oval.setHeight(heightParam); + assertEquals(height, oval.getHeight(), Configuration.EPSILON); + oval.setHeight((Double) null); + assertNull(oval.getHeight()); + oval.setHeight(height); + assertEquals(height, oval.getHeight(), Configuration.EPSILON); + + oval.setId(id); + assertEquals(id, oval.getId()); + oval.setColor(color); + assertEquals(color, oval.getColor()); } } diff --git a/model/src/test/java/lcsb/mapviewer/model/map/layout/graphics/LayerRectComparatorTest.java b/model/src/test/java/lcsb/mapviewer/model/map/layout/graphics/LayerRectComparatorTest.java index 1e7d8685f34c26057bc83ea83cb062d39aa8a82b..5c3c1f6e846ebd11c2a0c67e221d226f060f9e1c 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/layout/graphics/LayerRectComparatorTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/layout/graphics/LayerRectComparatorTest.java @@ -1,18 +1,16 @@ package lcsb.mapviewer.model.map.layout.graphics; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import java.awt.Color; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; +import org.mockito.Mockito; +import lcsb.mapviewer.ModelTestFunctions; import lcsb.mapviewer.common.exception.NotImplementedException; -public class LayerRectComparatorTest { +public class LayerRectComparatorTest extends ModelTestFunctions { LayerRectComparator comparator = new LayerRectComparator(); @Before @@ -25,19 +23,13 @@ public class LayerRectComparatorTest { @Test public void testEquals() { - try { - LayerRect layer1 = getLayerRect(); - LayerRect layer2 = getLayerRect(); - - assertEquals(0, comparator.compare(new LayerRect(), new LayerRect())); - assertEquals(0, comparator.compare(layer1, layer2)); - assertEquals(0, comparator.compare(layer1, layer1)); - assertEquals(0, comparator.compare(null, null)); - - } catch (Exception e) { - e.printStackTrace(); - fail("Unknown exception"); - } + LayerRect layer1 = getLayerRect(); + LayerRect layer2 = getLayerRect(); + + assertEquals(0, comparator.compare(new LayerRect(), new LayerRect())); + assertEquals(0, comparator.compare(layer1, layer2)); + assertEquals(0, comparator.compare(layer1, layer1)); + assertEquals(0, comparator.compare(null, null)); } private LayerRect getLayerRect() { @@ -51,111 +43,82 @@ public class LayerRectComparatorTest { @Test public void testDifferent() { - try { - LayerRect layer1 = getLayerRect(); - LayerRect layer2 = getLayerRect(); - - assertTrue(comparator.compare(layer1, new LayerRect()) != 0); + LayerRect layer1 = getLayerRect(); + LayerRect layer2 = getLayerRect(); - assertTrue(comparator.compare(layer1, null) != 0); - assertTrue(comparator.compare(null, layer1) != 0); + assertTrue(comparator.compare(layer1, new LayerRect()) != 0); - layer1 = getLayerRect(); - layer2 = getLayerRect(); + assertTrue(comparator.compare(layer1, null) != 0); + assertTrue(comparator.compare(null, layer1) != 0); - layer1.setColor(Color.GREEN); + layer1 = getLayerRect(); + layer2 = getLayerRect(); - assertTrue(comparator.compare(layer1, layer2) != 0); - assertTrue(comparator.compare(layer2, layer1) != 0); + layer1.setColor(Color.GREEN); - layer1 = getLayerRect(); - layer2 = getLayerRect(); + assertTrue(comparator.compare(layer1, layer2) != 0); + assertTrue(comparator.compare(layer2, layer1) != 0); - layer1.setHeight("23"); + layer1 = getLayerRect(); + layer2 = getLayerRect(); - assertTrue(comparator.compare(layer1, layer2) != 0); - assertTrue(comparator.compare(layer2, layer1) != 0); + layer1.setHeight("23"); - layer1 = getLayerRect(); - layer2 = getLayerRect(); + assertTrue(comparator.compare(layer1, layer2) != 0); + assertTrue(comparator.compare(layer2, layer1) != 0); - layer1.setHeight(1.2); + layer1 = getLayerRect(); + layer2 = getLayerRect(); - assertTrue(comparator.compare(layer1, layer2) != 0); - assertTrue(comparator.compare(layer2, layer1) != 0); + layer1.setHeight(1.2); - layer1 = getLayerRect(); - layer2 = getLayerRect(); + assertTrue(comparator.compare(layer1, layer2) != 0); + assertTrue(comparator.compare(layer2, layer1) != 0); - layer1.setX(33.4); + layer1 = getLayerRect(); + layer2 = getLayerRect(); - assertTrue(comparator.compare(layer1, layer2) != 0); - assertTrue(comparator.compare(layer2, layer1) != 0); + layer1.setX(33.4); - layer1 = getLayerRect(); - layer2 = getLayerRect(); + assertTrue(comparator.compare(layer1, layer2) != 0); + assertTrue(comparator.compare(layer2, layer1) != 0); - layer1.setY(33.4); + layer1 = getLayerRect(); + layer2 = getLayerRect(); - assertTrue(comparator.compare(layer1, layer2) != 0); - assertTrue(comparator.compare(layer2, layer1) != 0); + layer1.setY(33.4); - } catch (Exception e) { - e.printStackTrace(); - fail("Unknown exception"); - } + assertTrue(comparator.compare(layer1, layer2) != 0); + assertTrue(comparator.compare(layer2, layer1) != 0); } @Test public void testDifferent2() { - try { - LayerRect layer1 = getLayerRect(); - - assertTrue(comparator.compare(layer1, new LayerRect() { - private static final long serialVersionUID = 1L; - }) != 0); + LayerRect layer1 = getLayerRect(); - } catch (Exception e) { - e.printStackTrace(); - fail("Unknown exception"); - } + assertTrue(comparator.compare(layer1, Mockito.spy(LayerRect.class)) != 0); } - @Test + @Test(expected = NotImplementedException.class) public void testInvalid() { - try { - class Tmp extends LayerRect { - private static final long serialVersionUID = 1L; - } - Tmp layer1 = new Tmp(); - Tmp layer2 = new Tmp(); - - comparator.compare(layer1, layer2); - fail("Exception expected"); - - } catch (NotImplementedException e) { - } catch (Exception e) { - e.printStackTrace(); - fail("Unknown exception"); + class Tmp extends LayerRect { + private static final long serialVersionUID = 1L; } + Tmp layer1 = new Tmp(); + Tmp layer2 = new Tmp(); + + comparator.compare(layer1, layer2); } @Test public void testDifferentZIndex() { - try { - LayerRect layer1 = getLayerRect(); - LayerRect layer2 = getLayerRect(); - - layer1.setZ(12); + LayerRect layer1 = getLayerRect(); + LayerRect layer2 = getLayerRect(); - assertTrue(comparator.compare(layer1, layer2) != 0); - assertTrue(comparator.compare(layer2, layer1) != 0); + layer1.setZ(12); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertTrue(comparator.compare(layer1, layer2) != 0); + assertTrue(comparator.compare(layer2, layer1) != 0); } - } diff --git a/model/src/test/java/lcsb/mapviewer/model/map/layout/graphics/LayerRectTest.java b/model/src/test/java/lcsb/mapviewer/model/map/layout/graphics/LayerRectTest.java index b11a8d351a1cbbf2862436bfbb138d88d5544284..d89cd63f29adab3cc06cbac3cc5bc404b1488d54 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/layout/graphics/LayerRectTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/layout/graphics/LayerRectTest.java @@ -1,22 +1,19 @@ package lcsb.mapviewer.model.map.layout.graphics; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import java.awt.Color; import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; +import org.mockito.Mockito; +import lcsb.mapviewer.ModelTestFunctions; import lcsb.mapviewer.common.Configuration; import lcsb.mapviewer.common.exception.InvalidArgumentException; import lcsb.mapviewer.common.exception.NotImplementedException; -public class LayerRectTest { +public class LayerRectTest extends ModelTestFunctions { @Before public void setUp() throws Exception { @@ -28,27 +25,17 @@ public class LayerRectTest { @Test public void testSerialization() { - try { - SerializationUtils.serialize(createRect()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + SerializationUtils.serialize(createRect()); } @Test public void testConstructor1() { - try { - LayerRect layerRect = createRect(); + LayerRect layerRect = createRect(); - LayerRect copy = new LayerRect(layerRect); + LayerRect copy = new LayerRect(layerRect); - assertNotNull(copy); - assertEquals(0, new LayerRectComparator().compare(layerRect, copy)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertNotNull(copy); + assertEquals(0, new LayerRectComparator().compare(layerRect, copy)); } private LayerRect createRect() { @@ -59,111 +46,88 @@ public class LayerRectTest { @Test public void testCopy() { - try { - LayerRect copy = createRect().copy(); - - assertNotNull(copy); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + LayerRect copy = createRect().copy(); + + assertNotNull(copy); } - @Test + @Test(expected = NotImplementedException.class) public void testInvalidCopy() { - try { - new LayerRect() { - - /** - * - */ - private static final long serialVersionUID = 1L; - }.copy(); - - fail("Exception expected"); - } catch (NotImplementedException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Mockito.spy(LayerRect.class).copy(); + } + + @Test(expected = InvalidArgumentException.class) + public void testSetInvalidX() { + LayerRect rect = createRect(); + rect.setX("a1.6"); + } + + @Test(expected = InvalidArgumentException.class) + public void testSetInvalidY() { + LayerRect rect = createRect(); + rect.setY("a1.6"); + } + + @Test(expected = InvalidArgumentException.class) + public void testSetInvalidWidth() { + LayerRect rect = createRect(); + rect.setWidth("a1.6"); + } + + @Test(expected = InvalidArgumentException.class) + public void testSetInvalidHeight() { + LayerRect rect = createRect(); + rect.setHeight("a1.6"); } @Test public void testGetters() { - try { - LayerRect rect = createRect(); - - String yParam = "1.2"; - Double y = 1.2; - - String xParam = "2.2"; - Double x = 2.2; - - String widthParam = "10.2"; - Double width = 10.2; - - String heightParam = "72.2"; - Double height = 72.2; - - String invalidNumberStr = "xxd"; - - Color color = Color.BLACK; - - rect.setY(yParam); - assertEquals(y, rect.getY(), Configuration.EPSILON); - try { - rect.setY(invalidNumberStr); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - } - rect.setY((Double) null); - assertNull(rect.getY()); - rect.setY(y); - assertEquals(y, rect.getY(), Configuration.EPSILON); - - rect.setX(xParam); - assertEquals(x, rect.getX(), Configuration.EPSILON); - try { - rect.setX(invalidNumberStr); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - } - rect.setX((Double) null); - assertNull(rect.getX()); - rect.setX(x); - assertEquals(x, rect.getX(), Configuration.EPSILON); - - rect.setWidth(widthParam); - assertEquals(width, rect.getWidth(), Configuration.EPSILON); - try { - rect.setWidth(invalidNumberStr); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - } - rect.setWidth((Double) null); - assertNull(rect.getWidth()); - rect.setWidth(width); - assertEquals(width, rect.getWidth(), Configuration.EPSILON); - - rect.setHeight(heightParam); - assertEquals(height, rect.getHeight(), Configuration.EPSILON); - try { - rect.setHeight(invalidNumberStr); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - } - rect.setHeight((Double) null); - assertNull(rect.getHeight()); - rect.setHeight(height); - assertEquals(height, rect.getHeight(), Configuration.EPSILON); - - rect.setColor(color); - assertEquals(color, rect.getColor()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + LayerRect rect = createRect(); + + String yParam = "1.2"; + Double y = 1.2; + + String xParam = "2.2"; + Double x = 2.2; + + String widthParam = "10.2"; + Double width = 10.2; + + String heightParam = "72.2"; + Double height = 72.2; + + Color color = Color.BLACK; + + rect.setY(yParam); + assertEquals(y, rect.getY(), Configuration.EPSILON); + rect.setY((Double) null); + assertNull(rect.getY()); + rect.setY(y); + assertEquals(y, rect.getY(), Configuration.EPSILON); + + rect.setX(xParam); + assertEquals(x, rect.getX(), Configuration.EPSILON); + rect.setX((Double) null); + assertNull(rect.getX()); + rect.setX(x); + assertEquals(x, rect.getX(), Configuration.EPSILON); + + rect.setWidth(widthParam); + assertEquals(width, rect.getWidth(), Configuration.EPSILON); + rect.setWidth((Double) null); + assertNull(rect.getWidth()); + rect.setWidth(width); + assertEquals(width, rect.getWidth(), Configuration.EPSILON); + + rect.setHeight(heightParam); + assertEquals(height, rect.getHeight(), Configuration.EPSILON); + rect.setHeight((Double) null); + assertNull(rect.getHeight()); + rect.setHeight(height); + assertEquals(height, rect.getHeight(), Configuration.EPSILON); + + rect.setColor(color); + assertEquals(color, rect.getColor()); } } diff --git a/model/src/test/java/lcsb/mapviewer/model/map/layout/graphics/LayerTest.java b/model/src/test/java/lcsb/mapviewer/model/map/layout/graphics/LayerTest.java index c1eb42b89af21f59c7ce92da6bf74ef77b93a020..609dae86bfb789fa18571a07ac15e71401fc2dd9 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/layout/graphics/LayerTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/layout/graphics/LayerTest.java @@ -1,158 +1,112 @@ package lcsb.mapviewer.model.map.layout.graphics; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import java.util.ArrayList; import java.util.List; import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; +import org.mockito.Mockito; +import lcsb.mapviewer.ModelTestFunctions; import lcsb.mapviewer.common.exception.NotImplementedException; import lcsb.mapviewer.model.graphics.PolylineData; import lcsb.mapviewer.model.map.model.ModelData; -public class LayerTest { - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testSerialization() { - try { - SerializationUtils.serialize(new Layer()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testConstructor() { - try { - Layer layer = new Layer(); - layer.addLayerText(new LayerText()); - layer.addLayerLine(new PolylineData()); - layer.addLayerRect(new LayerRect()); - layer.addLayerOval(new LayerOval()); - Layer copy = new Layer(layer); - - assertNotNull(copy); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testCopy() { - try { - Layer degraded = new Layer().copy(); - assertNotNull(degraded); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testSetters() { - try { - Layer layer = new Layer().copy(); - - ModelData model = new ModelData(); - List<LayerOval> ovals = new ArrayList<>(); - List<LayerRect> rectangles = new ArrayList<>(); - List<PolylineData> lines = new ArrayList<>(); - List<LayerText> texts= new ArrayList<>(); - - boolean locked = true; - boolean visible = true; - String name = "sdtr"; - String layerId = "id"; - - layer.setModel(model); - layer.setOvals(ovals); - layer.setTexts(texts); - layer.setRectangles(rectangles); - layer.setLines(lines); - layer.setLocked(locked); - layer.setVisible(visible); - layer.setName(name); - layer.setLayerId(layerId); - - assertEquals(model, layer.getModel()); - assertEquals(ovals, layer.getOvals()); - assertEquals(rectangles, layer.getRectangles()); - assertEquals(lines, layer.getLines()); - assertEquals(texts, layer.getTexts()); - assertEquals(locked, layer.isLocked()); - assertEquals(name, layer.getName()); - assertEquals(visible, layer.isVisible()); - assertEquals(layerId, layer.getLayerId()); - - layer.setLocked("FALSE"); - layer.setVisible("FALSE"); - - assertFalse(layer.isLocked()); - assertFalse(layer.isVisible()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testInvalidCopy() { - try { - new Layer() { - - /** - * - */ - private static final long serialVersionUID = 1L; - }.copy(); - fail("Exception expected"); - } catch (NotImplementedException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testRemoveLayerText() { - try { - Layer layer = new Layer(); - layer.removeLayerText(new LayerText()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testAddLines() { - try { - Layer layer = new Layer(); - List<PolylineData> lines = new ArrayList<>(); - lines.add(new PolylineData()); - layer.addLayerLines(lines); - assertEquals(1, layer.getLines().size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } +public class LayerTest extends ModelTestFunctions { + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testSerialization() { + SerializationUtils.serialize(new Layer()); + } + + @Test + public void testConstructor() { + Layer layer = new Layer(); + layer.addLayerText(new LayerText()); + layer.addLayerLine(new PolylineData()); + layer.addLayerRect(new LayerRect()); + layer.addLayerOval(new LayerOval()); + Layer copy = new Layer(layer); + + assertNotNull(copy); + } + + @Test + public void testCopy() { + Layer degraded = new Layer().copy(); + assertNotNull(degraded); + } + + @Test + public void testSetters() { + Layer layer = new Layer().copy(); + + ModelData model = new ModelData(); + List<LayerOval> ovals = new ArrayList<>(); + List<LayerRect> rectangles = new ArrayList<>(); + List<PolylineData> lines = new ArrayList<>(); + List<LayerText> texts = new ArrayList<>(); + + boolean locked = true; + boolean visible = true; + String name = "sdtr"; + String layerId = "id"; + + layer.setModel(model); + layer.setOvals(ovals); + layer.setTexts(texts); + layer.setRectangles(rectangles); + layer.setLines(lines); + layer.setLocked(locked); + layer.setVisible(visible); + layer.setName(name); + layer.setLayerId(layerId); + + assertEquals(model, layer.getModel()); + assertEquals(ovals, layer.getOvals()); + assertEquals(rectangles, layer.getRectangles()); + assertEquals(lines, layer.getLines()); + assertEquals(texts, layer.getTexts()); + assertEquals(locked, layer.isLocked()); + assertEquals(name, layer.getName()); + assertEquals(visible, layer.isVisible()); + assertEquals(layerId, layer.getLayerId()); + + layer.setLocked("FALSE"); + layer.setVisible("FALSE"); + + assertFalse(layer.isLocked()); + assertFalse(layer.isVisible()); + } + + @Test(expected = NotImplementedException.class) + public void testInvalidCopy() { + Mockito.spy(Layer.class).copy(); + } + + @Test + public void testRemoveLayerText() { + Layer layer = new Layer(); + layer.removeLayerText(new LayerText()); + } + + @Test + public void testAddLines() { + Layer layer = new Layer(); + List<PolylineData> lines = new ArrayList<>(); + lines.add(new PolylineData()); + layer.addLayerLines(lines); + assertEquals(1, layer.getLines().size()); + } } diff --git a/model/src/test/java/lcsb/mapviewer/model/map/layout/graphics/LayerTextComparatorTest.java b/model/src/test/java/lcsb/mapviewer/model/map/layout/graphics/LayerTextComparatorTest.java index 71047387d9329ea490ac0f4850d4161e8dd7630f..6d0233362e1d03c805d2fa40701fa702f81aa213 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/layout/graphics/LayerTextComparatorTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/layout/graphics/LayerTextComparatorTest.java @@ -1,18 +1,16 @@ package lcsb.mapviewer.model.map.layout.graphics; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import java.awt.Color; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; +import org.mockito.Mockito; +import lcsb.mapviewer.ModelTestFunctions; import lcsb.mapviewer.common.exception.NotImplementedException; -public class LayerTextComparatorTest { +public class LayerTextComparatorTest extends ModelTestFunctions { LayerTextComparator comparator = new LayerTextComparator(); @Before @@ -25,53 +23,31 @@ public class LayerTextComparatorTest { @Test public void testEquals() { - try { - LayerText layer1 = getLayerText(); - LayerText layer2 = getLayerText(); - - assertEquals(0, comparator.compare(new LayerText(), new LayerText())); - assertEquals(0, comparator.compare(layer1, layer2)); - assertEquals(0, comparator.compare(layer1, layer1)); - assertEquals(0, comparator.compare(null, null)); - - } catch (Exception e) { - e.printStackTrace(); - fail("Unknown exception"); - } + LayerText layer1 = getLayerText(); + LayerText layer2 = getLayerText(); + + assertEquals(0, comparator.compare(new LayerText(), new LayerText())); + assertEquals(0, comparator.compare(layer1, layer2)); + assertEquals(0, comparator.compare(layer1, layer1)); + assertEquals(0, comparator.compare(null, null)); } @Test public void testDifferent2() { - try { - LayerText layer1 = getLayerText(); - - assertTrue(comparator.compare(layer1, new LayerText() { - private static final long serialVersionUID = 1L; - }) != 0); + LayerText layer1 = getLayerText(); - } catch (Exception e) { - e.printStackTrace(); - fail("Unknown exception"); - } + assertTrue(comparator.compare(layer1, Mockito.spy(LayerText.class)) != 0); } - @Test + @Test(expected = NotImplementedException.class) public void testInvalid() { - try { - class Tmp extends LayerText { - private static final long serialVersionUID = 1L; - } - Tmp layer1 = new Tmp(); - Tmp layer2 = new Tmp(); - - comparator.compare(layer1, layer2); - - fail("Exception expected"); - } catch (NotImplementedException e) { - } catch (Exception e) { - e.printStackTrace(); - fail("Unknown exception"); + class Tmp extends LayerText { + private static final long serialVersionUID = 1L; } + Tmp layer1 = new Tmp(); + Tmp layer2 = new Tmp(); + + comparator.compare(layer1, layer2); } private LayerText getLayerText() { @@ -86,84 +62,72 @@ public class LayerTextComparatorTest { @Test public void testDifferent() { - try { - LayerText layer1 = getLayerText(); - LayerText layer2 = getLayerText(); - - assertTrue(comparator.compare(layer1, new LayerText()) != 0); + LayerText layer1 = getLayerText(); + LayerText layer2 = getLayerText(); - assertTrue(comparator.compare(layer1, null) != 0); - assertTrue(comparator.compare(null, layer1) != 0); + assertTrue(comparator.compare(layer1, new LayerText()) != 0); - layer1 = getLayerText(); - layer2 = getLayerText(); + assertTrue(comparator.compare(layer1, null) != 0); + assertTrue(comparator.compare(null, layer1) != 0); - layer1.setColor(Color.GREEN); + layer1 = getLayerText(); + layer2 = getLayerText(); - assertTrue(comparator.compare(layer1, layer2) != 0); - assertTrue(comparator.compare(layer2, layer1) != 0); + layer1.setColor(Color.GREEN); - layer1 = getLayerText(); - layer2 = getLayerText(); + assertTrue(comparator.compare(layer1, layer2) != 0); + assertTrue(comparator.compare(layer2, layer1) != 0); - layer1.setNotes("asd"); + layer1 = getLayerText(); + layer2 = getLayerText(); - assertTrue(comparator.compare(layer1, layer2) != 0); - assertTrue(comparator.compare(layer2, layer1) != 0); + layer1.setNotes("asd"); - layer1 = getLayerText(); - layer2 = getLayerText(); + assertTrue(comparator.compare(layer1, layer2) != 0); + assertTrue(comparator.compare(layer2, layer1) != 0); - layer1.setHeight(1.2); + layer1 = getLayerText(); + layer2 = getLayerText(); - assertTrue(comparator.compare(layer1, layer2) != 0); - assertTrue(comparator.compare(layer2, layer1) != 0); + layer1.setHeight(1.2); - layer1 = getLayerText(); - layer2 = getLayerText(); + assertTrue(comparator.compare(layer1, layer2) != 0); + assertTrue(comparator.compare(layer2, layer1) != 0); - layer1.setX(33.4); + layer1 = getLayerText(); + layer2 = getLayerText(); - assertTrue(comparator.compare(layer1, layer2) != 0); - assertTrue(comparator.compare(layer2, layer1) != 0); + layer1.setX(33.4); - layer1 = getLayerText(); - layer2 = getLayerText(); + assertTrue(comparator.compare(layer1, layer2) != 0); + assertTrue(comparator.compare(layer2, layer1) != 0); - layer1.setY(33.4); + layer1 = getLayerText(); + layer2 = getLayerText(); - assertTrue(comparator.compare(layer1, layer2) != 0); - assertTrue(comparator.compare(layer2, layer1) != 0); + layer1.setY(33.4); - layer1 = getLayerText(); - layer2 = getLayerText(); + assertTrue(comparator.compare(layer1, layer2) != 0); + assertTrue(comparator.compare(layer2, layer1) != 0); - layer1.setFontSize(64.1); + layer1 = getLayerText(); + layer2 = getLayerText(); - assertTrue(comparator.compare(layer1, layer2) != 0); - assertTrue(comparator.compare(layer2, layer1) != 0); + layer1.setFontSize(64.1); - } catch (Exception e) { - e.printStackTrace(); - fail("Unknown exception"); - } + assertTrue(comparator.compare(layer1, layer2) != 0); + assertTrue(comparator.compare(layer2, layer1) != 0); } @Test public void testDifferentZIndex() { - try { - LayerText layer1 = getLayerText(); - LayerText layer2 = getLayerText(); + LayerText layer1 = getLayerText(); + LayerText layer2 = getLayerText(); - layer1.setZ(12); + layer1.setZ(12); - assertTrue(comparator.compare(layer1, layer2) != 0); - assertTrue(comparator.compare(layer2, layer1) != 0); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertTrue(comparator.compare(layer1, layer2) != 0); + assertTrue(comparator.compare(layer2, layer1) != 0); } } diff --git a/model/src/test/java/lcsb/mapviewer/model/map/layout/graphics/LayerTextTest.java b/model/src/test/java/lcsb/mapviewer/model/map/layout/graphics/LayerTextTest.java index 3dc6b454cb67a34e1a0f75a0eef1674a6956b0c8..dd50ebc9e8037e1b50d68cd1aec54dafe6c4c2dd 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/layout/graphics/LayerTextTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/layout/graphics/LayerTextTest.java @@ -1,22 +1,19 @@ package lcsb.mapviewer.model.map.layout.graphics; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import java.awt.geom.Rectangle2D; import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; +import org.mockito.Mockito; +import lcsb.mapviewer.ModelTestFunctions; import lcsb.mapviewer.common.Configuration; import lcsb.mapviewer.common.exception.InvalidArgumentException; import lcsb.mapviewer.common.exception.NotImplementedException; -public class LayerTextTest { +public class LayerTextTest extends ModelTestFunctions { @Before public void setUp() throws Exception { @@ -28,27 +25,17 @@ public class LayerTextTest { @Test public void testSerialization() { - try { - SerializationUtils.serialize(createText()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + SerializationUtils.serialize(createText()); } @Test public void testConstructor1() { - try { - LayerText layerText = createText(); + LayerText layerText = createText(); - LayerText copy = new LayerText(layerText); + LayerText copy = new LayerText(layerText); - assertNotNull(copy); - assertEquals(0, new LayerTextComparator().compare(layerText, copy)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertNotNull(copy); + assertEquals(0, new LayerTextComparator().compare(layerText, copy)); } private LayerText createText() { @@ -59,145 +46,114 @@ public class LayerTextTest { @Test public void testConstructor2() { - try { + LayerText copy = new LayerText(new Rectangle2D.Double(), "text"); - LayerText copy = new LayerText(new Rectangle2D.Double(), "text"); - - assertNotNull(copy); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertNotNull(copy); } @Test public void testCopy() { - try { - LayerText copy = createText().copy(); - - assertNotNull(copy); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + LayerText copy = createText().copy(); + + assertNotNull(copy); } - @Test + @Test(expected = NotImplementedException.class) public void testInvalidCopy() { - try { - new LayerText() { - - /** - * - */ - private static final long serialVersionUID = 1L; - }.copy(); - - fail("Exception expected"); - } catch (NotImplementedException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Mockito.spy(LayerText.class).copy(); } @Test public void testGetBorder() { - try { - LayerText copy = createText().copy(); - assertNotNull(copy.getBorder()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + LayerText copy = createText().copy(); + assertNotNull(copy.getBorder()); + } + + @Test(expected = InvalidArgumentException.class) + public void testSetInvalidX() { + LayerText text = createText(); + text.setX("a1.6"); + } + + @Test(expected = InvalidArgumentException.class) + public void testSetInvalidY() { + LayerText text = createText(); + text.setY("a1.6"); + } + + @Test(expected = InvalidArgumentException.class) + public void testSetInvalidWidth() { + LayerText text = createText(); + text.setWidth("a1.6"); + } + + @Test(expected = InvalidArgumentException.class) + public void testSetInvalidHeight() { + LayerText text = createText(); + text.setHeight("a1.6"); + } + + @Test(expected = InvalidArgumentException.class) + public void testSetInvalidFontSize() { + LayerText text = createText(); + text.setFontSize("a1.6"); } @Test public void testGetters() { - try { - LayerText text = createText(); - - String yParam = "1.2"; - Double y = 1.2; - - String xParam = "2.2"; - Double x = 2.2; - - String widthParam = "10.2"; - Double width = 10.2; - - String heightParam = "72.2"; - Double height = 72.2; - - String fontSizeParam = "5.0"; - Double fontSize = 5.0; - - String invalidNumberStr = "xxd"; - - text.setY(yParam); - assertEquals(y, text.getY(), Configuration.EPSILON); - try { - text.setY(invalidNumberStr); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - } - assertEquals(y, text.getY(), Configuration.EPSILON); - text.setY((Double) null); - assertNull(text.getY()); - text.setY(y); - assertEquals(y, text.getY(), Configuration.EPSILON); - - text.setX(xParam); - assertEquals(x, text.getX(), Configuration.EPSILON); - try { - text.setX(invalidNumberStr); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - } - text.setX((Double) null); - assertNull(text.getX()); - text.setX(x); - assertEquals(x, text.getX(), Configuration.EPSILON); - - text.setFontSize(fontSizeParam); - assertEquals(fontSize, text.getFontSize(), Configuration.EPSILON); - try { - text.setFontSize(invalidNumberStr); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - } - text.setFontSize((Double) null); - assertNull(text.getFontSize()); - text.setFontSize(fontSize); - assertEquals(fontSize, text.getFontSize(), Configuration.EPSILON); - - text.setWidth(widthParam); - assertEquals(width, text.getWidth(), Configuration.EPSILON); - try { - text.setWidth(invalidNumberStr); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - } - text.setWidth((Double) null); - assertNull(text.getWidth()); - text.setWidth(width); - assertEquals(width, text.getWidth(), Configuration.EPSILON); - - text.setHeight(heightParam); - assertEquals(height, text.getHeight(), Configuration.EPSILON); - try { - text.setHeight(invalidNumberStr); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - } - text.setHeight((Double) null); - assertNull(text.getHeight()); - text.setHeight(height); - assertEquals(height, text.getHeight(), Configuration.EPSILON); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + LayerText text = createText(); + + String yParam = "1.2"; + Double y = 1.2; + + String xParam = "2.2"; + Double x = 2.2; + + String widthParam = "10.2"; + Double width = 10.2; + + String heightParam = "72.2"; + Double height = 72.2; + + String fontSizeParam = "5.0"; + Double fontSize = 5.0; + + String invalidNumberStr = "xxd"; + + text.setY(yParam); + assertEquals(y, text.getY(), Configuration.EPSILON); + assertEquals(y, text.getY(), Configuration.EPSILON); + text.setY((Double) null); + assertNull(text.getY()); + text.setY(y); + assertEquals(y, text.getY(), Configuration.EPSILON); + + text.setX(xParam); + assertEquals(x, text.getX(), Configuration.EPSILON); + text.setX((Double) null); + assertNull(text.getX()); + text.setX(x); + assertEquals(x, text.getX(), Configuration.EPSILON); + + text.setFontSize(fontSizeParam); + assertEquals(fontSize, text.getFontSize(), Configuration.EPSILON); + text.setFontSize((Double) null); + assertNull(text.getFontSize()); + text.setFontSize(fontSize); + assertEquals(fontSize, text.getFontSize(), Configuration.EPSILON); + + text.setWidth(widthParam); + assertEquals(width, text.getWidth(), Configuration.EPSILON); + text.setWidth((Double) null); + assertNull(text.getWidth()); + text.setWidth(width); + assertEquals(width, text.getWidth(), Configuration.EPSILON); + + text.setHeight(heightParam); + assertEquals(height, text.getHeight(), Configuration.EPSILON); + text.setHeight((Double) null); + assertNull(text.getHeight()); + text.setHeight(height); + assertEquals(height, text.getHeight(), Configuration.EPSILON); } } diff --git a/model/src/test/java/lcsb/mapviewer/model/map/model/ElementSubmodelConnectionComparatorTest.java b/model/src/test/java/lcsb/mapviewer/model/map/model/ElementSubmodelConnectionComparatorTest.java index 8207eade06a8f599241382dccd095f2e47b8aad6..cd76b150b569b92d801c70307e4c4668bc47c6f2 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/model/ElementSubmodelConnectionComparatorTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/model/ElementSubmodelConnectionComparatorTest.java @@ -1,129 +1,114 @@ package lcsb.mapviewer.model.map.model; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.Assert.*; import java.awt.Color; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; +import org.mockito.Mockito; +import lcsb.mapviewer.ModelTestFunctions; import lcsb.mapviewer.model.map.compartment.Compartment; import lcsb.mapviewer.model.map.layout.graphics.Layer; import lcsb.mapviewer.model.map.reaction.Reaction; import lcsb.mapviewer.model.map.species.Element; import lcsb.mapviewer.model.map.species.GenericProtein; -public class ElementSubmodelConnectionComparatorTest { +public class ElementSubmodelConnectionComparatorTest extends ModelTestFunctions { - ElementSubmodelConnectionComparator comparator = new ElementSubmodelConnectionComparator(); + ElementSubmodelConnectionComparator comparator = new ElementSubmodelConnectionComparator(); - @Before - public void setUp() throws Exception { - } + @Before + public void setUp() throws Exception { + } - @After - public void tearDown() throws Exception { - } + @After + public void tearDown() throws Exception { + } - @Test - public void testEquals() throws Exception { - try { - ElementSubmodelConnection connectionA = createConnection(); - ElementSubmodelConnection connectionB = createConnection(); + @Test + public void testEquals() throws Exception { + ElementSubmodelConnection connectionA = createConnection(); + ElementSubmodelConnection connectionB = createConnection(); - assertEquals(0, comparator.compare(new ElementSubmodelConnection(), new ElementSubmodelConnection())); - assertEquals(0, comparator.compare(connectionA, connectionB)); - assertEquals(0, comparator.compare(connectionA, connectionA)); - assertEquals(0, comparator.compare(null, null)); + assertEquals(0, comparator.compare(new ElementSubmodelConnection(), new ElementSubmodelConnection())); + assertEquals(0, comparator.compare(connectionA, connectionB)); + assertEquals(0, comparator.compare(connectionA, connectionA)); + assertEquals(0, comparator.compare(null, null)); + } - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } + @Test + public void testDifferent() throws Exception { + ElementSubmodelConnection connectionA = createConnection(); + ElementSubmodelConnection connectionB = createConnection(); - @Test - public void testDifferent() throws Exception { - try { - ElementSubmodelConnection connectionA = createConnection(); - ElementSubmodelConnection connectionB = createConnection(); + assertTrue(comparator.compare(null, connectionB) != 0); + assertTrue(comparator.compare(connectionA, null) != 0); - assertTrue(comparator.compare(null, connectionB) != 0); - assertTrue(comparator.compare(connectionA, null) != 0); + connectionA.setFromElement(null); + assertTrue(comparator.compare(connectionA, connectionB) != 0); + assertTrue(comparator.compare(connectionB, connectionA) != 0); - connectionA.setFromElement(null); - assertTrue(comparator.compare(connectionA, connectionB) != 0); - assertTrue(comparator.compare(connectionB, connectionA) != 0); + connectionA = createConnection(); + connectionB = createConnection(); - connectionA = createConnection(); - connectionB = createConnection(); + connectionA.getFromElement().setWidth(1234567); - connectionA.getFromElement().setWidth(1234567); + assertTrue(comparator.compare(connectionA, connectionB) != 0); + assertTrue(comparator.compare(connectionB, connectionA) != 0); - assertTrue(comparator.compare(connectionA, connectionB) != 0); - assertTrue(comparator.compare(connectionB, connectionA) != 0); + connectionA = createConnection(); + connectionB = createConnection(); - connectionA = createConnection(); - connectionB = createConnection(); + connectionA.setToElement(null); + assertTrue(comparator.compare(connectionA, connectionB) != 0); + assertTrue(comparator.compare(connectionB, connectionA) != 0); - connectionA.setToElement(null); - assertTrue(comparator.compare(connectionA, connectionB) != 0); - assertTrue(comparator.compare(connectionB, connectionA) != 0); + connectionA = createConnection(); + connectionB = createConnection(); - connectionA = createConnection(); - connectionB = createConnection(); + connectionA.getToElement().setWidth(1234567); - connectionA.getToElement().setWidth(1234567); + assertTrue(comparator.compare(connectionA, connectionB) != 0); + assertTrue(comparator.compare(connectionB, connectionA) != 0); - assertTrue(comparator.compare(connectionA, connectionB) != 0); - assertTrue(comparator.compare(connectionB, connectionA) != 0); + assertTrue(comparator.compare(connectionB, Mockito.spy(ElementSubmodelConnection.class)) != 0); + } - assertTrue(comparator.compare(connectionB, new ElementSubmodelConnection() { - private static final long serialVersionUID = 1L; - }) != 0); + private Model getModel() { + Model model = new ModelFullIndexed(null); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } + model.setNotes("Some description"); + GenericProtein protein = new GenericProtein("A"); + protein.setName("ad"); + model.addElement(protein); - private Model getModel() { - Model model = new ModelFullIndexed(null); + GenericProtein protein2 = new GenericProtein("a_id"); + protein2.setName("ad"); + model.addElement(protein2); - model.setNotes("Some description"); - GenericProtein protein = new GenericProtein("A"); - protein.setName("ad"); - model.addElement(protein); + model.addElement(new Compartment("default")); - GenericProtein protein2 = new GenericProtein("a_id"); - protein2.setName("ad"); - model.addElement(protein2); + Layer layer = new Layer(); + layer.setName("layer name"); + model.addLayer(layer); - model.addElement(new Compartment("default")); + model.addReaction(new Reaction()); + return model; + } - Layer layer = new Layer(); - layer.setName("layer name"); - model.addLayer(layer); + private ElementSubmodelConnection createConnection() { + ElementSubmodelConnection result = new ElementSubmodelConnection(getModel(), SubmodelType.DOWNSTREAM_TARGETS); + result.setName("name A"); + result.setFromElement(createElement()); + result.setToElement(createElement()); + return result; + } - model.addReaction(new Reaction()); - return model; - } - - private ElementSubmodelConnection createConnection() { - ElementSubmodelConnection result = new ElementSubmodelConnection(getModel(), SubmodelType.DOWNSTREAM_TARGETS); - result.setName("name A"); - result.setFromElement(createElement()); - result.setToElement(createElement()); - return result; - } - - private Element createElement() { - Element protein = new GenericProtein("protein_id"); - protein.setColor(Color.BLACK); - return protein; - } + private Element createElement() { + Element protein = new GenericProtein("protein_id"); + protein.setColor(Color.BLACK); + return protein; + } } diff --git a/model/src/test/java/lcsb/mapviewer/model/map/model/ElementSubmodelConnectionTest.java b/model/src/test/java/lcsb/mapviewer/model/map/model/ElementSubmodelConnectionTest.java index ee58dfbe8d7617e034ac8d63f78c0e2d269c6a74..da061855ec7770512a8e55e08dbd7294db506dd4 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/model/ElementSubmodelConnectionTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/model/ElementSubmodelConnectionTest.java @@ -1,94 +1,59 @@ package lcsb.mapviewer.model.map.model; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; +import org.mockito.Mockito; +import lcsb.mapviewer.ModelTestFunctions; import lcsb.mapviewer.common.exception.NotImplementedException; - -public class ElementSubmodelConnectionTest { - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testSerialization() { - try { - SerializationUtils.serialize(new ElementSubmodelConnection()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testConstructor() { - try { - ElementSubmodelConnection connection = new ElementSubmodelConnection(new ModelData(), SubmodelType.DOWNSTREAM_TARGETS); - assertNotNull(connection); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testConstructor2() { - try { - ElementSubmodelConnection connection = new ElementSubmodelConnection(new ElementSubmodelConnection(new ModelData(), SubmodelType.DOWNSTREAM_TARGETS)); - assertNotNull(connection); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testConstructor3() { - try { - ElementSubmodelConnection connection = new ElementSubmodelConnection(new ModelFullIndexed(null), SubmodelType.DOWNSTREAM_TARGETS, "sd"); - assertNotNull(connection); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testCopy() { - try { - ElementSubmodelConnection connection = new ElementSubmodelConnection().copy(); - assertNotNull(connection); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testInvalidCopy() { - try { - new ElementSubmodelConnection() { - - /** - * - */ - private static final long serialVersionUID = 1L; - }.copy(); - fail("Exception expected"); - } catch (NotImplementedException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } +import lcsb.mapviewer.model.map.layout.graphics.Layer; + +public class ElementSubmodelConnectionTest extends ModelTestFunctions { + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testSerialization() { + SerializationUtils.serialize(new ElementSubmodelConnection()); + } + + @Test + public void testConstructor() { + ElementSubmodelConnection connection = new ElementSubmodelConnection(new ModelData(), + SubmodelType.DOWNSTREAM_TARGETS); + assertNotNull(connection); + } + + @Test + public void testConstructor2() { + ElementSubmodelConnection connection = new ElementSubmodelConnection( + new ElementSubmodelConnection(new ModelData(), SubmodelType.DOWNSTREAM_TARGETS)); + assertNotNull(connection); + } + + @Test + public void testConstructor3() { + ElementSubmodelConnection connection = new ElementSubmodelConnection(new ModelFullIndexed(null), + SubmodelType.DOWNSTREAM_TARGETS, "sd"); + assertNotNull(connection); + } + + @Test + public void testCopy() { + ElementSubmodelConnection connection = new ElementSubmodelConnection().copy(); + assertNotNull(connection); + } + + @Test(expected = NotImplementedException.class) + public void testInvalidCopy() { + Mockito.spy(ElementSubmodelConnection.class).copy(); + } } diff --git a/model/src/test/java/lcsb/mapviewer/model/map/model/ModelComparatorTest.java b/model/src/test/java/lcsb/mapviewer/model/map/model/ModelComparatorTest.java index 3a2cb1c4c4b0583bf0bf7f23b6c3dd20a27007a5..5c201cd3aa4282470322d59ac1ee1dd97083c089 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/model/ModelComparatorTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/model/ModelComparatorTest.java @@ -1,22 +1,18 @@ package lcsb.mapviewer.model.map.model; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; -import static org.mockito.Mockito.when; +import static org.junit.Assert.*; +import static org.mockito.Mockito.*; import java.util.Calendar; -import org.apache.logging.log4j.*; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.junit.*; import org.mockito.Mockito; +import lcsb.mapviewer.ModelTestFunctions; import lcsb.mapviewer.common.exception.NotImplementedException; -import lcsb.mapviewer.model.map.MiriamData; -import lcsb.mapviewer.model.map.MiriamRelationType; -import lcsb.mapviewer.model.map.MiriamType; +import lcsb.mapviewer.model.map.*; import lcsb.mapviewer.model.map.compartment.Compartment; import lcsb.mapviewer.model.map.compartment.PathwayCompartment; import lcsb.mapviewer.model.map.layout.graphics.Layer; @@ -25,7 +21,7 @@ import lcsb.mapviewer.model.map.reaction.type.TransportReaction; import lcsb.mapviewer.model.map.species.GenericProtein; import lcsb.mapviewer.model.map.species.Species; -public class ModelComparatorTest { +public class ModelComparatorTest extends ModelTestFunctions { Logger logger = LogManager.getLogger(ModelComparatorTest.class); ModelComparator comparator = new ModelComparator(); @@ -40,281 +36,228 @@ public class ModelComparatorTest { @Test public void testEquals() { - try { - Model model1 = getModel(); - Model model2 = getModel(); - - assertEquals(0, comparator.compare(new ModelFullIndexed(null), new ModelFullIndexed(null))); - assertEquals(0, comparator.compare(model1, model2)); - assertEquals(0, comparator.compare(model1, model1)); - assertEquals(0, comparator.compare(null, null)); - - } catch (Exception e) { - e.printStackTrace(); - fail("Unknown exception"); - } + Model model1 = getModel(); + Model model2 = getModel(); + + assertEquals(0, comparator.compare(new ModelFullIndexed(null), new ModelFullIndexed(null))); + assertEquals(0, comparator.compare(model1, model2)); + assertEquals(0, comparator.compare(model1, model1)); + assertEquals(0, comparator.compare(null, null)); } @Test public void testDifferent2() { - try { - Model model1 = getModel(); - Model model2 = Mockito.mock(Model.class); - - assertTrue(comparator.compare(model1, model2) != 0); + Model model1 = getModel(); + Model model2 = Mockito.mock(Model.class); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertTrue(comparator.compare(model1, model2) != 0); } @Test public void testDifferent3() { - try { - Model model1 = getModel(); - Model model2 = getModel(); - - Compartment compartment = new PathwayCompartment("1"); - Compartment compartment2 = new PathwayCompartment("12"); - model1.addElement(compartment); - model1.addElement(compartment2); - - compartment = new PathwayCompartment("1"); - compartment2 = new PathwayCompartment("12"); - model2.addElement(compartment); - model2.addElement(compartment2); - compartment2.setElementId("1"); - - assertTrue(comparator.compare(model1, model2) != 0); - assertTrue(comparator.compare(model2, model1) != 0); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Model model1 = getModel(); + Model model2 = getModel(); + + Compartment compartment = new PathwayCompartment("1"); + Compartment compartment2 = new PathwayCompartment("12"); + model1.addElement(compartment); + model1.addElement(compartment2); + + compartment = new PathwayCompartment("1"); + compartment2 = new PathwayCompartment("12"); + model2.addElement(compartment); + model2.addElement(compartment2); + compartment2.setElementId("1"); + + assertTrue(comparator.compare(model1, model2) != 0); + assertTrue(comparator.compare(model2, model1) != 0); } @Test public void testDifferentReactionsInReactionSet() { - try { - Model model1 = getModel(); - Model model2 = getModel(); - - Reaction reaction1 = new Reaction(); - Reaction reaction2 = new Reaction(); - Reaction reaction3 = new Reaction(); - Reaction reaction4 = new Reaction(); - reaction1.setIdReaction("a"); - reaction2.setIdReaction("b"); - reaction3.setIdReaction("a"); - reaction4.setIdReaction("b"); - - model1.addReaction(reaction1); - model1.addReaction(reaction2); - model2.addReaction(reaction3); - model2.addReaction(reaction4); - - reaction2.setIdReaction("a"); - - assertTrue(comparator.compare(model1, model2) != 0); - assertTrue(comparator.compare(model2, model1) != 0); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Model model1 = getModel(); + Model model2 = getModel(); + + Reaction reaction1 = new Reaction(); + Reaction reaction2 = new Reaction(); + Reaction reaction3 = new Reaction(); + Reaction reaction4 = new Reaction(); + reaction1.setIdReaction("a"); + reaction2.setIdReaction("b"); + reaction3.setIdReaction("a"); + reaction4.setIdReaction("b"); + + model1.addReaction(reaction1); + model1.addReaction(reaction2); + model2.addReaction(reaction3); + model2.addReaction(reaction4); + + reaction2.setIdReaction("a"); + + assertTrue(comparator.compare(model1, model2) != 0); + assertTrue(comparator.compare(model2, model1) != 0); } @Test public void testDifferentReactionSet() { - try { - Model model1 = getModel(); - Model model2 = getModel(); - - model1.addReaction(new TransportReaction("id")); + Model model1 = getModel(); + Model model2 = getModel(); - assertTrue(comparator.compare(model1, model2) != 0); - assertTrue(comparator.compare(model2, model1) != 0); + model1.addReaction(new TransportReaction("id")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertTrue(comparator.compare(model1, model2) != 0); + assertTrue(comparator.compare(model2, model1) != 0); } - @Test + @Test(expected = NotImplementedException.class) public void testInvalid() { - try { - Model model1 = getModel(); - Model model2 = getModel(); - - Species mockSpecies = Mockito.mock(Species.class); - when(mockSpecies.getElementId()).thenReturn("1"); - model1.addElement(mockSpecies); + Model model1 = getModel(); + Model model2 = getModel(); - model2.addElement(mockSpecies); + Species mockSpecies = Mockito.mock(Species.class); + when(mockSpecies.getElementId()).thenReturn("1"); + model1.addElement(mockSpecies); - try { - comparator.compare(model1, model2); - fail("Exception expected"); + model2.addElement(mockSpecies); - } catch (NotImplementedException e) { - - } - try { - comparator.compare(model2, model1); - fail("Exception expected"); - - } catch (NotImplementedException e) { - - } - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + comparator.compare(model1, model2); } @Test public void testDifferent() throws Exception { - try { - Model model1 = getModel(); - Model model2 = getModel(); + Model model1 = getModel(); + Model model2 = getModel(); - assertTrue(comparator.compare(model1, new ModelFullIndexed(null)) != 0); - assertTrue(comparator.compare(model1, null) != 0); - assertTrue(comparator.compare(null, model1) != 0); + assertTrue(comparator.compare(model1, new ModelFullIndexed(null)) != 0); + assertTrue(comparator.compare(model1, null) != 0); + assertTrue(comparator.compare(null, model1) != 0); - model1 = getModel(); - model2 = getModel(); + model1 = getModel(); + model2 = getModel(); - model1.setNotes("ASDsaD"); + model1.setNotes("ASDsaD"); - assertTrue(comparator.compare(model1, model2) != 0); - assertTrue(comparator.compare(model2, model1) != 0); + assertTrue(comparator.compare(model1, model2) != 0); + assertTrue(comparator.compare(model2, model1) != 0); - model1 = getModel(); - model2 = getModel(); + model1 = getModel(); + model2 = getModel(); - GenericProtein protein = new GenericProtein("SAd"); + GenericProtein protein = new GenericProtein("SAd"); - model1.addElement(protein); + model1.addElement(protein); - assertTrue(comparator.compare(model1, model2) != 0); - assertTrue(comparator.compare(model2, model1) != 0); + assertTrue(comparator.compare(model1, model2) != 0); + assertTrue(comparator.compare(model2, model1) != 0); - model1 = getModel(); - model2 = getModel(); + model1 = getModel(); + model2 = getModel(); - model1.getElements().iterator().next().setElementId("sdfsd"); + model1.getElements().iterator().next().setElementId("sdfsd"); - assertTrue(comparator.compare(model1, model2) != 0); - assertTrue(comparator.compare(model2, model1) != 0); + assertTrue(comparator.compare(model1, model2) != 0); + assertTrue(comparator.compare(model2, model1) != 0); - model1 = getModel(); - model2 = getModel(); + model1 = getModel(); + model2 = getModel(); - model1.addElement(new Compartment("unk_id")); + model1.addElement(new Compartment("unk_id")); - assertTrue(comparator.compare(model1, model2) != 0); - assertTrue(comparator.compare(model2, model1) != 0); + assertTrue(comparator.compare(model1, model2) != 0); + assertTrue(comparator.compare(model2, model1) != 0); - model1 = getModel(); - model2 = getModel(); + model1 = getModel(); + model2 = getModel(); - model1.getElementByElementId("default").setName("tmpxx"); + model1.getElementByElementId("default").setName("tmpxx"); - assertTrue(comparator.compare(model1, model2) != 0); - assertTrue(comparator.compare(model2, model1) != 0); + assertTrue(comparator.compare(model1, model2) != 0); + assertTrue(comparator.compare(model2, model1) != 0); - model1 = getModel(); - model2 = getModel(); + model1 = getModel(); + model2 = getModel(); - model1.addLayer(new Layer()); + model1.addLayer(new Layer()); - assertTrue(comparator.compare(model1, model2) != 0); - assertTrue(comparator.compare(model2, model1) != 0); + assertTrue(comparator.compare(model1, model2) != 0); + assertTrue(comparator.compare(model2, model1) != 0); - model1 = getModel(); - model2 = getModel(); + model1 = getModel(); + model2 = getModel(); - model1.getLayers().iterator().next().setName("buu"); + model1.getLayers().iterator().next().setName("buu"); - assertTrue(comparator.compare(model1, model2) != 0); - assertTrue(comparator.compare(model2, model1) != 0); + assertTrue(comparator.compare(model1, model2) != 0); + assertTrue(comparator.compare(model2, model1) != 0); - model1 = getModel(); - model2 = getModel(); + model1 = getModel(); + model2 = getModel(); - model1.addElement(new GenericProtein("ASdas")); + model1.addElement(new GenericProtein("ASdas")); - assertTrue(comparator.compare(model1, model2) != 0); - assertTrue(comparator.compare(model2, model1) != 0); + assertTrue(comparator.compare(model1, model2) != 0); + assertTrue(comparator.compare(model2, model1) != 0); - model1 = getModel(); - model2 = getModel(); + model1 = getModel(); + model2 = getModel(); - model1.getElements().iterator().next() - .addMiriamData(new MiriamData(MiriamRelationType.BQ_BIOL_HAS_PART, MiriamType.CHEBI, "c")); + model1.getElements().iterator().next() + .addMiriamData(new MiriamData(MiriamRelationType.BQ_BIOL_HAS_PART, MiriamType.CHEBI, "c")); - assertTrue(comparator.compare(model1, model2) != 0); - assertTrue(comparator.compare(model2, model1) != 0); + assertTrue(comparator.compare(model1, model2) != 0); + assertTrue(comparator.compare(model2, model1) != 0); - model1 = getModel(); - model2 = getModel(); + model1 = getModel(); + model2 = getModel(); - model1.getReactions().iterator().next().setName("dsf"); + model1.getReactions().iterator().next().setName("dsf"); - assertTrue(comparator.compare(model1, model2) != 0); - assertTrue(comparator.compare(model2, model1) != 0); + assertTrue(comparator.compare(model1, model2) != 0); + assertTrue(comparator.compare(model2, model1) != 0); - model1 = getModel(); - model2 = getModel(); + model1 = getModel(); + model2 = getModel(); - model1.setIdModel("asdsdasd"); + model1.setIdModel("asdsdasd"); - assertTrue(comparator.compare(model1, model2) != 0); - assertTrue(comparator.compare(model2, model1) != 0); + assertTrue(comparator.compare(model1, model2) != 0); + assertTrue(comparator.compare(model2, model1) != 0); - model1 = getModel(); - model2 = getModel(); + model1 = getModel(); + model2 = getModel(); - model1.setWidth(123); + model1.setWidth(123); - assertTrue(comparator.compare(model1, model2) != 0); - assertTrue(comparator.compare(model2, model1) != 0); + assertTrue(comparator.compare(model1, model2) != 0); + assertTrue(comparator.compare(model2, model1) != 0); - model1 = getModel(); - model2 = getModel(); + model1 = getModel(); + model2 = getModel(); - model1.setHeight(636); + model1.setHeight(636); - assertTrue(comparator.compare(model1, model2) != 0); - assertTrue(comparator.compare(model2, model1) != 0); + assertTrue(comparator.compare(model1, model2) != 0); + assertTrue(comparator.compare(model2, model1) != 0); - model1 = getModel(); - model2 = getModel(); + model1 = getModel(); + model2 = getModel(); - model1.setZoomLevels(1); + model1.setZoomLevels(1); - assertTrue(comparator.compare(model1, model2) != 0); - assertTrue(comparator.compare(model2, model1) != 0); + assertTrue(comparator.compare(model1, model2) != 0); + assertTrue(comparator.compare(model2, model1) != 0); - model1 = getModel(); - model2 = getModel(); + model1 = getModel(); + model2 = getModel(); - model1.setTileSize(129); + model1.setTileSize(129); - assertTrue(comparator.compare(model1, model2) != 0); - assertTrue(comparator.compare(model2, model1) != 0); + assertTrue(comparator.compare(model1, model2) != 0); + assertTrue(comparator.compare(model2, model1) != 0); - model1 = getModel(); - model2 = getModel(); + model1 = getModel(); + model2 = getModel(); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } } private Model getModel() { @@ -337,152 +280,115 @@ public class ModelComparatorTest { @Test public void testCompareSubmodels() throws Exception { - try { - Model model1 = getModel(); - Model model2 = getModel(); + Model model1 = getModel(); + Model model2 = getModel(); - Model model3 = getModel(); + Model model3 = getModel(); - ModelSubmodelConnection submodelA = new ModelSubmodelConnection(model3, SubmodelType.DOWNSTREAM_TARGETS); + ModelSubmodelConnection submodelA = new ModelSubmodelConnection(model3, SubmodelType.DOWNSTREAM_TARGETS); - model1.addSubmodelConnection(submodelA); + model1.addSubmodelConnection(submodelA); - assertTrue(comparator.compare(model1, model2) != 0); - assertTrue(comparator.compare(model2, model1) != 0); + assertTrue(comparator.compare(model1, model2) != 0); + assertTrue(comparator.compare(model2, model1) != 0); - Model model4 = getModel(); + Model model4 = getModel(); - ModelSubmodelConnection submodelB = new ModelSubmodelConnection(model4, SubmodelType.DOWNSTREAM_TARGETS); + ModelSubmodelConnection submodelB = new ModelSubmodelConnection(model4, SubmodelType.DOWNSTREAM_TARGETS); - model2.addSubmodelConnection(submodelB); + model2.addSubmodelConnection(submodelB); - assertTrue(comparator.compare(model1, model2) == 0); + assertTrue(comparator.compare(model1, model2) == 0); - submodelB.setName("A"); + submodelB.setName("A"); - assertTrue(comparator.compare(model1, model2) != 0); - assertTrue(comparator.compare(model2, model1) != 0); + assertTrue(comparator.compare(model1, model2) != 0); + assertTrue(comparator.compare(model2, model1) != 0); - submodelB.setName(null); - assertTrue(comparator.compare(model1, model2) == 0); + submodelB.setName(null); + assertTrue(comparator.compare(model1, model2) == 0); - model4.setNotes("ASdasdhsjkadhask"); - assertTrue(comparator.compare(model1, model2) != 0); - assertTrue(comparator.compare(model2, model1) != 0); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + model4.setNotes("ASdasdhsjkadhask"); + assertTrue(comparator.compare(model1, model2) != 0); + assertTrue(comparator.compare(model2, model1) != 0); } @Test public void testCompareSubmodels2() throws Exception { - try { - Model model1 = getModel(); - Model model2 = getModel(); - - model1.addSubmodelConnection(new ModelSubmodelConnection(getModel(), SubmodelType.DOWNSTREAM_TARGETS)); - model1.addSubmodelConnection(new ModelSubmodelConnection(getModel(), SubmodelType.DOWNSTREAM_TARGETS)); + Model model1 = getModel(); + Model model2 = getModel(); - model2.addSubmodelConnection(new ModelSubmodelConnection(getModel(), SubmodelType.DOWNSTREAM_TARGETS)); - model2.addSubmodelConnection(new ModelSubmodelConnection(getModel(), SubmodelType.PATHWAY)); + model1.addSubmodelConnection(new ModelSubmodelConnection(getModel(), SubmodelType.DOWNSTREAM_TARGETS)); + model1.addSubmodelConnection(new ModelSubmodelConnection(getModel(), SubmodelType.DOWNSTREAM_TARGETS)); - assertTrue(comparator.compare(model1, model2) != 0); - assertTrue(comparator.compare(model2, model1) != 0); + model2.addSubmodelConnection(new ModelSubmodelConnection(getModel(), SubmodelType.DOWNSTREAM_TARGETS)); + model2.addSubmodelConnection(new ModelSubmodelConnection(getModel(), SubmodelType.PATHWAY)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertTrue(comparator.compare(model1, model2) != 0); + assertTrue(comparator.compare(model2, model1) != 0); } @Test public void testCompareName() throws Exception { - try { - Model model1 = getModel(); - Model model2 = getModel(); - model1.setName("ASD"); - assertTrue(comparator.compare(model1, model2) != 0); - assertTrue(comparator.compare(model2, model1) != 0); - model2.setName("A"); - assertTrue(comparator.compare(model1, model2) != 0); - assertTrue(comparator.compare(model2, model1) != 0); - model1.setName("A"); - assertEquals(0, comparator.compare(model1, model2)); - assertEquals(0, comparator.compare(model2, model1)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Model model1 = getModel(); + Model model2 = getModel(); + model1.setName("ASD"); + assertTrue(comparator.compare(model1, model2) != 0); + assertTrue(comparator.compare(model2, model1) != 0); + model2.setName("A"); + assertTrue(comparator.compare(model1, model2) != 0); + assertTrue(comparator.compare(model2, model1) != 0); + model1.setName("A"); + assertEquals(0, comparator.compare(model1, model2)); + assertEquals(0, comparator.compare(model2, model1)); } @Test public void testCompareAnnotations() throws Exception { - try { - Model model1 = getModel(); - Model model2 = getModel(); - model1.addMiriamData(new MiriamData(MiriamType.CHEBI, "CHEBI:12345")); - assertTrue("Models have different annotations", comparator.compare(model1, model2) != 0); - assertTrue(comparator.compare(model2, model1) != 0); - model2.addMiriamData(new MiriamData(MiriamType.CHEBI, "CHEBI:12345")); - assertEquals(0, comparator.compare(model1, model2)); - assertEquals(0, comparator.compare(model2, model1)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Model model1 = getModel(); + Model model2 = getModel(); + model1.addMiriamData(new MiriamData(MiriamType.CHEBI, "CHEBI:12345")); + assertTrue("Models have different annotations", comparator.compare(model1, model2) != 0); + assertTrue(comparator.compare(model2, model1) != 0); + model2.addMiriamData(new MiriamData(MiriamType.CHEBI, "CHEBI:12345")); + assertEquals(0, comparator.compare(model1, model2)); + assertEquals(0, comparator.compare(model2, model1)); } @Test public void testCompareAuthors() throws Exception { - try { - Model model1 = getModel(); - Model model2 = getModel(); - model1.addAuthor(new Author("x", "y")); - assertTrue("Models have different authors", comparator.compare(model1, model2) != 0); - assertTrue(comparator.compare(model2, model1) != 0); - model2.addAuthor(new Author(model1.getAuthors().iterator().next())); - assertEquals(0, comparator.compare(model1, model2)); - assertEquals(0, comparator.compare(model2, model1)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Model model1 = getModel(); + Model model2 = getModel(); + model1.addAuthor(new Author("x", "y")); + assertTrue("Models have different authors", comparator.compare(model1, model2) != 0); + assertTrue(comparator.compare(model2, model1) != 0); + model2.addAuthor(new Author(model1.getAuthors().iterator().next())); + assertEquals(0, comparator.compare(model1, model2)); + assertEquals(0, comparator.compare(model2, model1)); } @Test public void testCompareCreationDate() throws Exception { - try { - Model model1 = getModel(); - Model model2 = getModel(); - model1.setCreationDate(Calendar.getInstance()); - assertTrue("Models have different creation dates", comparator.compare(model1, model2) != 0); - assertTrue(comparator.compare(model2, model1) != 0); - model2.setCreationDate(model1.getCreationDate()); - assertEquals(0, comparator.compare(model1, model2)); - assertEquals(0, comparator.compare(model2, model1)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Model model1 = getModel(); + Model model2 = getModel(); + model1.setCreationDate(Calendar.getInstance()); + assertTrue("Models have different creation dates", comparator.compare(model1, model2) != 0); + assertTrue(comparator.compare(model2, model1) != 0); + model2.setCreationDate(model1.getCreationDate()); + assertEquals(0, comparator.compare(model1, model2)); + assertEquals(0, comparator.compare(model2, model1)); } @Test public void testCompareModificationDate() throws Exception { - try { - Model model1 = getModel(); - Model model2 = getModel(); - model1.addModificationDate(Calendar.getInstance()); - assertTrue("Models have different modification dates", comparator.compare(model1, model2) != 0); - assertTrue(comparator.compare(model2, model1) != 0); - model2.addModificationDate(model1.getModificationDates().get(0)); - assertEquals(0, comparator.compare(model1, model2)); - assertEquals(0, comparator.compare(model2, model1)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Model model1 = getModel(); + Model model2 = getModel(); + model1.addModificationDate(Calendar.getInstance()); + assertTrue("Models have different modification dates", comparator.compare(model1, model2) != 0); + assertTrue(comparator.compare(model2, model1) != 0); + model2.addModificationDate(model1.getModificationDates().get(0)); + assertEquals(0, comparator.compare(model1, model2)); + assertEquals(0, comparator.compare(model2, model1)); } } diff --git a/model/src/test/java/lcsb/mapviewer/model/map/model/ModelDataTest.java b/model/src/test/java/lcsb/mapviewer/model/map/model/ModelDataTest.java index 20d4b1c27f788a52de171a1f59176cda494178b8..0e9f421cdc585ab5cbaf6b28c8dbc1d7d57abdbd 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/model/ModelDataTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/model/ModelDataTest.java @@ -1,21 +1,14 @@ package lcsb.mapviewer.model.map.model; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; -import java.util.ArrayList; -import java.util.Calendar; -import java.util.HashSet; -import java.util.List; -import java.util.Set; +import java.util.*; import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; +import org.mockito.Mockito; +import lcsb.mapviewer.ModelTestFunctions; import lcsb.mapviewer.common.Configuration; import lcsb.mapviewer.common.exception.InvalidArgumentException; import lcsb.mapviewer.model.Project; @@ -26,7 +19,7 @@ import lcsb.mapviewer.model.map.reaction.Reaction; import lcsb.mapviewer.model.map.species.Element; import lcsb.mapviewer.model.map.species.GenericProtein; -public class ModelDataTest { +public class ModelDataTest extends ModelTestFunctions { @Before public void setUp() throws Exception { @@ -38,275 +31,183 @@ public class ModelDataTest { @Test public void testSerialization() { - try { - SerializationUtils.serialize(new ModelData()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + SerializationUtils.serialize(new ModelData()); } @Test public void testAddElements() { - try { - ModelData md = new ModelData(); - List<Element> elements = new ArrayList<>(); - elements.add(new GenericProtein("unk_id")); - md.addElements(elements); - assertEquals(1, md.getElements().size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + ModelData md = new ModelData(); + List<Element> elements = new ArrayList<>(); + elements.add(new GenericProtein("unk_id")); + md.addElements(elements); + assertEquals(1, md.getElements().size()); } @Test public void testAddReactions() { - try { - ModelData md = new ModelData(); - List<Reaction> reactions = new ArrayList<>(); - reactions.add(new Reaction()); - md.addReactions(reactions); - assertEquals(1, md.getReactions().size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + ModelData md = new ModelData(); + List<Reaction> reactions = new ArrayList<>(); + reactions.add(new Reaction()); + md.addReactions(reactions); + assertEquals(1, md.getReactions().size()); } @Test public void testAddLayers() { - try { - ModelData md = new ModelData(); - List<Layer> layers = new ArrayList<>(); - layers.add(new Layer()); - md.addLayers(layers); - assertEquals(1, md.getLayers().size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + ModelData md = new ModelData(); + List<Layer> layers = new ArrayList<>(); + layers.add(new Layer()); + md.addLayers(layers); + assertEquals(1, md.getLayers().size()); } @Test public void testAddElementGroup() { - try { - ModelData md = new ModelData(); - md.addElementGroup(null); - // not implemented for now - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + ModelData md = new ModelData(); + md.addElementGroup(null); + // not implemented for now } @Test public void testAddBlockDiagram() { - try { - ModelData md = new ModelData(); - md.addBlockDiagream(new BlockDiagram() { - - /** - * - */ - private static final long serialVersionUID = 1L; - }); - // not implemented for now - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + ModelData md = new ModelData(); + md.addBlockDiagream(Mockito.spy(BlockDiagram.class)); + // not implemented for now } - @Test + @Test(expected = InvalidArgumentException.class) public void testRemoveElement1() { - try { - ModelData md = new ModelData(); - md.removeElement(null); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + ModelData md = new ModelData(); + md.removeElement(null); } @Test public void testRemoveElement2() { - try { - ModelData md = new ModelData(); - md.removeElement(new GenericProtein("unk_id")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + ModelData md = new ModelData(); + md.removeElement(new GenericProtein("unk_id")); } @Test public void testRemoveElement3() { - try { - ModelData md = new ModelData(); - Element protein = new GenericProtein("unk_id"); - md.addElement(protein); - assertEquals(1, md.getElements().size()); - md.removeElement(protein); - assertEquals(0, md.getElements().size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + ModelData md = new ModelData(); + Element protein = new GenericProtein("unk_id"); + md.addElement(protein); + assertEquals(1, md.getElements().size()); + md.removeElement(protein); + assertEquals(0, md.getElements().size()); } @Test public void testRemoveReaction2() { - try { - ModelData md = new ModelData(); - md.removeReaction(new Reaction()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + ModelData md = new ModelData(); + md.removeReaction(new Reaction()); } @Test public void testRemoveReaction3() { - try { - ModelData md = new ModelData(); - Reaction reaction = new Reaction(); - md.addReaction(reaction); - assertEquals(1, md.getReactions().size()); - md.removeReaction(reaction); - assertEquals(0, md.getReactions().size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + ModelData md = new ModelData(); + Reaction reaction = new Reaction(); + md.addReaction(reaction); + assertEquals(1, md.getReactions().size()); + md.removeReaction(reaction); + assertEquals(0, md.getReactions().size()); } @Test public void testAddSubmodel() { - try { - ModelData md = new ModelData(); - md.addSubmodel(new ModelSubmodelConnection()); - assertEquals(1, md.getSubmodels().size()); - } catch (InvalidArgumentException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + ModelData md = new ModelData(); + md.addSubmodel(new ModelSubmodelConnection()); + assertEquals(1, md.getSubmodels().size()); } @Test public void testAddAuthor() { - try { - ModelData md = new ModelData(); - md.addAuthor(new Author("Piotr", "Gawron")); - assertEquals(1, md.getAuthors().size()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + ModelData md = new ModelData(); + md.addAuthor(new Author("Piotr", "Gawron")); + assertEquals(1, md.getAuthors().size()); } @Test public void testAddModificationDate() { - try { - ModelData md = new ModelData(); - md.addModificationDate(Calendar.getInstance()); - assertEquals(1, md.getModificationDates().size()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + ModelData md = new ModelData(); + md.addModificationDate(Calendar.getInstance()); + assertEquals(1, md.getModificationDates().size()); } @Test public void testSetCreationDate() { - try { - ModelData md = new ModelData(); - assertNull(md.getCreationDate()); - md.setCreationDate(Calendar.getInstance()); - assertNotNull(md.getCreationDate()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + ModelData md = new ModelData(); + assertNull(md.getCreationDate()); + md.setCreationDate(Calendar.getInstance()); + assertNotNull(md.getCreationDate()); } @Test public void testGetters() { - try { - ModelData md = new ModelData(); - Set<Element> elements = new HashSet<>(); - Set<Layer> layers = new HashSet<>(); - Set<Reaction> reactions = new HashSet<>(); - Set<SubmodelConnection> parents = new HashSet<>(); - List<OverviewImage> overviewImages = new ArrayList<>(); - overviewImages.add(new OverviewImage()); - Integer id = 95; - int width = 2; - Double widthDouble = 2.0; - int height = 29; - int zoomLevels = 3; - int tileSize = 512; - String modelId = "modId"; - String notes = "nOT"; - String name = "n_ma"; - Double heightDouble = 29.0; - Project project = new Project(); - - Model model = new ModelFullIndexed(null); - - md.setId(id); - assertEquals(id, md.getId()); - - md.setElements(elements); - assertEquals(elements, md.getElements()); - - md.setProject(project); - assertEquals(project, md.getProject()); - - md.setWidth(width); - assertEquals(widthDouble, md.getWidth(), Configuration.EPSILON); - - md.setHeight(height); - assertEquals(heightDouble, md.getHeight(), Configuration.EPSILON); - - md.setZoomLevels(zoomLevels); - assertEquals(zoomLevels, md.getZoomLevels()); - - md.setTileSize(tileSize); - assertEquals(tileSize, md.getTileSize()); - - md.setIdModel(modelId); - assertEquals(modelId, md.getIdModel()); - - md.setNotes(notes); - assertEquals(notes, md.getNotes()); - - md.setName(name); - assertEquals(name, md.getName()); - - md.setModel(null); - assertNull(md.getModel()); - md.setModel(model); - assertEquals(model, md.getModel()); - - md.setLayers(layers); - assertEquals(layers, md.getLayers()); - - md.setReactions(reactions); - assertEquals(reactions, md.getReactions()); - - md.setParentModels(parents); - assertEquals(parents, md.getParentModels()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + ModelData md = new ModelData(); + Set<Element> elements = new HashSet<>(); + Set<Layer> layers = new HashSet<>(); + Set<Reaction> reactions = new HashSet<>(); + Set<SubmodelConnection> parents = new HashSet<>(); + List<OverviewImage> overviewImages = new ArrayList<>(); + overviewImages.add(new OverviewImage()); + Integer id = 95; + int width = 2; + Double widthDouble = 2.0; + int height = 29; + int zoomLevels = 3; + int tileSize = 512; + String modelId = "modId"; + String notes = "nOT"; + String name = "n_ma"; + Double heightDouble = 29.0; + Project project = new Project(); + + Model model = new ModelFullIndexed(null); + + md.setId(id); + assertEquals(id, md.getId()); + + md.setElements(elements); + assertEquals(elements, md.getElements()); + + md.setProject(project); + assertEquals(project, md.getProject()); + + md.setWidth(width); + assertEquals(widthDouble, md.getWidth(), Configuration.EPSILON); + + md.setHeight(height); + assertEquals(heightDouble, md.getHeight(), Configuration.EPSILON); + + md.setZoomLevels(zoomLevels); + assertEquals(zoomLevels, md.getZoomLevels()); + + md.setTileSize(tileSize); + assertEquals(tileSize, md.getTileSize()); + + md.setIdModel(modelId); + assertEquals(modelId, md.getIdModel()); + + md.setNotes(notes); + assertEquals(notes, md.getNotes()); + + md.setName(name); + assertEquals(name, md.getName()); + + md.setModel(null); + assertNull(md.getModel()); + md.setModel(model); + assertEquals(model, md.getModel()); + + md.setLayers(layers); + assertEquals(layers, md.getLayers()); + + md.setReactions(reactions); + assertEquals(reactions, md.getReactions()); + + md.setParentModels(parents); + assertEquals(parents, md.getParentModels()); + } } diff --git a/model/src/test/java/lcsb/mapviewer/model/map/model/ModelFullIndexedTest.java b/model/src/test/java/lcsb/mapviewer/model/map/model/ModelFullIndexedTest.java index d6eab5e5ce76153c519f5b6050b36db1b226e7a3..0f4f321b6cf4613235be4693f4fcc8264938797d 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/model/ModelFullIndexedTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/model/ModelFullIndexedTest.java @@ -1,42 +1,27 @@ package lcsb.mapviewer.model.map.model; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import org.apache.logging.log4j.*; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import static org.junit.Assert.*; + +import java.util.*; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.junit.*; import org.mockito.Mockito; +import lcsb.mapviewer.ModelTestFunctions; import lcsb.mapviewer.common.Configuration; import lcsb.mapviewer.common.exception.InvalidArgumentException; import lcsb.mapviewer.model.Project; -import lcsb.mapviewer.model.map.BioEntity; -import lcsb.mapviewer.model.map.MiriamData; -import lcsb.mapviewer.model.map.MiriamType; +import lcsb.mapviewer.model.map.*; import lcsb.mapviewer.model.map.compartment.Compartment; import lcsb.mapviewer.model.map.compartment.PathwayCompartment; import lcsb.mapviewer.model.map.layout.graphics.Layer; -import lcsb.mapviewer.model.map.reaction.Product; -import lcsb.mapviewer.model.map.reaction.Reactant; -import lcsb.mapviewer.model.map.reaction.Reaction; +import lcsb.mapviewer.model.map.reaction.*; import lcsb.mapviewer.model.map.reaction.type.TransportReaction; -import lcsb.mapviewer.model.map.species.Complex; -import lcsb.mapviewer.model.map.species.Element; -import lcsb.mapviewer.model.map.species.GenericProtein; -import lcsb.mapviewer.model.map.species.Species; +import lcsb.mapviewer.model.map.species.*; -public class ModelFullIndexedTest { +public class ModelFullIndexedTest extends ModelTestFunctions { Logger logger = LogManager.getLogger(ModelFullIndexedTest.class); @Before @@ -49,628 +34,442 @@ public class ModelFullIndexedTest { @Test public void testConstructor() { - try { - ModelFullIndexed model = new ModelFullIndexed(null); - Species protein = new GenericProtein("1a"); - Species protein2 = new GenericProtein("f"); - Species protein3 = new GenericProtein("fa"); - - Element compartment = new Compartment("aaa"); - Element compartment3 = new Compartment("aaa3"); - Element compartment2 = new PathwayCompartment("aaa2"); - model.addElement(protein); - model.addElement(protein2); - model.addElement(protein3); - model.addElement(compartment); - model.addElement(compartment2); - model.addElement(compartment3); - - Reaction reaction = new TransportReaction(); - reaction.addReactant(new Reactant(protein)); - reaction.addProduct(new Product(protein2)); - model.addReaction(reaction); - model.setProject(new Project()); - - ModelData submodel = new ModelData(); - model.addSubmodelConnection(new ModelSubmodelConnection(submodel, SubmodelType.DOWNSTREAM_TARGETS)); - Model submodel2 = new ModelFullIndexed(null); - model.addSubmodelConnection(new ModelSubmodelConnection(submodel2, SubmodelType.DOWNSTREAM_TARGETS)); - - ModelFullIndexed model2 = new ModelFullIndexed(model.getModelData()); - - assertNotNull(model2); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + ModelFullIndexed model = new ModelFullIndexed(null); + Species protein = new GenericProtein("1a"); + Species protein2 = new GenericProtein("f"); + Species protein3 = new GenericProtein("fa"); + + Element compartment = new Compartment("aaa"); + Element compartment3 = new Compartment("aaa3"); + Element compartment2 = new PathwayCompartment("aaa2"); + model.addElement(protein); + model.addElement(protein2); + model.addElement(protein3); + model.addElement(compartment); + model.addElement(compartment2); + model.addElement(compartment3); + + Reaction reaction = new TransportReaction(); + reaction.addReactant(new Reactant(protein)); + reaction.addProduct(new Product(protein2)); + model.addReaction(reaction); + model.setProject(new Project()); + + ModelData submodel = new ModelData(); + model.addSubmodelConnection(new ModelSubmodelConnection(submodel, SubmodelType.DOWNSTREAM_TARGETS)); + Model submodel2 = new ModelFullIndexed(null); + model.addSubmodelConnection(new ModelSubmodelConnection(submodel2, SubmodelType.DOWNSTREAM_TARGETS)); + + ModelFullIndexed model2 = new ModelFullIndexed(model.getModelData()); + + assertNotNull(model2); } @Test public void testGetByName() { - try { - String name1 = "1a"; - String name2 = "2a"; - String unknownName = "unk"; - ModelFullIndexed model = new ModelFullIndexed(null); - Species protein = new GenericProtein("id1"); - protein.setName(name1); - Species protein2 = new GenericProtein("id2"); - protein2.setName(name2); - - model.addElement(protein); - model.addElement(protein2); + String name1 = "1a"; + String name2 = "2a"; + String unknownName = "unk"; + ModelFullIndexed model = new ModelFullIndexed(null); + Species protein = new GenericProtein("id1"); + protein.setName(name1); + Species protein2 = new GenericProtein("id2"); + protein2.setName(name2); - List<Element> elements = model.getElementsByName(name1); - List<Element> unkElements = model.getElementsByName(unknownName); + model.addElement(protein); + model.addElement(protein2); - assertEquals(1, elements.size()); - assertEquals(0, unkElements.size()); + List<Element> elements = model.getElementsByName(name1); + List<Element> unkElements = model.getElementsByName(unknownName); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(1, elements.size()); + assertEquals(0, unkElements.size()); } @Test public void testGetSpeciesList() { - try { - ModelFullIndexed model = new ModelFullIndexed(null); - Species protein = new GenericProtein("id1"); - Species protein2 = new GenericProtein("id2"); + ModelFullIndexed model = new ModelFullIndexed(null); + Species protein = new GenericProtein("id1"); + Species protein2 = new GenericProtein("id2"); - model.addElement(protein); - model.addElement(protein2); - model.addElement(new Compartment("compId")); + model.addElement(protein); + model.addElement(protein2); + model.addElement(new Compartment("compId")); - List<Species> speciesList = model.getSpeciesList(); + List<Species> speciesList = model.getSpeciesList(); - assertEquals(2, speciesList.size()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(2, speciesList.size()); } @Test public void testConstructor2() { - try { - ModelFullIndexed model = new ModelFullIndexed(null); - - ModelFullIndexed model2 = new ModelFullIndexed(model.getModelData()); + ModelFullIndexed model = new ModelFullIndexed(null); - assertNotNull(model2); + ModelFullIndexed model2 = new ModelFullIndexed(model.getModelData()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertNotNull(model2); } - @Test + @Test(expected = InvalidArgumentException.class) public void testAddInvalidElement6() { - try { - Element elementMock = Mockito.mock(Element.class); - ModelFullIndexed model = new ModelFullIndexed(null); - model.addElement(elementMock); - - new ModelFullIndexed(model.getModelData()); - - fail("Exception expected"); + Element elementMock = Mockito.mock(Element.class); + ModelFullIndexed model = new ModelFullIndexed(null); + model.addElement(elementMock); - } catch (InvalidArgumentException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + new ModelFullIndexed(model.getModelData()); } - @Test + @Test(expected = InvalidArgumentException.class) public void testAddInvalidElement5() { - try { - ModelFullIndexed model = new ModelFullIndexed(null); - - Complex complex = new Complex("1"); + ModelFullIndexed model = new ModelFullIndexed(null); - model.addElement(complex); - try { - model.addElement(complex); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - } + Complex complex = new Complex("1"); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + model.addElement(complex); + model.addElement(complex); } @Test public void testAddSpeciesWithParent() { - try { - ModelFullIndexed model = new ModelFullIndexed(null); + ModelFullIndexed model = new ModelFullIndexed(null); - model.addElement(new Compartment("default")); + model.addElement(new Compartment("default")); - Complex complex = new Complex("1"); + Complex complex = new Complex("1"); - GenericProtein protein = new GenericProtein("asd"); - protein.setElementId("zz"); - protein.setComplex(complex); + GenericProtein protein = new GenericProtein("asd"); + protein.setElementId("zz"); + protein.setComplex(complex); - model.addElement(complex); + model.addElement(complex); - model.addElement(protein); + model.addElement(protein); - assertEquals(3, model.getElements().size()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(3, model.getElements().size()); } @Test public void testAddSpeciesWithParentWithCompartment() { - try { - ModelFullIndexed model = new ModelFullIndexed(null); - - Compartment compartment = new Compartment("default"); - model.addElement(compartment); + ModelFullIndexed model = new ModelFullIndexed(null); - Complex complex = new Complex("1"); - complex.setCompartment(compartment); + Compartment compartment = new Compartment("default"); + model.addElement(compartment); - GenericProtein protein = new GenericProtein("asd"); - protein.setElementId("zz"); - protein.setComplex(complex); + Complex complex = new Complex("1"); + complex.setCompartment(compartment); - model.addElement(complex); + GenericProtein protein = new GenericProtein("asd"); + protein.setElementId("zz"); + protein.setComplex(complex); - model.addElement(protein); + model.addElement(complex); - assertEquals(3, model.getElements().size()); + model.addElement(protein); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(3, model.getElements().size()); } @Test public void testGetElementByElementId() { - try { - ModelFullIndexed model = new ModelFullIndexed(null); - - assertNull(model.getElementByElementId("id")); - Species protein = new GenericProtein("asd"); - protein.setElementId("id"); + ModelFullIndexed model = new ModelFullIndexed(null); - model.addElement(protein); + assertNull(model.getElementByElementId("id")); + Species protein = new GenericProtein("asd"); + protein.setElementId("id"); - assertNotNull(model.getElementByElementId("id")); + model.addElement(protein); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertNotNull(model.getElementByElementId("id")); } - @Test + @Test(expected = InvalidArgumentException.class) public void testAddCompartment2() { - try { - ModelFullIndexed model = new ModelFullIndexed(null); - - Compartment compartment = new Compartment("1"); + ModelFullIndexed model = new ModelFullIndexed(null); - assertEquals(0, model.getCompartments().size()); - model.addElement(compartment); - assertEquals(1, model.getCompartments().size()); - model.addElement(compartment); + Compartment compartment = new Compartment("1"); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, model.getCompartments().size()); + model.addElement(compartment); + assertEquals(1, model.getCompartments().size()); + model.addElement(compartment); } @Test public void testGetReactionByReactionId() { - try { - String reactionId = "id_r"; - ModelFullIndexed model = new ModelFullIndexed(null); - Reaction reaction = new Reaction(); - reaction.setIdReaction(reactionId); - assertNull(model.getReactionByReactionId(reactionId)); - model.addReaction(reaction); - assertEquals(reaction, model.getReactionByReactionId(reactionId)); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String reactionId = "id_r"; + ModelFullIndexed model = new ModelFullIndexed(null); + Reaction reaction = new Reaction(); + reaction.setIdReaction(reactionId); + assertNull(model.getReactionByReactionId(reactionId)); + model.addReaction(reaction); + assertEquals(reaction, model.getReactionByReactionId(reactionId)); } @Test public void testGetReactionByDbId() { - try { - int reactionId = 12; - ModelFullIndexed model = new ModelFullIndexed(null); - Reaction reaction = new Reaction(); - reaction.setId(reactionId); - assertNull(model.getReactionByDbId(reactionId)); - model.addReaction(reaction); - assertEquals(reaction, model.getReactionByDbId(reactionId)); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + int reactionId = 12; + ModelFullIndexed model = new ModelFullIndexed(null); + Reaction reaction = new Reaction(); + reaction.setId(reactionId); + assertNull(model.getReactionByDbId(reactionId)); + model.addReaction(reaction); + assertEquals(reaction, model.getReactionByDbId(reactionId)); } @Test public void testGetElementByDbId() { - try { - int elementId = 12; - ModelFullIndexed model = new ModelFullIndexed(null); - Element protein = new GenericProtein("1"); - protein.setId(elementId); - assertNull(model.getElementByDbId(elementId)); - model.addElement(protein); - assertEquals(protein, model.getElementByDbId(elementId)); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + int elementId = 12; + ModelFullIndexed model = new ModelFullIndexed(null); + Element protein = new GenericProtein("1"); + protein.setId(elementId); + assertNull(model.getElementByDbId(elementId)); + model.addElement(protein); + assertEquals(protein, model.getElementByDbId(elementId)); } @Test public void testGetSortedCompartments() { - try { - ModelFullIndexed model = new ModelFullIndexed(null); - Compartment compartment = new Compartment("a1"); - compartment.setWidth(12); - compartment.setHeight(12); - model.addElement(compartment); - compartment = new Compartment("a2"); - compartment.setWidth(14); - compartment.setHeight(14); - model.addElement(compartment); - compartment = new Compartment("a3"); - compartment.setWidth(13); - compartment.setHeight(13); - model.addElement(compartment); - - List<Compartment> compartments = model.getSortedCompartments(); - assertEquals(196.0, compartments.get(0).getSize(), Configuration.EPSILON); - assertEquals(169.0, compartments.get(1).getSize(), Configuration.EPSILON); - assertEquals(144.0, compartments.get(2).getSize(), Configuration.EPSILON); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + ModelFullIndexed model = new ModelFullIndexed(null); + Compartment compartment = new Compartment("a1"); + compartment.setWidth(12); + compartment.setHeight(12); + model.addElement(compartment); + compartment = new Compartment("a2"); + compartment.setWidth(14); + compartment.setHeight(14); + model.addElement(compartment); + compartment = new Compartment("a3"); + compartment.setWidth(13); + compartment.setHeight(13); + model.addElement(compartment); + + List<Compartment> compartments = model.getSortedCompartments(); + assertEquals(196.0, compartments.get(0).getSize(), Configuration.EPSILON); + assertEquals(169.0, compartments.get(1).getSize(), Configuration.EPSILON); + assertEquals(144.0, compartments.get(2).getSize(), Configuration.EPSILON); } @Test public void testRemoveCompartment2() { - try { - ModelFullIndexed model = new ModelFullIndexed(null); - Compartment compartment = new Compartment("a1"); - compartment.setWidth(12); - compartment.setHeight(12); - model.addElement(compartment); + ModelFullIndexed model = new ModelFullIndexed(null); + Compartment compartment = new Compartment("a1"); + compartment.setWidth(12); + compartment.setHeight(12); + model.addElement(compartment); - compartment = new Compartment("a2"); - compartment.setWidth(14); - compartment.setHeight(14); - model.addElement(compartment); - assertEquals(2, model.getElements().size()); + compartment = new Compartment("a2"); + compartment.setWidth(14); + compartment.setHeight(14); + model.addElement(compartment); + assertEquals(2, model.getElements().size()); - model.removeElement(compartment); - assertEquals(1, model.getElements().size()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + model.removeElement(compartment); + assertEquals(1, model.getElements().size()); } @Test public void testAddElements() { - try { - ModelFullIndexed model = new ModelFullIndexed(null); - - Compartment compartment = new Compartment("1"); - compartment.setWidth(100); - compartment.setHeight(100); - List<Element> elements = new ArrayList<>(); - elements.add(compartment); + ModelFullIndexed model = new ModelFullIndexed(null); - Complex complex = new Complex("ca1"); - elements.add(complex); - complex.setWidth(10); - complex.setHeight(10); + Compartment compartment = new Compartment("1"); + compartment.setWidth(100); + compartment.setHeight(100); + List<Element> elements = new ArrayList<>(); + elements.add(compartment); - Species species = new GenericProtein("a1"); - elements.add(species); - species.setWidth(20); - species.setHeight(20); + Complex complex = new Complex("ca1"); + elements.add(complex); + complex.setWidth(10); + complex.setHeight(10); - assertEquals(0, model.getCompartments().size()); - model.addElements(elements); - assertEquals(1, model.getCompartments().size()); - assertEquals(1, model.getComplexList().size()); - assertEquals(1, model.getNotComplexSpeciesList().size()); + Species species = new GenericProtein("a1"); + elements.add(species); + species.setWidth(20); + species.setHeight(20); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, model.getCompartments().size()); + model.addElements(elements); + assertEquals(1, model.getCompartments().size()); + assertEquals(1, model.getComplexList().size()); + assertEquals(1, model.getNotComplexSpeciesList().size()); } - @Test + @Test(expected = InvalidArgumentException.class) public void testAddInvalidElement2() { - try { - ModelFullIndexed model = new ModelFullIndexed(null); - GenericProtein protein = new GenericProtein((String) null); - model.addElement(protein); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + ModelFullIndexed model = new ModelFullIndexed(null); + GenericProtein protein = new GenericProtein((String) null); + model.addElement(protein); } @Test public void testRemoveCompartment() { - try { - ModelFullIndexed model = new ModelFullIndexed(null); - - Compartment parent = new Compartment("parent_id"); + ModelFullIndexed model = new ModelFullIndexed(null); - Compartment compartment = new Compartment("child_id"); - compartment.setCompartment(parent); + Compartment parent = new Compartment("parent_id"); - model.addElement(compartment); + Compartment compartment = new Compartment("child_id"); + compartment.setCompartment(parent); - assertEquals(1, model.getElements().size()); + model.addElement(compartment); - model.removeElement(compartment); - assertEquals(0, model.getElements().size()); + assertEquals(1, model.getElements().size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + model.removeElement(compartment); + assertEquals(0, model.getElements().size()); } @Test public void testRemoveComplex() { - try { - ModelFullIndexed model = new ModelFullIndexed(null); - model.addElement(new Compartment("default")); - - Complex parentComplex = new Complex("a"); + ModelFullIndexed model = new ModelFullIndexed(null); + model.addElement(new Compartment("default")); - Complex childComplex = new Complex("b"); - childComplex.setComplex(parentComplex); - childComplex.setElementId("1"); + Complex parentComplex = new Complex("a"); - childComplex.setCompartment(new Compartment("comp_id")); - childComplex.setComplex(new Complex("d")); + Complex childComplex = new Complex("b"); + childComplex.setComplex(parentComplex); + childComplex.setElementId("1"); - model.addElement(childComplex); + childComplex.setCompartment(new Compartment("comp_id")); + childComplex.setComplex(new Complex("d")); - assertEquals(2, model.getElements().size()); + model.addElement(childComplex); - childComplex.setComplex(new Complex("xxx")); + assertEquals(2, model.getElements().size()); - model.removeElement(childComplex); - assertEquals(1, model.getElements().size()); + childComplex.setComplex(new Complex("xxx")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + model.removeElement(childComplex); + assertEquals(1, model.getElements().size()); } @Test public void testAddLayers() { - try { - ModelFullIndexed model = new ModelFullIndexed(null); + ModelFullIndexed model = new ModelFullIndexed(null); - Layer layer = new Layer(); - List<Layer> layers = new ArrayList<>(); - layers.add(layer); + Layer layer = new Layer(); + List<Layer> layers = new ArrayList<>(); + layers.add(layer); - assertEquals(0, model.getLayers().size()); - model.addLayers(layers); - assertEquals(1, model.getLayers().size()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, model.getLayers().size()); + model.addLayers(layers); + assertEquals(1, model.getLayers().size()); } @Test public void testGetElementByAnnotation() { - try { - ModelFullIndexed model = new ModelFullIndexed(null); - - Reaction reaction = new Reaction(); - reaction.addMiriamData(new MiriamData(MiriamType.CAS, "C")); - model.addReaction(reaction); + ModelFullIndexed model = new ModelFullIndexed(null); - Set<BioEntity> objects = model.getElementsByAnnotation(new MiriamData()); - assertEquals(0, objects.size()); - objects = model.getElementsByAnnotation(new MiriamData(MiriamType.CAS, "C")); - assertTrue(objects.contains(reaction)); + Reaction reaction = new Reaction(); + reaction.addMiriamData(new MiriamData(MiriamType.CAS, "C")); + model.addReaction(reaction); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Set<BioEntity> objects = model.getElementsByAnnotation(new MiriamData()); + assertEquals(0, objects.size()); + objects = model.getElementsByAnnotation(new MiriamData(MiriamType.CAS, "C")); + assertTrue(objects.contains(reaction)); } - @Test + @Test(expected = InvalidArgumentException.class) public void testSetNotes() { - try { - ModelFullIndexed model = new ModelFullIndexed(null); - - model.setNotes("<html/>"); - fail("Exception expected"); - } catch (InvalidArgumentException e) { + ModelFullIndexed model = new ModelFullIndexed(null); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + model.setNotes("<html/>"); } @Test public void testStubCoverageTests() { - try { - ModelFullIndexed model = new ModelFullIndexed(null); - - model.addElementGroup(null); - model.addBlockDiagream(null); + ModelFullIndexed model = new ModelFullIndexed(null); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + model.addElementGroup(null); + model.addBlockDiagream(null); } @Test public void testGetSubmodelByName() { - try { - ModelFullIndexed model = new ModelFullIndexed(null); - ModelFullIndexed child = new ModelFullIndexed(null); - String parentName = "PARENT M"; - String childName = "MY CHILD"; - model.setName(parentName); - child.setName(childName); - model.addSubmodelConnection(new ModelSubmodelConnection(child, SubmodelType.DOWNSTREAM_TARGETS)); - - assertNull(model.getSubmodelByName("xyZ")); - assertNull(model.getSubmodelByName(null)); - assertEquals(model, model.getSubmodelByName(parentName)); - assertEquals(child, model.getSubmodelByName(childName)); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + ModelFullIndexed model = new ModelFullIndexed(null); + ModelFullIndexed child = new ModelFullIndexed(null); + String parentName = "PARENT M"; + String childName = "MY CHILD"; + model.setName(parentName); + child.setName(childName); + model.addSubmodelConnection(new ModelSubmodelConnection(child, SubmodelType.DOWNSTREAM_TARGETS)); + + assertNull(model.getSubmodelByName("xyZ")); + assertNull(model.getSubmodelByName(null)); + assertEquals(model, model.getSubmodelByName(parentName)); + assertEquals(child, model.getSubmodelByName(childName)); } @Test public void testGetSubmodelById() { - try { - ModelFullIndexed model = new ModelFullIndexed(null); - ModelFullIndexed child = new ModelFullIndexed(null); - Integer parentId = 73; - Integer childId = 92; - model.setId(parentId); - child.setId(childId); - model.addSubmodelConnection(new ModelSubmodelConnection(child, SubmodelType.DOWNSTREAM_TARGETS)); - - assertNull(model.getSubmodelById(543543)); - assertNull(model.getSubmodelById((String) null)); - assertNull(model.getSubmodelById((Integer) null)); - assertEquals(model, model.getSubmodelById(parentId + "")); - assertEquals(child, model.getSubmodelById(childId + "")); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + ModelFullIndexed model = new ModelFullIndexed(null); + ModelFullIndexed child = new ModelFullIndexed(null); + Integer parentId = 73; + Integer childId = 92; + model.setId(parentId); + child.setId(childId); + model.addSubmodelConnection(new ModelSubmodelConnection(child, SubmodelType.DOWNSTREAM_TARGETS)); + + assertNull(model.getSubmodelById(543543)); + assertNull(model.getSubmodelById((String) null)); + assertNull(model.getSubmodelById((Integer) null)); + assertEquals(model, model.getSubmodelById(parentId + "")); + assertEquals(child, model.getSubmodelById(childId + "")); } @Test public void testGetSubmodelByConnectionName() { - try { - ModelFullIndexed model = new ModelFullIndexed(null); - ModelFullIndexed child = new ModelFullIndexed(null); - String name = "bla"; - model.addSubmodelConnection(new ModelSubmodelConnection(child, SubmodelType.DOWNSTREAM_TARGETS, name)); + ModelFullIndexed model = new ModelFullIndexed(null); + ModelFullIndexed child = new ModelFullIndexed(null); + String name = "bla"; + model.addSubmodelConnection(new ModelSubmodelConnection(child, SubmodelType.DOWNSTREAM_TARGETS, name)); - assertNull(model.getSubmodelByConnectionName(null)); - assertNull(model.getSubmodelByConnectionName("basdkjas")); - assertEquals(child, model.getSubmodelByConnectionName(name)); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertNull(model.getSubmodelByConnectionName(null)); + assertNull(model.getSubmodelByConnectionName("basdkjas")); + assertEquals(child, model.getSubmodelByConnectionName(name)); } @Test public void testAddReactions() { - try { - ModelFullIndexed model = new ModelFullIndexed(null); - Reaction reaction = new Reaction(); - reaction.setIdReaction("b"); - List<Reaction> reactions = new ArrayList<>(); - reactions.add(reaction); - Reaction reaction2 = new Reaction(); - reaction2.setIdReaction("a"); - reactions.add(reaction2); + ModelFullIndexed model = new ModelFullIndexed(null); + Reaction reaction = new Reaction(); + reaction.setIdReaction("b"); + List<Reaction> reactions = new ArrayList<>(); + reactions.add(reaction); + Reaction reaction2 = new Reaction(); + reaction2.setIdReaction("a"); + reactions.add(reaction2); - model.addReactions(reactions); + model.addReactions(reactions); - assertTrue(model.getReactions().contains(reaction)); + assertTrue(model.getReactions().contains(reaction)); - model.removeReaction(reaction2); + model.removeReaction(reaction2); - assertEquals(1, model.getReactions().size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(1, model.getReactions().size()); } @Test public void testSubmodels() { - try { - ModelFullIndexed model = new ModelFullIndexed(null); - ModelFullIndexed child = new ModelFullIndexed(null); - model.addSubmodelConnection(new ModelSubmodelConnection(child, SubmodelType.DOWNSTREAM_TARGETS)); - - assertTrue(model.getSubmodels().contains(child)); + ModelFullIndexed model = new ModelFullIndexed(null); + ModelFullIndexed child = new ModelFullIndexed(null); + model.addSubmodelConnection(new ModelSubmodelConnection(child, SubmodelType.DOWNSTREAM_TARGETS)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertTrue(model.getSubmodels().contains(child)); } @Test public void testAddMiriam() { - try { - ModelFullIndexed model = new ModelFullIndexed(null); - model.addMiriamData(new MiriamData()); - model.addMiriamData(new MiriamData(MiriamType.CHEBI, "CHEBI:12345")); + ModelFullIndexed model = new ModelFullIndexed(null); + model.addMiriamData(new MiriamData()); + model.addMiriamData(new MiriamData(MiriamType.CHEBI, "CHEBI:12345")); - assertEquals(2, model.getMiriamData().size()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(2, model.getMiriamData().size()); } @Test public void testGetters() { - try { - Model model = new ModelFullIndexed(null); + Model model = new ModelFullIndexed(null); double width = 12.0; int widthInt = 12; @@ -701,41 +500,30 @@ public class ModelFullIndexedTest { model.setHeight(heightInt); assertEquals(height, model.getHeight(), Configuration.EPSILON); - model.setElements(elements); - assertEquals(elements, model.getElements()); - model.setZoomLevels(zoomLevels); - assertEquals(zoomLevels, model.getZoomLevels()); - model.setTileSize(tileSize); - assertEquals(tileSize, model.getTileSize()); - model.setIdModel(idModel); - assertEquals(idModel, model.getIdModel()); - - assertNotNull(model.getParentModels()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + model.setElements(elements); + assertEquals(elements, model.getElements()); + model.setZoomLevels(zoomLevels); + assertEquals(zoomLevels, model.getZoomLevels()); + model.setTileSize(tileSize); + assertEquals(tileSize, model.getTileSize()); + model.setIdModel(idModel); + assertEquals(idModel, model.getIdModel()); + assertNotNull(model.getParentModels()); } @Test public void testGetAnnotatedObjects() { - try { - String reactionId = "id_r"; - ModelFullIndexed model = new ModelFullIndexed(null); - Reaction reaction = new Reaction(); - reaction.setIdReaction(reactionId); - model.addReaction(reaction); - Species protein = new GenericProtein("2"); - model.addElement(protein); - - Collection<BioEntity> obj = model.getBioEntities(); - assertEquals(2, obj.size()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String reactionId = "id_r"; + ModelFullIndexed model = new ModelFullIndexed(null); + Reaction reaction = new Reaction(); + reaction.setIdReaction(reactionId); + model.addReaction(reaction); + Species protein = new GenericProtein("2"); + model.addElement(protein); + + Collection<BioEntity> obj = model.getBioEntities(); + assertEquals(2, obj.size()); } } diff --git a/model/src/test/java/lcsb/mapviewer/model/map/model/ModelSubmodelConnectionComparatorTest.java b/model/src/test/java/lcsb/mapviewer/model/map/model/ModelSubmodelConnectionComparatorTest.java index d20df8137c46b42f0bb535169d2b122d168cff98..90dc66bf241e8bcceb323117738fa314b2673617 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/model/ModelSubmodelConnectionComparatorTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/model/ModelSubmodelConnectionComparatorTest.java @@ -1,110 +1,95 @@ package lcsb.mapviewer.model.map.model; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.Assert.*; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; +import org.mockito.Mockito; +import lcsb.mapviewer.ModelTestFunctions; import lcsb.mapviewer.model.map.compartment.Compartment; import lcsb.mapviewer.model.map.layout.graphics.Layer; import lcsb.mapviewer.model.map.reaction.Reaction; import lcsb.mapviewer.model.map.species.GenericProtein; import lcsb.mapviewer.model.map.species.Species; -public class ModelSubmodelConnectionComparatorTest { +public class ModelSubmodelConnectionComparatorTest extends ModelTestFunctions { - ModelSubmodelConnectionComparator comparator = new ModelSubmodelConnectionComparator(); + ModelSubmodelConnectionComparator comparator = new ModelSubmodelConnectionComparator(); - @Before - public void setUp() throws Exception { - } + @Before + public void setUp() throws Exception { + } - @After - public void tearDown() throws Exception { - } + @After + public void tearDown() throws Exception { + } - @Test - public void testEquals() throws Exception { - try { - ModelSubmodelConnection connectionA = createConnection(); - ModelSubmodelConnection connectionB = createConnection(); + @Test + public void testEquals() throws Exception { + ModelSubmodelConnection connectionA = createConnection(); + ModelSubmodelConnection connectionB = createConnection(); - assertEquals(0, comparator.compare(new ModelSubmodelConnection(), new ModelSubmodelConnection())); - assertEquals(0, comparator.compare(connectionA, connectionB)); - assertEquals(0, comparator.compare(connectionA, connectionA)); - assertEquals(0, comparator.compare(null, null)); + assertEquals(0, comparator.compare(new ModelSubmodelConnection(), new ModelSubmodelConnection())); + assertEquals(0, comparator.compare(connectionA, connectionB)); + assertEquals(0, comparator.compare(connectionA, connectionA)); + assertEquals(0, comparator.compare(null, null)); + } - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } + @Test + public void testDifferent() throws Exception { + ModelSubmodelConnection connectionA = createConnection(); + ModelSubmodelConnection connectionB = createConnection(); - @Test - public void testDifferent() throws Exception { - try { - ModelSubmodelConnection connectionA = createConnection(); - ModelSubmodelConnection connectionB = createConnection(); + assertTrue(comparator.compare(null, connectionB) != 0); + assertTrue(comparator.compare(connectionA, null) != 0); - assertTrue(comparator.compare(null, connectionB) != 0); - assertTrue(comparator.compare(connectionA, null) != 0); + connectionA.getParentModel().setNotes("QQWECS"); + assertTrue(comparator.compare(connectionA, connectionB) != 0); + assertTrue(comparator.compare(connectionB, connectionA) != 0); - connectionA.getParentModel().setNotes("QQWECS"); - assertTrue(comparator.compare(connectionA, connectionB) != 0); - assertTrue(comparator.compare(connectionB, connectionA) != 0); + connectionA = createConnection(); + connectionB = createConnection(); - connectionA = createConnection(); - connectionB = createConnection(); + connectionA.setParentModel((ModelData) null); - connectionA.setParentModel((ModelData) null); + assertTrue(comparator.compare(connectionA, connectionB) != 0); + assertTrue(comparator.compare(connectionB, connectionA) != 0); - assertTrue(comparator.compare(connectionA, connectionB) != 0); - assertTrue(comparator.compare(connectionB, connectionA) != 0); + connectionA = createConnection(); + connectionB = createConnection(); - connectionA = createConnection(); - connectionB = createConnection(); + connectionA.setType(SubmodelType.UNKNOWN); - connectionA.setType(SubmodelType.UNKNOWN); + assertTrue(comparator.compare(connectionA, connectionB) != 0); + assertTrue(comparator.compare(connectionB, connectionA) != 0); - assertTrue(comparator.compare(connectionA, connectionB) != 0); - assertTrue(comparator.compare(connectionB, connectionA) != 0); + assertTrue(comparator.compare(connectionB, Mockito.spy(ModelSubmodelConnection.class)) != 0); + } - assertTrue(comparator.compare(connectionB, new ModelSubmodelConnection() { - private static final long serialVersionUID = 1L; - }) != 0); + private Model getModel() { + Model model = new ModelFullIndexed(null); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } + model.setNotes("Some description"); - private Model getModel() { - Model model = new ModelFullIndexed(null); + Species species = new GenericProtein("a_id"); + species.setName("ad"); + model.addElement(species); - model.setNotes("Some description"); + model.addElement(new Compartment("default")); - Species species = new GenericProtein("a_id"); - species.setName("ad"); - model.addElement(species); + Layer layer = new Layer(); + layer.setName("layer name"); + model.addLayer(layer); - model.addElement(new Compartment("default")); + model.addReaction(new Reaction()); + return model; + } - Layer layer = new Layer(); - layer.setName("layer name"); - model.addLayer(layer); - - model.addReaction(new Reaction()); - return model; - } - - private ModelSubmodelConnection createConnection() { - ModelSubmodelConnection result = new ModelSubmodelConnection(getModel(), SubmodelType.DOWNSTREAM_TARGETS); - result.setName("name A"); - result.setParentModel(getModel()); - return result; - } + private ModelSubmodelConnection createConnection() { + ModelSubmodelConnection result = new ModelSubmodelConnection(getModel(), SubmodelType.DOWNSTREAM_TARGETS); + result.setName("name A"); + result.setParentModel(getModel()); + return result; + } } diff --git a/model/src/test/java/lcsb/mapviewer/model/map/model/ModelSubmodelConnectionTest.java b/model/src/test/java/lcsb/mapviewer/model/map/model/ModelSubmodelConnectionTest.java index 5652e39481e3604919b756173952f6c0b9309662..ad99e667a2178fd1d4df9be20d6b9090facc21a0 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/model/ModelSubmodelConnectionTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/model/ModelSubmodelConnectionTest.java @@ -1,102 +1,67 @@ package lcsb.mapviewer.model.map.model; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; +import org.mockito.Mockito; +import lcsb.mapviewer.ModelTestFunctions; import lcsb.mapviewer.common.exception.NotImplementedException; - -public class ModelSubmodelConnectionTest { - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testSerialization() { - try { - SerializationUtils.serialize(new ModelSubmodelConnection()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testConstructor() { - try { - ModelSubmodelConnection connection = new ModelSubmodelConnection(new ModelFullIndexed(null), SubmodelType.DOWNSTREAM_TARGETS, "str"); - ModelSubmodelConnection connection2 = new ModelSubmodelConnection(connection); - assertNotNull(connection2); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testConstructor2() { - try { - ModelSubmodelConnection connection = new ModelSubmodelConnection(new ModelFullIndexed(null), SubmodelType.DOWNSTREAM_TARGETS, "str"); - - assertNotNull(connection); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testCopy() { - try { - ModelSubmodelConnection connection = new ModelSubmodelConnection(new ModelFullIndexed(null), SubmodelType.DOWNSTREAM_TARGETS, "str"); - ModelSubmodelConnection degraded = connection.copy(); - assertNotNull(degraded); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testGetters() { - try { - ModelSubmodelConnection connection = new ModelSubmodelConnection(new ModelFullIndexed(null), SubmodelType.DOWNSTREAM_TARGETS, "str"); - - int id = 30; - connection.setId(id); - assertEquals(id, connection.getId()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testInvalidCopy() { - try { - new ModelSubmodelConnection() { - - /** - * - */ - private static final long serialVersionUID = 1L; - }.copy(); - fail("Exception expected"); - } catch (NotImplementedException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } +import lcsb.mapviewer.model.map.layout.graphics.Layer; + +public class ModelSubmodelConnectionTest extends ModelTestFunctions { + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testSerialization() { + SerializationUtils.serialize(new ModelSubmodelConnection()); + } + + @Test + public void testConstructor() { + ModelSubmodelConnection connection = new ModelSubmodelConnection(new ModelFullIndexed(null), + SubmodelType.DOWNSTREAM_TARGETS, "str"); + ModelSubmodelConnection connection2 = new ModelSubmodelConnection(connection); + assertNotNull(connection2); + } + + @Test + public void testConstructor2() { + ModelSubmodelConnection connection = new ModelSubmodelConnection(new ModelFullIndexed(null), + SubmodelType.DOWNSTREAM_TARGETS, "str"); + + assertNotNull(connection); + } + + @Test + public void testCopy() { + ModelSubmodelConnection connection = new ModelSubmodelConnection(new ModelFullIndexed(null), + SubmodelType.DOWNSTREAM_TARGETS, "str"); + ModelSubmodelConnection degraded = connection.copy(); + assertNotNull(degraded); + } + + @Test + public void testGetters() { + ModelSubmodelConnection connection = new ModelSubmodelConnection(new ModelFullIndexed(null), + SubmodelType.DOWNSTREAM_TARGETS, "str"); + + int id = 30; + connection.setId(id); + assertEquals(id, connection.getId()); + } + + @Test(expected = NotImplementedException.class) + public void testInvalidCopy() { + Mockito.spy(ModelSubmodelConnection.class).copy(); + } } diff --git a/model/src/test/java/lcsb/mapviewer/model/map/model/ModelTest.java b/model/src/test/java/lcsb/mapviewer/model/map/model/ModelTest.java index a399e706f8e3d1476cb9a387b40415e49f215896..1b671a945c62137fd5eab9d179dd7352caa9fb79 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/model/ModelTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/model/ModelTest.java @@ -1,229 +1,189 @@ package lcsb.mapviewer.model.map.model; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import java.util.List; import java.util.Set; -import org.apache.logging.log4j.*; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.junit.*; -import lcsb.mapviewer.model.map.BioEntity; -import lcsb.mapviewer.model.map.MiriamData; -import lcsb.mapviewer.model.map.MiriamRelationType; -import lcsb.mapviewer.model.map.MiriamType; +import lcsb.mapviewer.ModelTestFunctions; +import lcsb.mapviewer.model.map.*; import lcsb.mapviewer.model.map.compartment.Compartment; import lcsb.mapviewer.model.map.layout.graphics.Layer; import lcsb.mapviewer.model.map.reaction.Reaction; -import lcsb.mapviewer.model.map.species.Complex; -import lcsb.mapviewer.model.map.species.Element; -import lcsb.mapviewer.model.map.species.GenericProtein; -import lcsb.mapviewer.model.map.species.Species; - -public class ModelTest { - Logger logger = LogManager.getLogger(ModelTest.class); - - private Species species; - - private Complex complex; - private Model model; - - @Before - public void setUp() throws Exception { - model = new ModelFullIndexed(null); - - species = new GenericProtein("sa1"); - - complex = new Complex("sa2"); - - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testAddElement() { - try { - model.addElement(species); - Element element = model.getElementByElementId(species.getElementId()); - assertNotNull(element); - element = model.getElementByElementId(species.getElementId() + "blbla"); - assertNull(element); - - } catch (Exception e) { - e.printStackTrace(); - fail("Unknown exception occured"); - } - } - - @Test - public void testGetElements() { - try { - Set<Element> elements = model.getElements(); - assertEquals(0, elements.size()); - model.addElement(species); - assertEquals(1, elements.size()); - - Element element = model.getElementByElementId(species.getElementId()); - assertNotNull(element); - element = model.getElementByElementId(species.getElementId() + "blbla"); - assertNull(element); - - element = model.getElementByElementId(complex.getElementId()); - assertNull(element); - - model.addElement(complex); - assertEquals(2, elements.size()); - element = model.getElementByElementId(complex.getElementId()); - assertNotNull(element); - - } catch (Exception e) { - e.printStackTrace(); - fail("Unknown exception occured"); - } - } - - @Test - public void testAddReaction() { - try { - Reaction reaction = new Reaction(); - model.addReaction(reaction); - assertNotNull(model.getReactions()); - assertEquals(1, model.getReactions().size()); - } catch (Exception e) { - e.printStackTrace(); - fail("Unknown exception occured"); - } - } - - @Test - public void testAddLayer() { - try { - Layer layer = new Layer(); - layer.setLayerId("bla id"); - Set<Layer> list = model.getLayers(); - assertEquals(0, list.size()); - model.addLayer(layer); - list = model.getLayers(); - assertEquals(1, list.size()); - } catch (Exception e) { - e.printStackTrace(); - fail("Unknown exception occured"); - } - } - - @Test - public void testElementsByAnnotation() { - try { - model = createModel(); - - Set<BioEntity> elements = model.getElementsByAnnotation(new MiriamData(MiriamRelationType.BQ_MODEL_IS, MiriamType.CHEMBL_TARGET, "CHEMBL12345")); - assertNotNull(elements); - assertEquals(1, elements.size()); - BioEntity element = elements.iterator().next(); - assertTrue(element instanceof Species); - Species species = (Species) element; - assertEquals("s5", species.getName()); - - elements = model.getElementsByAnnotation(new MiriamData(MiriamRelationType.BQ_MODEL_IS, MiriamType.CHEBI, "CHEBI:12")); - assertNotNull(elements); - assertEquals(1, elements.size()); - element = elements.iterator().next(); - assertTrue(element instanceof Compartment); - Compartment compartment = (Compartment) element; - assertEquals("c1", compartment.getName()); - - elements = model.getElementsByAnnotation(new MiriamData(MiriamRelationType.BQ_MODEL_IS, MiriamType.CHEBI, "CHEBI:12234")); - assertNotNull(elements); - assertEquals(0, elements.size()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - private Model createModel() { - Model model = new ModelFullIndexed(null); - - Species protein = new GenericProtein("sa1"); - protein.setName("s1"); - model.addElement(protein); - - Species protein2 = new GenericProtein("sa2"); - protein2.setName("s1"); - model.addElement(protein2); - - Species protein3 = new GenericProtein("sa3"); - protein3.setName("s1"); - model.addElement(protein3); - - Species protein4 = new GenericProtein("sa4"); - protein4.setName("s5"); - protein4.addMiriamData(new MiriamData(MiriamRelationType.BQ_MODEL_IS, MiriamType.CHEMBL_TARGET, "CHEMBL12345")); - model.addElement(protein4); - - Compartment compartment = new Compartment("cca"); - compartment.setName("c1"); - compartment.addMiriamData(new MiriamData(MiriamRelationType.BQ_MODEL_IS, MiriamType.CHEBI, "CHEBI:12")); - - model.addElement(compartment); - - return model; - } - - @Test - public void testSorting() throws Exception { - try { - Model model = new ModelFullIndexed(null); - - Species species = new GenericProtein("2"); - species.setWidth(100); - species.setHeight(100); - model.addElement(species); - - species = new GenericProtein("3"); - species.setWidth(10); - species.setHeight(10); - model.addElement(species); - - species = new GenericProtein("4"); - species.setWidth(200); - species.setHeight(100); - model.addElement(species); - - Compartment compartment = new Compartment("5"); - compartment.setWidth(10); - compartment.setHeight(20); - model.addElement(compartment); - - compartment = new Compartment("6"); - compartment.setWidth(100); - compartment.setHeight(200); - model.addElement(compartment); - - compartment = new Compartment("7"); - compartment.setWidth(20); - compartment.setHeight(30); - model.addElement(compartment); - - List<Element> sortedElements = model.getElementsSortedBySize(); - if (sortedElements.size() > 0) { - double last = (sortedElements.get(0)).getHeight() * (sortedElements.get(0)).getWidth(); - for (Element a : sortedElements) { - assertTrue(last >= a.getHeight() * a.getWidth()); - } - } - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } +import lcsb.mapviewer.model.map.species.*; + +public class ModelTest extends ModelTestFunctions { + Logger logger = LogManager.getLogger(ModelTest.class); + + private Species species; + + private Complex complex; + private Model model; + + @Before + public void setUp() throws Exception { + model = new ModelFullIndexed(null); + + species = new GenericProtein("sa1"); + + complex = new Complex("sa2"); + + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testAddElement() { + model.addElement(species); + Element element = model.getElementByElementId(species.getElementId()); + assertNotNull(element); + element = model.getElementByElementId(species.getElementId() + "blbla"); + assertNull(element); + } + + @Test + public void testGetElements() { + Set<Element> elements = model.getElements(); + assertEquals(0, elements.size()); + model.addElement(species); + assertEquals(1, elements.size()); + + Element element = model.getElementByElementId(species.getElementId()); + assertNotNull(element); + element = model.getElementByElementId(species.getElementId() + "blbla"); + assertNull(element); + + element = model.getElementByElementId(complex.getElementId()); + assertNull(element); + + model.addElement(complex); + assertEquals(2, elements.size()); + element = model.getElementByElementId(complex.getElementId()); + assertNotNull(element); + } + + @Test + public void testAddReaction() { + Reaction reaction = new Reaction(); + model.addReaction(reaction); + assertNotNull(model.getReactions()); + assertEquals(1, model.getReactions().size()); + } + + @Test + public void testAddLayer() { + Layer layer = new Layer(); + layer.setLayerId("bla id"); + Set<Layer> list = model.getLayers(); + assertEquals(0, list.size()); + model.addLayer(layer); + list = model.getLayers(); + assertEquals(1, list.size()); + } + + @Test + public void testElementsByAnnotation() { + model = createModel(); + + Set<BioEntity> elements = model.getElementsByAnnotation( + new MiriamData(MiriamRelationType.BQ_MODEL_IS, MiriamType.CHEMBL_TARGET, "CHEMBL12345")); + assertNotNull(elements); + assertEquals(1, elements.size()); + BioEntity element = elements.iterator().next(); + assertTrue(element instanceof Species); + Species species = (Species) element; + assertEquals("s5", species.getName()); + + elements = model + .getElementsByAnnotation(new MiriamData(MiriamRelationType.BQ_MODEL_IS, MiriamType.CHEBI, "CHEBI:12")); + assertNotNull(elements); + assertEquals(1, elements.size()); + element = elements.iterator().next(); + assertTrue(element instanceof Compartment); + Compartment compartment = (Compartment) element; + assertEquals("c1", compartment.getName()); + + elements = model + .getElementsByAnnotation(new MiriamData(MiriamRelationType.BQ_MODEL_IS, MiriamType.CHEBI, "CHEBI:12234")); + assertNotNull(elements); + assertEquals(0, elements.size()); + } + + private Model createModel() { + Model model = new ModelFullIndexed(null); + + Species protein = new GenericProtein("sa1"); + protein.setName("s1"); + model.addElement(protein); + + Species protein2 = new GenericProtein("sa2"); + protein2.setName("s1"); + model.addElement(protein2); + + Species protein3 = new GenericProtein("sa3"); + protein3.setName("s1"); + model.addElement(protein3); + + Species protein4 = new GenericProtein("sa4"); + protein4.setName("s5"); + protein4.addMiriamData(new MiriamData(MiriamRelationType.BQ_MODEL_IS, MiriamType.CHEMBL_TARGET, "CHEMBL12345")); + model.addElement(protein4); + + Compartment compartment = new Compartment("cca"); + compartment.setName("c1"); + compartment.addMiriamData(new MiriamData(MiriamRelationType.BQ_MODEL_IS, MiriamType.CHEBI, "CHEBI:12")); + + model.addElement(compartment); + + return model; + } + + @Test + public void testSorting() throws Exception { + Model model = new ModelFullIndexed(null); + + Species species = new GenericProtein("2"); + species.setWidth(100); + species.setHeight(100); + model.addElement(species); + + species = new GenericProtein("3"); + species.setWidth(10); + species.setHeight(10); + model.addElement(species); + + species = new GenericProtein("4"); + species.setWidth(200); + species.setHeight(100); + model.addElement(species); + + Compartment compartment = new Compartment("5"); + compartment.setWidth(10); + compartment.setHeight(20); + model.addElement(compartment); + + compartment = new Compartment("6"); + compartment.setWidth(100); + compartment.setHeight(200); + model.addElement(compartment); + + compartment = new Compartment("7"); + compartment.setWidth(20); + compartment.setHeight(30); + model.addElement(compartment); + + List<Element> sortedElements = model.getElementsSortedBySize(); + if (sortedElements.size() > 0) { + double last = (sortedElements.get(0)).getHeight() * (sortedElements.get(0)).getWidth(); + for (Element a : sortedElements) { + assertTrue(last >= a.getHeight() * a.getWidth()); + } + } + } } diff --git a/model/src/test/java/lcsb/mapviewer/model/map/model/SubmodelConnectionComparatorTest.java b/model/src/test/java/lcsb/mapviewer/model/map/model/SubmodelConnectionComparatorTest.java index df1ff90e5b2878cd37660b09844721bd622b8683..88330e931c7b2a3085edb65e4474b3fa9982776b 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/model/SubmodelConnectionComparatorTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/model/SubmodelConnectionComparatorTest.java @@ -1,13 +1,11 @@ package lcsb.mapviewer.model.map.model; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; +import org.mockito.Mockito; +import lcsb.mapviewer.ModelTestFunctions; import lcsb.mapviewer.common.exception.NotImplementedException; import lcsb.mapviewer.model.map.compartment.Compartment; import lcsb.mapviewer.model.map.layout.graphics.Layer; @@ -15,175 +13,137 @@ import lcsb.mapviewer.model.map.reaction.Reaction; import lcsb.mapviewer.model.map.species.GenericProtein; import lcsb.mapviewer.model.map.species.Species; -public class SubmodelConnectionComparatorTest { - - SubmodelConnectionComparator comparator = new SubmodelConnectionComparator(); - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testEquals() throws Exception { - try { - SubmodelConnection connectionA = createConnection(); - SubmodelConnection connectionB = createConnection(); +public class SubmodelConnectionComparatorTest extends ModelTestFunctions { - assertEquals(0, comparator.compare(new ElementSubmodelConnection(), new ElementSubmodelConnection())); - assertEquals(0, comparator.compare(new ModelSubmodelConnection(), new ModelSubmodelConnection())); - assertEquals(0, comparator.compare(connectionA, connectionB)); - assertEquals(0, comparator.compare(connectionA, connectionA)); - assertEquals(0, comparator.compare(null, null)); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testInvalid() throws Exception { - try { - class Tmp extends SubmodelConnection { - private static final long serialVersionUID = 1L; - - @Override - public SubmodelConnection copy() { - return null; - } - } - ; - Tmp connectionA = new Tmp(); - Tmp connectionB = new Tmp(); - - comparator.compare(connectionA, connectionB); - comparator.compare(connectionA, connectionA); - - fail("Exception expected"); - } catch (NotImplementedException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testInternal() throws Exception { - try { - SubmodelConnection connectionA = createConnection(); - SubmodelConnection connectionB = createConnection(); - - assertTrue(comparator.internalCompare(null, connectionB) != 0); - assertTrue(comparator.internalCompare(connectionA, null) != 0); - assertEquals(0, comparator.internalCompare(null, null)); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testDifferent() throws Exception { - try { - SubmodelConnection connectionA = createConnection(); - SubmodelConnection connectionB = createConnection(); - - assertTrue(comparator.compare(null, connectionB) != 0); - assertTrue(comparator.compare(connectionA, null) != 0); - - connectionA.setName("AA"); - assertTrue(comparator.compare(connectionA, connectionB) != 0); - assertTrue(comparator.compare(connectionB, connectionA) != 0); - - connectionA = createConnection(); - connectionB = createConnection(); - - connectionA.setType(null); - - assertTrue(comparator.compare(connectionA, connectionB) != 0); - assertTrue(comparator.compare(connectionB, connectionA) != 0); - - connectionA = createConnection(); - connectionB = createConnection(); - - connectionA.setType(SubmodelType.PATHWAY); - - assertTrue(comparator.compare(connectionA, connectionB) != 0); - assertTrue(comparator.compare(connectionB, connectionA) != 0); - - connectionA = createConnection(); - connectionB = createConnection(); - - connectionA.getSubmodel().setNotes("ASD acd"); - - assertTrue(comparator.compare(connectionA, connectionB) != 0); - assertTrue(comparator.compare(connectionB, connectionA) != 0); - - connectionA = createConnection(); - connectionB = createConnection(); - connectionB.setSubmodel(new ModelFullIndexed(null)); - assertTrue(comparator.compare(connectionA, connectionB) != 0); - assertTrue(comparator.compare(connectionB, connectionA) != 0); - - assertTrue(comparator.compare(connectionB, new SubmodelConnection() { - private static final long serialVersionUID = 1L; - - @Override - public SubmodelConnection copy() { - return null; - } - }) != 0); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testDifferent2() throws Exception { - try { - ElementSubmodelConnection connectionA = new ElementSubmodelConnection(); - ElementSubmodelConnection connectionB = new ElementSubmodelConnection(); - - connectionB.setSubmodel(new ModelFullIndexed(null)); - assertTrue(comparator.compare(connectionA, connectionB) != 0); - assertTrue(comparator.compare(connectionB, connectionA) != 0); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - private Model getModel() { - Model model = new ModelFullIndexed(null); - - model.setNotes("Some description"); - - Species protein = new GenericProtein("a_id"); - protein.setName("ad"); - protein.setElementId("a_id"); - model.addElement(protein); - - model.addElement(new Compartment("default")); - - Layer layer = new Layer(); - layer.setName("layer name"); - model.addLayer(layer); + SubmodelConnectionComparator comparator = new SubmodelConnectionComparator(); - model.addReaction(new Reaction()); - return model; - } + @Before + public void setUp() throws Exception { + } - private ElementSubmodelConnection createConnection() { - ElementSubmodelConnection result = new ElementSubmodelConnection(getModel(), SubmodelType.DOWNSTREAM_TARGETS); - result.setName("name A"); - return result; - } + @After + public void tearDown() throws Exception { + } + + @Test + public void testEquals() throws Exception { + SubmodelConnection connectionA = createConnection(); + SubmodelConnection connectionB = createConnection(); + + assertEquals(0, comparator.compare(new ElementSubmodelConnection(), new ElementSubmodelConnection())); + assertEquals(0, comparator.compare(new ModelSubmodelConnection(), new ModelSubmodelConnection())); + assertEquals(0, comparator.compare(connectionA, connectionB)); + assertEquals(0, comparator.compare(connectionA, connectionA)); + assertEquals(0, comparator.compare(null, null)); + } + + @Test(expected = NotImplementedException.class) + public void testInvalid() throws Exception { + class Tmp extends SubmodelConnection { + private static final long serialVersionUID = 1L; + + @Override + public SubmodelConnection copy() { + return null; + } + } + ; + Tmp connectionA = new Tmp(); + Tmp connectionB = new Tmp(); + + comparator.compare(connectionA, connectionB); + comparator.compare(connectionA, connectionA); + } + + @Test + public void testInternal() throws Exception { + SubmodelConnection connectionA = createConnection(); + SubmodelConnection connectionB = createConnection(); + + assertTrue(comparator.internalCompare(null, connectionB) != 0); + assertTrue(comparator.internalCompare(connectionA, null) != 0); + assertEquals(0, comparator.internalCompare(null, null)); + } + + @Test + public void testDifferent() throws Exception { + SubmodelConnection connectionA = createConnection(); + SubmodelConnection connectionB = createConnection(); + + assertTrue(comparator.compare(null, connectionB) != 0); + assertTrue(comparator.compare(connectionA, null) != 0); + + connectionA.setName("AA"); + assertTrue(comparator.compare(connectionA, connectionB) != 0); + assertTrue(comparator.compare(connectionB, connectionA) != 0); + + connectionA = createConnection(); + connectionB = createConnection(); + + connectionA.setType(null); + + assertTrue(comparator.compare(connectionA, connectionB) != 0); + assertTrue(comparator.compare(connectionB, connectionA) != 0); + + connectionA = createConnection(); + connectionB = createConnection(); + + connectionA.setType(SubmodelType.PATHWAY); + + assertTrue(comparator.compare(connectionA, connectionB) != 0); + assertTrue(comparator.compare(connectionB, connectionA) != 0); + + connectionA = createConnection(); + connectionB = createConnection(); + + connectionA.getSubmodel().setNotes("ASD acd"); + + assertTrue(comparator.compare(connectionA, connectionB) != 0); + assertTrue(comparator.compare(connectionB, connectionA) != 0); + + connectionA = createConnection(); + connectionB = createConnection(); + connectionB.setSubmodel(new ModelFullIndexed(null)); + assertTrue(comparator.compare(connectionA, connectionB) != 0); + assertTrue(comparator.compare(connectionB, connectionA) != 0); + + assertTrue(comparator.compare(connectionB, Mockito.spy(SubmodelConnection.class)) != 0); + } + + @Test + public void testDifferent2() throws Exception { + ElementSubmodelConnection connectionA = new ElementSubmodelConnection(); + ElementSubmodelConnection connectionB = new ElementSubmodelConnection(); + + connectionB.setSubmodel(new ModelFullIndexed(null)); + assertTrue(comparator.compare(connectionA, connectionB) != 0); + assertTrue(comparator.compare(connectionB, connectionA) != 0); + } + + private Model getModel() { + Model model = new ModelFullIndexed(null); + + model.setNotes("Some description"); + + Species protein = new GenericProtein("a_id"); + protein.setName("ad"); + protein.setElementId("a_id"); + model.addElement(protein); + + model.addElement(new Compartment("default")); + + Layer layer = new Layer(); + layer.setName("layer name"); + model.addLayer(layer); + + model.addReaction(new Reaction()); + return model; + } + + private ElementSubmodelConnection createConnection() { + ElementSubmodelConnection result = new ElementSubmodelConnection(getModel(), SubmodelType.DOWNSTREAM_TARGETS); + result.setName("name A"); + return result; + } } diff --git a/model/src/test/java/lcsb/mapviewer/model/map/modifier/CatalysisTest.java b/model/src/test/java/lcsb/mapviewer/model/map/modifier/CatalysisTest.java index 44222b739ee23ea46d6b64f531a34061ccee5d98..5b149190ac8f9611759e089f5048bff2c9ec998c 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/modifier/CatalysisTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/modifier/CatalysisTest.java @@ -1,19 +1,17 @@ package lcsb.mapviewer.model.map.modifier; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.mockito.Mockito; +import lcsb.mapviewer.ModelTestFunctions; import lcsb.mapviewer.common.exception.NotImplementedException; import lcsb.mapviewer.model.graphics.PolylineData; import lcsb.mapviewer.model.map.species.AntisenseRna; -public class CatalysisTest { +public class CatalysisTest extends ModelTestFunctions { @Before public void setUp() throws Exception { @@ -25,60 +23,33 @@ public class CatalysisTest { @Test public void testSerialization() { - try { - SerializationUtils.serialize(new Catalysis()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + SerializationUtils.serialize(new Catalysis()); } @Test public void testConstructor() { - try { - Catalysis modifier = new Catalysis(new AntisenseRna("unk_id")); - assertNotNull(modifier); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Catalysis modifier = new Catalysis(new AntisenseRna("unk_id")); + assertNotNull(modifier); } @Test public void testConstructor2() { - try { - Catalysis modifier = new Catalysis(new AntisenseRna("unk_id")); - modifier.setLine(new PolylineData()); - Catalysis modifier2 = new Catalysis(modifier); - assertNotNull(modifier2); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Catalysis modifier = new Catalysis(new AntisenseRna("unk_id")); + modifier.setLine(new PolylineData()); + Catalysis modifier2 = new Catalysis(modifier); + assertNotNull(modifier2); } @Test public void testCopy() { - try { - Catalysis modifier = new Catalysis(new AntisenseRna("unk_id")); - modifier.setLine(new PolylineData()); - Catalysis modifier2 = modifier.copy(); - assertNotNull(modifier2); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Catalysis modifier = new Catalysis(new AntisenseRna("unk_id")); + modifier.setLine(new PolylineData()); + Catalysis modifier2 = modifier.copy(); + assertNotNull(modifier2); } - @Test + @Test(expected = NotImplementedException.class) public void testCopyInvalid() { - try { - Mockito.mock(Catalysis.class, Mockito.CALLS_REAL_METHODS).copy(); - fail("Exception expected"); - } catch (NotImplementedException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Mockito.mock(Catalysis.class, Mockito.CALLS_REAL_METHODS).copy(); } } diff --git a/model/src/test/java/lcsb/mapviewer/model/map/modifier/InhibitionTest.java b/model/src/test/java/lcsb/mapviewer/model/map/modifier/InhibitionTest.java index c02610ebf6e49b703c77860d86d9561198265959..52775701ecfccd5c95e9e6ee754aead67966330f 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/modifier/InhibitionTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/modifier/InhibitionTest.java @@ -1,19 +1,17 @@ package lcsb.mapviewer.model.map.modifier; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.mockito.Mockito; +import lcsb.mapviewer.ModelTestFunctions; import lcsb.mapviewer.common.exception.NotImplementedException; import lcsb.mapviewer.model.graphics.PolylineData; import lcsb.mapviewer.model.map.species.GenericProtein; -public class InhibitionTest { +public class InhibitionTest extends ModelTestFunctions { @Before public void setUp() throws Exception { @@ -25,61 +23,34 @@ public class InhibitionTest { @Test public void testSerialization() { - try { - SerializationUtils.serialize(new Inhibition()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + SerializationUtils.serialize(new Inhibition()); } @Test public void testConstructor() { - try { - Inhibition modifier = new Inhibition(new GenericProtein("unk_id")); - assertNotNull(modifier); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Inhibition modifier = new Inhibition(new GenericProtein("unk_id")); + assertNotNull(modifier); } @Test public void testConstructor2() { - try { - Inhibition modifier = new Inhibition(new GenericProtein("unk_id")); - modifier.setLine(new PolylineData()); - Inhibition modifier2 = new Inhibition(modifier); - assertNotNull(modifier2); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Inhibition modifier = new Inhibition(new GenericProtein("unk_id")); + modifier.setLine(new PolylineData()); + Inhibition modifier2 = new Inhibition(modifier); + assertNotNull(modifier2); } @Test public void testCopy() { - try { - Inhibition modifier = new Inhibition(new GenericProtein("unk_id")); - modifier.setLine(new PolylineData()); - Inhibition modifier2 = modifier.copy(); - assertNotNull(modifier2); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Inhibition modifier = new Inhibition(new GenericProtein("unk_id")); + modifier.setLine(new PolylineData()); + Inhibition modifier2 = modifier.copy(); + assertNotNull(modifier2); } - @Test + @Test(expected = NotImplementedException.class) public void testCopyInvalid() { - try { - Mockito.mock(Inhibition.class, Mockito.CALLS_REAL_METHODS).copy(); - fail("Exception expected"); - } catch (NotImplementedException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Mockito.mock(Inhibition.class, Mockito.CALLS_REAL_METHODS).copy(); } } diff --git a/model/src/test/java/lcsb/mapviewer/model/map/modifier/ModulationTest.java b/model/src/test/java/lcsb/mapviewer/model/map/modifier/ModulationTest.java index 22341eec8825df48ab56c4368470c3f4e73e0417..cb0231984aa2c83903dc51b9d880b59133f79f4e 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/modifier/ModulationTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/modifier/ModulationTest.java @@ -1,19 +1,17 @@ package lcsb.mapviewer.model.map.modifier; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.mockito.Mockito; +import lcsb.mapviewer.ModelTestFunctions; import lcsb.mapviewer.common.exception.NotImplementedException; import lcsb.mapviewer.model.graphics.PolylineData; import lcsb.mapviewer.model.map.species.GenericProtein; -public class ModulationTest { +public class ModulationTest extends ModelTestFunctions { @Before public void setUp() throws Exception { @@ -25,61 +23,34 @@ public class ModulationTest { @Test public void testSerialization() { - try { - SerializationUtils.serialize(new Modulation()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + SerializationUtils.serialize(new Modulation()); } @Test public void testConstructor() { - try { - Modulation modifier = new Modulation(new GenericProtein("unk_id")); - assertNotNull(modifier); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Modulation modifier = new Modulation(new GenericProtein("unk_id")); + assertNotNull(modifier); } @Test public void testConstructor2() { - try { - Modulation modifier = new Modulation(new GenericProtein("unk_id")); - modifier.setLine(new PolylineData()); - Modulation modifier2 = new Modulation(modifier); - assertNotNull(modifier2); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Modulation modifier = new Modulation(new GenericProtein("unk_id")); + modifier.setLine(new PolylineData()); + Modulation modifier2 = new Modulation(modifier); + assertNotNull(modifier2); } - @Test + @Test(expected = NotImplementedException.class) public void testCopyInvalid() { - try { - Mockito.mock(Modulation.class, Mockito.CALLS_REAL_METHODS).copy(); - fail("Exception expected"); - } catch (NotImplementedException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Mockito.mock(Modulation.class, Mockito.CALLS_REAL_METHODS).copy(); } @Test public void testCopy() { - try { - Modulation modifier = new Modulation(new GenericProtein("unk_id")); - modifier.setLine(new PolylineData()); - Modulation modifier2 = modifier.copy(); - assertNotNull(modifier2); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Modulation modifier = new Modulation(new GenericProtein("unk_id")); + modifier.setLine(new PolylineData()); + Modulation modifier2 = modifier.copy(); + assertNotNull(modifier2); } } diff --git a/model/src/test/java/lcsb/mapviewer/model/map/modifier/PhysicalStimulationTest.java b/model/src/test/java/lcsb/mapviewer/model/map/modifier/PhysicalStimulationTest.java index 29ae6503fa33604c7bcbe4a579f4a244b0130cfa..e20499a2f326e5e3d878b305ce5da4b10307f1c6 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/modifier/PhysicalStimulationTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/modifier/PhysicalStimulationTest.java @@ -1,19 +1,17 @@ package lcsb.mapviewer.model.map.modifier; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.mockito.Mockito; +import lcsb.mapviewer.ModelTestFunctions; import lcsb.mapviewer.common.exception.NotImplementedException; import lcsb.mapviewer.model.graphics.PolylineData; import lcsb.mapviewer.model.map.species.GenericProtein; -public class PhysicalStimulationTest { +public class PhysicalStimulationTest extends ModelTestFunctions { @Before public void setUp() throws Exception { @@ -25,61 +23,34 @@ public class PhysicalStimulationTest { @Test public void testSerialization() { - try { - SerializationUtils.serialize(new PhysicalStimulation()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + SerializationUtils.serialize(new PhysicalStimulation()); } @Test public void testConstructor() { - try { - PhysicalStimulation modifier = new PhysicalStimulation(new GenericProtein("unk_id")); - assertNotNull(modifier); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + PhysicalStimulation modifier = new PhysicalStimulation(new GenericProtein("unk_id")); + assertNotNull(modifier); } @Test public void testConstructor2() { - try { - PhysicalStimulation modifier = new PhysicalStimulation(new GenericProtein("unk_id")); - modifier.setLine(new PolylineData()); - PhysicalStimulation modifier2 = new PhysicalStimulation(modifier); - assertNotNull(modifier2); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + PhysicalStimulation modifier = new PhysicalStimulation(new GenericProtein("unk_id")); + modifier.setLine(new PolylineData()); + PhysicalStimulation modifier2 = new PhysicalStimulation(modifier); + assertNotNull(modifier2); } - @Test + @Test(expected = NotImplementedException.class) public void testCopyInvalid() { - try { - Mockito.mock(PhysicalStimulation.class, Mockito.CALLS_REAL_METHODS).copy(); - fail("Exception expected"); - } catch (NotImplementedException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Mockito.mock(PhysicalStimulation.class, Mockito.CALLS_REAL_METHODS).copy(); } @Test public void testCopy() { - try { - PhysicalStimulation modifier = new PhysicalStimulation(new GenericProtein("unk_id")); - modifier.setLine(new PolylineData()); - PhysicalStimulation modifier2 = modifier.copy(); - assertNotNull(modifier2); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + PhysicalStimulation modifier = new PhysicalStimulation(new GenericProtein("unk_id")); + modifier.setLine(new PolylineData()); + PhysicalStimulation modifier2 = modifier.copy(); + assertNotNull(modifier2); } } diff --git a/model/src/test/java/lcsb/mapviewer/model/map/modifier/TriggerTest.java b/model/src/test/java/lcsb/mapviewer/model/map/modifier/TriggerTest.java index 48e1a908df2dd20896dff605a8308a2b9e966f06..f5c6524aefd0a4f2c29d06470ac3bb9d060d25fd 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/modifier/TriggerTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/modifier/TriggerTest.java @@ -1,19 +1,17 @@ package lcsb.mapviewer.model.map.modifier; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.mockito.Mockito; +import lcsb.mapviewer.ModelTestFunctions; import lcsb.mapviewer.common.exception.NotImplementedException; import lcsb.mapviewer.model.graphics.PolylineData; import lcsb.mapviewer.model.map.species.GenericProtein; -public class TriggerTest { +public class TriggerTest extends ModelTestFunctions { @Before public void setUp() throws Exception { @@ -25,61 +23,34 @@ public class TriggerTest { @Test public void testSerialization() { - try { - SerializationUtils.serialize(new Trigger()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + SerializationUtils.serialize(new Trigger()); } @Test public void testConstructor() { - try { - Trigger modifier = new Trigger(new GenericProtein("unk_id")); - assertNotNull(modifier); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Trigger modifier = new Trigger(new GenericProtein("unk_id")); + assertNotNull(modifier); } @Test public void testConstructor2() { - try { - Trigger modifier = new Trigger(new GenericProtein("unk_id")); - modifier.setLine(new PolylineData()); - Trigger modifier2 = new Trigger(modifier); - assertNotNull(modifier2); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Trigger modifier = new Trigger(new GenericProtein("unk_id")); + modifier.setLine(new PolylineData()); + Trigger modifier2 = new Trigger(modifier); + assertNotNull(modifier2); } @Test public void testCopy() { - try { - Trigger modifier = new Trigger(new GenericProtein("unk_id")); - modifier.setLine(new PolylineData()); - Trigger modifier2 = modifier.copy(); - assertNotNull(modifier2); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Trigger modifier = new Trigger(new GenericProtein("unk_id")); + modifier.setLine(new PolylineData()); + Trigger modifier2 = modifier.copy(); + assertNotNull(modifier2); } - @Test + @Test(expected = NotImplementedException.class) public void testCopyInvalid() { - try { - Mockito.mock(Trigger.class, Mockito.CALLS_REAL_METHODS).copy(); - fail("Exception expected"); - } catch (NotImplementedException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Mockito.mock(Trigger.class, Mockito.CALLS_REAL_METHODS).copy(); } } diff --git a/model/src/test/java/lcsb/mapviewer/model/map/modifier/UnknownCatalysisTest.java b/model/src/test/java/lcsb/mapviewer/model/map/modifier/UnknownCatalysisTest.java index 9d66e7e47b465b2f0c9449ceb2942ae46264ff01..e708b26dc7af85251ef1e7b32acb214f0c617d5d 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/modifier/UnknownCatalysisTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/modifier/UnknownCatalysisTest.java @@ -1,19 +1,17 @@ package lcsb.mapviewer.model.map.modifier; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.mockito.Mockito; +import lcsb.mapviewer.ModelTestFunctions; import lcsb.mapviewer.common.exception.NotImplementedException; import lcsb.mapviewer.model.graphics.PolylineData; import lcsb.mapviewer.model.map.species.GenericProtein; -public class UnknownCatalysisTest { +public class UnknownCatalysisTest extends ModelTestFunctions { @Before public void setUp() throws Exception { @@ -25,61 +23,34 @@ public class UnknownCatalysisTest { @Test public void testSerialization() { - try { - SerializationUtils.serialize(new UnknownCatalysis()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + SerializationUtils.serialize(new UnknownCatalysis()); } @Test public void testConstructor() { - try { - UnknownCatalysis modifier = new UnknownCatalysis(new GenericProtein("unk_id")); - assertNotNull(modifier); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + UnknownCatalysis modifier = new UnknownCatalysis(new GenericProtein("unk_id")); + assertNotNull(modifier); } @Test public void testConstructor2() { - try { - UnknownCatalysis modifier = new UnknownCatalysis(new GenericProtein("unk_id")); - modifier.setLine(new PolylineData()); - UnknownCatalysis modifier2 = new UnknownCatalysis(modifier); - assertNotNull(modifier2); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + UnknownCatalysis modifier = new UnknownCatalysis(new GenericProtein("unk_id")); + modifier.setLine(new PolylineData()); + UnknownCatalysis modifier2 = new UnknownCatalysis(modifier); + assertNotNull(modifier2); } @Test public void testCopy() { - try { - UnknownCatalysis modifier = new UnknownCatalysis(new GenericProtein("unk_id")); - modifier.setLine(new PolylineData()); - UnknownCatalysis modifier2 = modifier.copy(); - assertNotNull(modifier2); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + UnknownCatalysis modifier = new UnknownCatalysis(new GenericProtein("unk_id")); + modifier.setLine(new PolylineData()); + UnknownCatalysis modifier2 = modifier.copy(); + assertNotNull(modifier2); } - @Test + @Test(expected = NotImplementedException.class) public void testCopyInvalid() { - try { - Mockito.mock(UnknownCatalysis.class, Mockito.CALLS_REAL_METHODS).copy(); - fail("Exception expected"); - } catch (NotImplementedException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Mockito.mock(UnknownCatalysis.class, Mockito.CALLS_REAL_METHODS).copy(); } } diff --git a/model/src/test/java/lcsb/mapviewer/model/map/modifier/UnknownInhibitionTest.java b/model/src/test/java/lcsb/mapviewer/model/map/modifier/UnknownInhibitionTest.java index dab8c5099f6dc0436ccdb75cb3bee16b595d4961..7a9e707905c97d32522696c7637e78953c7164d3 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/modifier/UnknownInhibitionTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/modifier/UnknownInhibitionTest.java @@ -1,19 +1,17 @@ package lcsb.mapviewer.model.map.modifier; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.mockito.Mockito; +import lcsb.mapviewer.ModelTestFunctions; import lcsb.mapviewer.common.exception.NotImplementedException; import lcsb.mapviewer.model.graphics.PolylineData; import lcsb.mapviewer.model.map.species.GenericProtein; -public class UnknownInhibitionTest { +public class UnknownInhibitionTest extends ModelTestFunctions { @Before public void setUp() throws Exception { @@ -25,61 +23,34 @@ public class UnknownInhibitionTest { @Test public void testSerialization() { - try { - SerializationUtils.serialize(new UnknownInhibition()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + SerializationUtils.serialize(new UnknownInhibition()); } @Test public void testConstructor() { - try { - UnknownInhibition modifier = new UnknownInhibition(new GenericProtein("unk_id")); - assertNotNull(modifier); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + UnknownInhibition modifier = new UnknownInhibition(new GenericProtein("unk_id")); + assertNotNull(modifier); } @Test public void testConstructor2() { - try { - UnknownInhibition modifier = new UnknownInhibition(new GenericProtein("unk_id")); - modifier.setLine(new PolylineData()); - UnknownInhibition modifier2 = new UnknownInhibition(modifier); - assertNotNull(modifier2); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + UnknownInhibition modifier = new UnknownInhibition(new GenericProtein("unk_id")); + modifier.setLine(new PolylineData()); + UnknownInhibition modifier2 = new UnknownInhibition(modifier); + assertNotNull(modifier2); } @Test public void testCopy() { - try { - UnknownInhibition modifier = new UnknownInhibition(new GenericProtein("unk_id")); - modifier.setLine(new PolylineData()); - UnknownInhibition modifier2 = modifier.copy(); - assertNotNull(modifier2); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + UnknownInhibition modifier = new UnknownInhibition(new GenericProtein("unk_id")); + modifier.setLine(new PolylineData()); + UnknownInhibition modifier2 = modifier.copy(); + assertNotNull(modifier2); } - @Test + @Test(expected = NotImplementedException.class) public void testCopyInvalid() { - try { - Mockito.mock(UnknownInhibition.class, Mockito.CALLS_REAL_METHODS).copy(); - fail("Exception expected"); - } catch (NotImplementedException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Mockito.mock(UnknownInhibition.class, Mockito.CALLS_REAL_METHODS).copy(); } } diff --git a/model/src/test/java/lcsb/mapviewer/model/map/reaction/AbstractNodeComparatorTest.java b/model/src/test/java/lcsb/mapviewer/model/map/reaction/AbstractNodeComparatorTest.java index 917b58d35d9cf0a9d7687ba881e1365b7a42be1b..a4b850daa88778a9484de1b8e30b0386a407d770 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/reaction/AbstractNodeComparatorTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/reaction/AbstractNodeComparatorTest.java @@ -1,16 +1,14 @@ package lcsb.mapviewer.model.map.reaction; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.Assert.*; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.mockito.Mockito; +import lcsb.mapviewer.ModelTestFunctions; import lcsb.mapviewer.common.exception.NotImplementedException; -public class AbstractNodeComparatorTest { +public class AbstractNodeComparatorTest extends ModelTestFunctions { AbstractNodeComparator comparator = new AbstractNodeComparator(); @@ -30,23 +28,14 @@ public class AbstractNodeComparatorTest { @Test public void testCompareOk() { - try { - assertEquals(0, comparator.compare(new AndOperator(), new AndOperator())); - assertEquals(0, comparator.compare(null, null)); - } catch (Exception e) { - e.printStackTrace(); - } + assertEquals(0, comparator.compare(new AndOperator(), new AndOperator())); + assertEquals(0, comparator.compare(null, null)); } @Test public void testDifferent() { - try { - assertTrue(comparator.compare(new AndOperator(), null) != 0); - assertTrue(comparator.compare(null, new AndOperator()) != 0); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertTrue(comparator.compare(new AndOperator(), null) != 0); + assertTrue(comparator.compare(null, new AndOperator()) != 0); } } diff --git a/model/src/test/java/lcsb/mapviewer/model/map/reaction/AndOperatorTest.java b/model/src/test/java/lcsb/mapviewer/model/map/reaction/AndOperatorTest.java index 3673aecbf73dec4aa1c3adf201054328a77a2e7d..a63775e92fdcf4b1a451f5e7d356ebe408f2f62a 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/reaction/AndOperatorTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/reaction/AndOperatorTest.java @@ -1,20 +1,16 @@ package lcsb.mapviewer.model.map.reaction; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.mockito.Mockito; +import lcsb.mapviewer.ModelTestFunctions; import lcsb.mapviewer.common.exception.NotImplementedException; import lcsb.mapviewer.model.graphics.PolylineData; -public class AndOperatorTest { +public class AndOperatorTest extends ModelTestFunctions { @Before public void setUp() throws Exception { @@ -26,75 +22,47 @@ public class AndOperatorTest { @Test public void testSerialization() { - try { - SerializationUtils.serialize(new AndOperator()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + SerializationUtils.serialize(new AndOperator()); } @Test public void testConstructor() { - try { - AndOperator op = new AndOperator(); - op.setLine(new PolylineData()); - AndOperator operator = new AndOperator(op); - assertNotNull(operator); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + AndOperator op = new AndOperator(); + op.setLine(new PolylineData()); + AndOperator operator = new AndOperator(op); + assertNotNull(operator); } @Test public void testGetters() { - try { - AndOperator operator = new AndOperator(); - assertFalse("".equals(new AndOperator().getSBGNOperatorText())); - assertFalse("".equals(operator.getOperatorText())); + AndOperator operator = new AndOperator(); + assertFalse("".equals(new AndOperator().getSBGNOperatorText())); + assertFalse("".equals(operator.getOperatorText())); - NodeOperator nodeOperatorForInput = new AndOperator(); - NodeOperator nodeOperatorForOutput = new AndOperator(); + NodeOperator nodeOperatorForInput = new AndOperator(); + NodeOperator nodeOperatorForOutput = new AndOperator(); - Reaction reaction = new Reaction(); + Reaction reaction = new Reaction(); - operator.setReaction(reaction); - operator.setNodeOperatorForInput(nodeOperatorForInput); - operator.setNodeOperatorForOutput(nodeOperatorForOutput); + operator.setReaction(reaction); + operator.setNodeOperatorForInput(nodeOperatorForInput); + operator.setNodeOperatorForOutput(nodeOperatorForOutput); - assertEquals(reaction, operator.getReaction()); - assertEquals(nodeOperatorForInput, operator.getNodeOperatorForInput()); - assertEquals(nodeOperatorForOutput, operator.getNodeOperatorForOutput()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(reaction, operator.getReaction()); + assertEquals(nodeOperatorForInput, operator.getNodeOperatorForInput()); + assertEquals(nodeOperatorForOutput, operator.getNodeOperatorForOutput()); } @Test public void testCopy1() { - try { - AndOperator op = new AndOperator(); - op.setLine(new PolylineData()); - AndOperator operator = op.copy(); - assertNotNull(operator); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + AndOperator op = new AndOperator(); + op.setLine(new PolylineData()); + AndOperator operator = op.copy(); + assertNotNull(operator); } - @Test + @Test(expected = NotImplementedException.class) public void testCopy2() { - try { - Mockito.mock(AndOperator.class, Mockito.CALLS_REAL_METHODS).copy(); - fail("Exception expected"); - } catch (NotImplementedException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Mockito.mock(AndOperator.class, Mockito.CALLS_REAL_METHODS).copy(); } } diff --git a/model/src/test/java/lcsb/mapviewer/model/map/reaction/AssociationOperatorTest.java b/model/src/test/java/lcsb/mapviewer/model/map/reaction/AssociationOperatorTest.java index 7e1867e0b24340d4b8cabbf7911516fe12bcc5f3..406c3fcbca55f0dd8a6740f01bcbdb7c7192750a 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/reaction/AssociationOperatorTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/reaction/AssociationOperatorTest.java @@ -1,19 +1,16 @@ package lcsb.mapviewer.model.map.reaction; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.mockito.Mockito; +import lcsb.mapviewer.ModelTestFunctions; import lcsb.mapviewer.common.exception.NotImplementedException; import lcsb.mapviewer.model.graphics.PolylineData; -public class AssociationOperatorTest { +public class AssociationOperatorTest extends ModelTestFunctions { @Before public void setUp() throws Exception { @@ -25,61 +22,34 @@ public class AssociationOperatorTest { @Test public void testSerialization() { - try { - SerializationUtils.serialize(new AssociationOperator()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + SerializationUtils.serialize(new AssociationOperator()); } @Test public void testConstructor() { - try { - AssociationOperator op = new AssociationOperator(); - op.setLine(new PolylineData()); - AssociationOperator operator = new AssociationOperator(op); - assertNotNull(operator); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + AssociationOperator op = new AssociationOperator(); + op.setLine(new PolylineData()); + AssociationOperator operator = new AssociationOperator(op); + assertNotNull(operator); } @Test public void testGetters() { - try { - assertFalse("".equals(new AssociationOperator().getSBGNOperatorText())); - assertFalse("".equals(new AssociationOperator().getOperatorText())); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertFalse("".equals(new AssociationOperator().getSBGNOperatorText())); + assertFalse("".equals(new AssociationOperator().getOperatorText())); } @Test public void testCopy1() { - try { - AssociationOperator op = new AssociationOperator(); - op.setLine(new PolylineData()); - AssociationOperator operator = op.copy(); - assertNotNull(operator); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + AssociationOperator op = new AssociationOperator(); + op.setLine(new PolylineData()); + AssociationOperator operator = op.copy(); + assertNotNull(operator); } - @Test + @Test(expected = NotImplementedException.class) public void testCopy2() { - try { - Mockito.mock(AssociationOperator.class, Mockito.CALLS_REAL_METHODS).copy(); - fail("Exception expected"); - } catch (NotImplementedException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Mockito.mock(AssociationOperator.class, Mockito.CALLS_REAL_METHODS).copy(); } } diff --git a/model/src/test/java/lcsb/mapviewer/model/map/reaction/DissociationOperatorTest.java b/model/src/test/java/lcsb/mapviewer/model/map/reaction/DissociationOperatorTest.java index 32e7603167cec24abe436074de42a7f8e48ea605..7738614412580b27d3276fdde9461e53b3ca2daa 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/reaction/DissociationOperatorTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/reaction/DissociationOperatorTest.java @@ -1,19 +1,16 @@ package lcsb.mapviewer.model.map.reaction; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.mockito.Mockito; +import lcsb.mapviewer.ModelTestFunctions; import lcsb.mapviewer.common.exception.NotImplementedException; import lcsb.mapviewer.model.graphics.PolylineData; -public class DissociationOperatorTest { +public class DissociationOperatorTest extends ModelTestFunctions { @Before public void setUp() throws Exception { @@ -25,61 +22,34 @@ public class DissociationOperatorTest { @Test public void testSerialization() { - try { - SerializationUtils.serialize(new DissociationOperator()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + SerializationUtils.serialize(new DissociationOperator()); } @Test public void testConstructor() { - try { - DissociationOperator op = new DissociationOperator(); - op.setLine(new PolylineData()); - DissociationOperator operator = new DissociationOperator(op); - assertNotNull(operator); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + DissociationOperator op = new DissociationOperator(); + op.setLine(new PolylineData()); + DissociationOperator operator = new DissociationOperator(op); + assertNotNull(operator); } @Test public void testGetters() { - try { - assertFalse("".equals(new DissociationOperator().getSBGNOperatorText())); - assertFalse("".equals(new DissociationOperator().getOperatorText())); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertFalse("".equals(new DissociationOperator().getSBGNOperatorText())); + assertFalse("".equals(new DissociationOperator().getOperatorText())); } @Test public void testCopy1() { - try { - DissociationOperator op = new DissociationOperator(); - op.setLine(new PolylineData()); - DissociationOperator operator = op.copy(); - assertNotNull(operator); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + DissociationOperator op = new DissociationOperator(); + op.setLine(new PolylineData()); + DissociationOperator operator = op.copy(); + assertNotNull(operator); } - @Test + @Test(expected = NotImplementedException.class) public void testCopy2() { - try { - Mockito.mock(DissociationOperator.class, Mockito.CALLS_REAL_METHODS).copy(); - fail("Exception expected"); - } catch (NotImplementedException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Mockito.mock(DissociationOperator.class, Mockito.CALLS_REAL_METHODS).copy(); } } diff --git a/model/src/test/java/lcsb/mapviewer/model/map/reaction/ModifierTest.java b/model/src/test/java/lcsb/mapviewer/model/map/reaction/ModifierTest.java index d99344c1182678e406b99179922efd4819caee75..603d7bbe74f1f8eb8776fe80a43b3d0e1fafced6 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/reaction/ModifierTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/reaction/ModifierTest.java @@ -1,18 +1,16 @@ package lcsb.mapviewer.model.map.reaction; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.mockito.Mockito; +import lcsb.mapviewer.ModelTestFunctions; import lcsb.mapviewer.common.exception.NotImplementedException; import lcsb.mapviewer.model.graphics.PolylineData; -public class ModifierTest { +public class ModifierTest extends ModelTestFunctions { @Before public void setUp() throws Exception { @@ -24,50 +22,28 @@ public class ModifierTest { @Test public void testSerialization() { - try { - SerializationUtils.serialize(new Modifier()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + SerializationUtils.serialize(new Modifier()); } @Test public void testConstructor() { - try { - Modifier original = new Modifier(); - original.setLine(new PolylineData()); - Modifier modifier = new Modifier(original); - assertNotNull(modifier); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Modifier original = new Modifier(); + original.setLine(new PolylineData()); + Modifier modifier = new Modifier(original); + assertNotNull(modifier); } @Test public void testCopy() { - try { - Modifier original = new Modifier(); - original.setLine(new PolylineData()); - Modifier modifier = original.copy(); - assertNotNull(modifier); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Modifier original = new Modifier(); + original.setLine(new PolylineData()); + Modifier modifier = original.copy(); + assertNotNull(modifier); } - @Test + @Test(expected = NotImplementedException.class) public void testInvalidCopy() { - try { - Mockito.mock(Modifier.class, Mockito.CALLS_REAL_METHODS).copy(); - fail("Exception expected"); - } catch (NotImplementedException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Mockito.mock(Modifier.class, Mockito.CALLS_REAL_METHODS).copy(); } } diff --git a/model/src/test/java/lcsb/mapviewer/model/map/reaction/NandOperatorTest.java b/model/src/test/java/lcsb/mapviewer/model/map/reaction/NandOperatorTest.java index 943434f3a00e330c785f7eb26273af7b7e640373..c5dd68f2a1db1f35f16e51f4b48a3df8f3400ebd 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/reaction/NandOperatorTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/reaction/NandOperatorTest.java @@ -1,19 +1,16 @@ package lcsb.mapviewer.model.map.reaction; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.mockito.Mockito; +import lcsb.mapviewer.ModelTestFunctions; import lcsb.mapviewer.common.exception.NotImplementedException; import lcsb.mapviewer.model.graphics.PolylineData; -public class NandOperatorTest { +public class NandOperatorTest extends ModelTestFunctions { @Before public void setUp() throws Exception { @@ -25,61 +22,34 @@ public class NandOperatorTest { @Test public void testSerialization() { - try { - SerializationUtils.serialize(new NandOperator()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + SerializationUtils.serialize(new NandOperator()); } @Test public void testConstructor() { - try { - NandOperator op = new NandOperator(); - op.setLine(new PolylineData()); - NandOperator operator = new NandOperator(op); - assertNotNull(operator); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + NandOperator op = new NandOperator(); + op.setLine(new PolylineData()); + NandOperator operator = new NandOperator(op); + assertNotNull(operator); } @Test public void testGetters() { - try { - assertFalse("".equals(new NandOperator().getSBGNOperatorText())); - assertFalse("".equals(new NandOperator().getOperatorText())); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertFalse("".equals(new NandOperator().getSBGNOperatorText())); + assertFalse("".equals(new NandOperator().getOperatorText())); } @Test public void testCopy1() { - try { - NandOperator op = new NandOperator(); - op.setLine(new PolylineData()); - NandOperator operator = op.copy(); - assertNotNull(operator); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + NandOperator op = new NandOperator(); + op.setLine(new PolylineData()); + NandOperator operator = op.copy(); + assertNotNull(operator); } - @Test + @Test(expected = NotImplementedException.class) public void testCopy2() { - try { - Mockito.mock(NandOperator.class, Mockito.CALLS_REAL_METHODS).copy(); - fail("Exception expected"); - } catch (NotImplementedException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Mockito.mock(NandOperator.class, Mockito.CALLS_REAL_METHODS).copy(); } } diff --git a/model/src/test/java/lcsb/mapviewer/model/map/reaction/NodeOperatorComparatorTest.java b/model/src/test/java/lcsb/mapviewer/model/map/reaction/NodeOperatorComparatorTest.java index df23bf80876b94f5ffa94b69b618debe61de5ba3..8f5d37ff02532e34c14a31db7dbc69bca63f4f47 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/reaction/NodeOperatorComparatorTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/reaction/NodeOperatorComparatorTest.java @@ -1,20 +1,16 @@ package lcsb.mapviewer.model.map.reaction; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.Assert.*; import java.awt.geom.Point2D; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; +import lcsb.mapviewer.ModelTestFunctions; import lcsb.mapviewer.model.graphics.PolylineData; -import lcsb.mapviewer.model.map.species.Gene; -import lcsb.mapviewer.model.map.species.GenericProtein; -import lcsb.mapviewer.model.map.species.Species; +import lcsb.mapviewer.model.map.species.*; -public class NodeOperatorComparatorTest { +public class NodeOperatorComparatorTest extends ModelTestFunctions { NodeOperatorComparator comparator = new NodeOperatorComparator(); @@ -28,22 +24,16 @@ public class NodeOperatorComparatorTest { @Test public void testEquals() { - try { - assertEquals(0, comparator.compare(new AndOperator(), new AndOperator())); + assertEquals(0, comparator.compare(new AndOperator(), new AndOperator())); - NodeOperator operator1 = createNodeOperator(); - NodeOperator operator2 = createNodeOperator(); - - assertEquals(0, comparator.compare(operator1, operator2)); + NodeOperator operator1 = createNodeOperator(); + NodeOperator operator2 = createNodeOperator(); - assertEquals(0, comparator.compare(operator1, operator1)); + assertEquals(0, comparator.compare(operator1, operator2)); - assertEquals(0, comparator.compare(null, null)); + assertEquals(0, comparator.compare(operator1, operator1)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, comparator.compare(null, null)); } @Test @@ -59,53 +49,48 @@ public class NodeOperatorComparatorTest { @Test public void testDifferent() { - try { - NodeOperator operator1 = createNodeOperator(); - NodeOperator operator2 = createNodeOperator(); + NodeOperator operator1 = createNodeOperator(); + NodeOperator operator2 = createNodeOperator(); - operator1.getLine().addPoint(new Point2D.Double(1, 1)); - assertTrue(comparator.compare(operator1, operator2) != 0); - assertTrue(comparator.compare(operator2, operator1) != 0); + operator1.getLine().addPoint(new Point2D.Double(1, 1)); + assertTrue(comparator.compare(operator1, operator2) != 0); + assertTrue(comparator.compare(operator2, operator1) != 0); - operator1 = createNodeOperator(); - operator2 = createNodeOperator(); + operator1 = createNodeOperator(); + operator2 = createNodeOperator(); - operator1.addInput(new Reactant()); - assertTrue(comparator.compare(operator1, operator2) != 0); - assertTrue(comparator.compare(operator2, operator1) != 0); + operator1.addInput(new Reactant()); + assertTrue(comparator.compare(operator1, operator2) != 0); + assertTrue(comparator.compare(operator2, operator1) != 0); - operator1 = createNodeOperator(); - operator2 = createNodeOperator(); + operator1 = createNodeOperator(); + operator2 = createNodeOperator(); - operator1.addOutput(new Product()); - assertTrue(comparator.compare(operator1, operator2) != 0); - assertTrue(comparator.compare(operator2, operator1) != 0); + operator1.addOutput(new Product()); + assertTrue(comparator.compare(operator1, operator2) != 0); + assertTrue(comparator.compare(operator2, operator1) != 0); - operator1 = createNodeOperator(); - operator2 = createNodeOperator(); + operator1 = createNodeOperator(); + operator2 = createNodeOperator(); - Product product = (Product) operator1.getOutputs().get(0); - product.setElement(new GenericProtein("id666")); - assertTrue(comparator.compare(operator1, operator2) != 0); - assertTrue(comparator.compare(operator2, operator1) != 0); + Product product = (Product) operator1.getOutputs().get(0); + product.setElement(new GenericProtein("id666")); + assertTrue(comparator.compare(operator1, operator2) != 0); + assertTrue(comparator.compare(operator2, operator1) != 0); - operator1 = createNodeOperator(); - operator2 = createNodeOperator(); + operator1 = createNodeOperator(); + operator2 = createNodeOperator(); - Reactant reactant = (Reactant) operator1.getInputs().get(0); - reactant.getElement().setName("bla"); - assertTrue(comparator.compare(operator1, operator2) != 0); - assertTrue(comparator.compare(operator2, operator1) != 0); + Reactant reactant = (Reactant) operator1.getInputs().get(0); + reactant.getElement().setName("bla"); + assertTrue(comparator.compare(operator1, operator2) != 0); + assertTrue(comparator.compare(operator2, operator1) != 0); - assertTrue(comparator.compare(null, operator1) != 0); - assertTrue(comparator.compare(operator2, null) != 0); + assertTrue(comparator.compare(null, operator1) != 0); + assertTrue(comparator.compare(operator2, null) != 0); - assertTrue(comparator.compare(operator2, new OrOperator()) != 0); + assertTrue(comparator.compare(operator2, new OrOperator()) != 0); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } } private NodeOperator createNodeOperator() { diff --git a/model/src/test/java/lcsb/mapviewer/model/map/reaction/NodeOperatorTest.java b/model/src/test/java/lcsb/mapviewer/model/map/reaction/NodeOperatorTest.java index de27fe0cce18f8b0b7c379db80bc37addc9a03d2..b7406bad07a04c6171c84968e20499ac50e40f87 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/reaction/NodeOperatorTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/reaction/NodeOperatorTest.java @@ -1,210 +1,140 @@ package lcsb.mapviewer.model.map.reaction; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import java.util.ArrayList; import java.util.List; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; +import lcsb.mapviewer.ModelTestFunctions; import lcsb.mapviewer.common.exception.InvalidArgumentException; import lcsb.mapviewer.model.graphics.PolylineData; -public class NodeOperatorTest { - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testConstructor() { - try { - NodeOperator operator = new NodeOperatorMock(); - NodeOperator operator2 = new NodeOperatorMock(); - NodeOperator operator3 = new NodeOperatorMock(); - operator.addInput(operator2); - operator.addOutput(operator3); - operator.setLine(new PolylineData()); - - NodeOperator result = new NodeOperatorMock(operator); - assertEquals(1, result.getInputs().size()); - assertEquals(1, result.getOutputs().size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - - } - - @Test - public void testAddInput() { - try { - NodeOperator operator = new NodeOperatorMock(); - NodeOperator operator2 = new NodeOperatorMock(); - operator.addInput(operator2); - assertEquals(1, operator.getInputs().size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - - } - - @Test - public void testAddInputs() { - try { - NodeOperator operator = new NodeOperatorMock(); - NodeOperator operator2 = new NodeOperatorMock(); - List<NodeOperator> list = new ArrayList<>(); - list.add(operator2); - operator.addInputs(list); - assertEquals(1, operator.getInputs().size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - - } - - @Test - public void testAddInput2() { - try { - NodeOperator operator = new NodeOperatorMock(); - NodeOperator operator2 = new NodeOperatorMock(); - operator.addInput(operator2); - operator.addInput(operator2); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - - } - - @Test - public void testIsReactantOperator() { - try { - NodeOperator operator = new NodeOperatorMock(); - assertFalse(operator.isReactantOperator()); - - AndOperator op1 = new AndOperator(); - operator.addInput(op1); - assertFalse(operator.isReactantOperator()); - - op1.addInput(new Reactant()); - assertTrue(operator.isReactantOperator()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - - } - - @Test - public void testAddOutputs() { - try { - NodeOperator operator = new NodeOperatorMock(); - NodeOperator operator2 = new NodeOperatorMock(); - List<NodeOperator> list = new ArrayList<>(); - list.add(operator2); - operator.addOutputs(list); - assertEquals(1, operator.getOutputs().size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - - } - - @Test - public void testAddOutput2() { - try { - NodeOperator operator = new NodeOperatorMock(); - NodeOperator operator2 = new NodeOperatorMock(); - operator.addOutput(operator2); - operator.addOutput(operator2); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - - } - - @Test - public void testIsProductOperator() { - try { - NodeOperator operator = new NodeOperatorMock(); - assertFalse(operator.isReactantOperator()); - - AndOperator op1 = new AndOperator(); - operator.addInput(op1); - assertFalse(operator.isProductOperator()); - - op1.addInput(new Reactant()); - assertFalse(operator.isProductOperator()); - - SplitOperator op2 = new SplitOperator(); - operator.addOutput(op2); - assertFalse(operator.isProductOperator()); - - op2.addOutput(new Product()); - assertTrue(operator.isProductOperator()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - - } - - @Test - public void testGetters() { - try { - NodeOperator operator = new NodeOperatorMock(); - assertNotNull(operator.getSBGNOperatorText()); - List<AbstractNode> inputs = new ArrayList<>(); - List<AbstractNode> outputs = new ArrayList<>(); - operator.setInputs(inputs); - operator.setOutputs(outputs); - assertEquals(inputs, operator.getInputs()); - assertEquals(outputs, operator.getOutputs()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - - } - - @Test - public void testIsModifierOperator() { - try { - NodeOperator operator = new NodeOperatorMock(); - assertFalse(operator.isReactantOperator()); - - AndOperator op1 = new AndOperator(); - operator.addInput(op1); - assertFalse(operator.isModifierOperator()); - - op1.addInput(new Modifier()); - assertTrue(operator.isModifierOperator()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - - } +public class NodeOperatorTest extends ModelTestFunctions { + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testConstructor() { + NodeOperator operator = new NodeOperatorMock(); + NodeOperator operator2 = new NodeOperatorMock(); + NodeOperator operator3 = new NodeOperatorMock(); + operator.addInput(operator2); + operator.addOutput(operator3); + operator.setLine(new PolylineData()); + + NodeOperator result = new NodeOperatorMock(operator); + assertEquals(1, result.getInputs().size()); + assertEquals(1, result.getOutputs().size()); + } + + @Test + public void testAddInput() { + NodeOperator operator = new NodeOperatorMock(); + NodeOperator operator2 = new NodeOperatorMock(); + operator.addInput(operator2); + assertEquals(1, operator.getInputs().size()); + } + + @Test + public void testAddInputs() { + NodeOperator operator = new NodeOperatorMock(); + NodeOperator operator2 = new NodeOperatorMock(); + List<NodeOperator> list = new ArrayList<>(); + list.add(operator2); + operator.addInputs(list); + assertEquals(1, operator.getInputs().size()); + } + + @Test(expected = InvalidArgumentException.class) + public void testAddInput2() { + NodeOperator operator = new NodeOperatorMock(); + NodeOperator operator2 = new NodeOperatorMock(); + operator.addInput(operator2); + operator.addInput(operator2); + } + + @Test + public void testIsReactantOperator() { + NodeOperator operator = new NodeOperatorMock(); + assertFalse(operator.isReactantOperator()); + + AndOperator op1 = new AndOperator(); + operator.addInput(op1); + assertFalse(operator.isReactantOperator()); + + op1.addInput(new Reactant()); + assertTrue(operator.isReactantOperator()); + } + + @Test + public void testAddOutputs() { + NodeOperator operator = new NodeOperatorMock(); + NodeOperator operator2 = new NodeOperatorMock(); + List<NodeOperator> list = new ArrayList<>(); + list.add(operator2); + operator.addOutputs(list); + assertEquals(1, operator.getOutputs().size()); + } + + @Test(expected = InvalidArgumentException.class) + public void testAddOutput2() { + NodeOperator operator = new NodeOperatorMock(); + NodeOperator operator2 = new NodeOperatorMock(); + operator.addOutput(operator2); + operator.addOutput(operator2); + } + + @Test + public void testIsProductOperator() { + NodeOperator operator = new NodeOperatorMock(); + assertFalse(operator.isReactantOperator()); + + AndOperator op1 = new AndOperator(); + operator.addInput(op1); + assertFalse(operator.isProductOperator()); + + op1.addInput(new Reactant()); + assertFalse(operator.isProductOperator()); + + SplitOperator op2 = new SplitOperator(); + operator.addOutput(op2); + assertFalse(operator.isProductOperator()); + + op2.addOutput(new Product()); + assertTrue(operator.isProductOperator()); + } + + @Test + public void testGetters() { + NodeOperator operator = new NodeOperatorMock(); + assertNotNull(operator.getSBGNOperatorText()); + List<AbstractNode> inputs = new ArrayList<>(); + List<AbstractNode> outputs = new ArrayList<>(); + operator.setInputs(inputs); + operator.setOutputs(outputs); + assertEquals(inputs, operator.getInputs()); + assertEquals(outputs, operator.getOutputs()); + } + + @Test + public void testIsModifierOperator() { + NodeOperator operator = new NodeOperatorMock(); + assertFalse(operator.isReactantOperator()); + + AndOperator op1 = new AndOperator(); + operator.addInput(op1); + assertFalse(operator.isModifierOperator()); + + op1.addInput(new Modifier()); + assertTrue(operator.isModifierOperator()); + } } diff --git a/model/src/test/java/lcsb/mapviewer/model/map/reaction/OrOperatorTest.java b/model/src/test/java/lcsb/mapviewer/model/map/reaction/OrOperatorTest.java index 23a13dcc51085babe2520998ff7bc684a0dd14aa..570a5b6e985c46d3a450362aa6cf1dad4d2710b1 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/reaction/OrOperatorTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/reaction/OrOperatorTest.java @@ -1,19 +1,16 @@ package lcsb.mapviewer.model.map.reaction; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.mockito.Mockito; +import lcsb.mapviewer.ModelTestFunctions; import lcsb.mapviewer.common.exception.NotImplementedException; import lcsb.mapviewer.model.graphics.PolylineData; -public class OrOperatorTest { +public class OrOperatorTest extends ModelTestFunctions { @Before public void setUp() throws Exception { @@ -25,61 +22,34 @@ public class OrOperatorTest { @Test public void testSerialization() { - try { - SerializationUtils.serialize(new OrOperator()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + SerializationUtils.serialize(new OrOperator()); } @Test public void testConstructor() { - try { - OrOperator op = new OrOperator(); - op.setLine(new PolylineData()); - OrOperator operator = new OrOperator(op); - assertNotNull(operator); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + OrOperator op = new OrOperator(); + op.setLine(new PolylineData()); + OrOperator operator = new OrOperator(op); + assertNotNull(operator); } @Test public void testGetters() { - try { - assertFalse("".equals(new OrOperator().getSBGNOperatorText())); - assertFalse("".equals(new OrOperator().getOperatorText())); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertFalse("".equals(new OrOperator().getSBGNOperatorText())); + assertFalse("".equals(new OrOperator().getOperatorText())); } @Test public void testCopy1() { - try { - OrOperator op = new OrOperator(); - op.setLine(new PolylineData()); - OrOperator operator = op.copy(); - assertNotNull(operator); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + OrOperator op = new OrOperator(); + op.setLine(new PolylineData()); + OrOperator operator = op.copy(); + assertNotNull(operator); } - @Test + @Test(expected = NotImplementedException.class) public void testCopy2() { - try { - Mockito.mock(OrOperator.class, Mockito.CALLS_REAL_METHODS).copy(); - fail("Exception expected"); - } catch (NotImplementedException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Mockito.mock(OrOperator.class, Mockito.CALLS_REAL_METHODS).copy(); } } diff --git a/model/src/test/java/lcsb/mapviewer/model/map/reaction/ProductTest.java b/model/src/test/java/lcsb/mapviewer/model/map/reaction/ProductTest.java index 900bd6c5b1268bdeab6bb6eee98c6a085e2a5e44..27de69631a5b7132d7d656584b5ee59edb743f77 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/reaction/ProductTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/reaction/ProductTest.java @@ -1,18 +1,16 @@ package lcsb.mapviewer.model.map.reaction; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.mockito.Mockito; +import lcsb.mapviewer.ModelTestFunctions; import lcsb.mapviewer.common.exception.NotImplementedException; import lcsb.mapviewer.model.graphics.PolylineData; -public class ProductTest { +public class ProductTest extends ModelTestFunctions { @Before public void setUp() throws Exception { @@ -24,49 +22,27 @@ public class ProductTest { @Test public void testSerialization() { - try { - SerializationUtils.serialize(new Product()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + SerializationUtils.serialize(new Product()); } @Test public void testConstructor() { - try { - Product original = new Product(); - original.setLine(new PolylineData()); - Product product = new Product(original); - assertNotNull(product); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Product original = new Product(); + original.setLine(new PolylineData()); + Product product = new Product(original); + assertNotNull(product); } @Test public void testCopy() { - try { - Product original = new Product(); - original.setLine(new PolylineData()); - Product product = original.copy(); - assertNotNull(product); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Product original = new Product(); + original.setLine(new PolylineData()); + Product product = original.copy(); + assertNotNull(product); } - @Test + @Test(expected = NotImplementedException.class) public void testInvalidCopy() { - try { - Mockito.mock(Product.class, Mockito.CALLS_REAL_METHODS).copy(); - fail("Exception expected"); - } catch (NotImplementedException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Mockito.mock(Product.class, Mockito.CALLS_REAL_METHODS).copy(); } } diff --git a/model/src/test/java/lcsb/mapviewer/model/map/reaction/ReactantTest.java b/model/src/test/java/lcsb/mapviewer/model/map/reaction/ReactantTest.java index 0cc12001ac3862a8411afe365cb094f7d0dd2cab..3d3c1aa3a3dcfb2c741003bfc75a934cb6b17270 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/reaction/ReactantTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/reaction/ReactantTest.java @@ -1,18 +1,16 @@ package lcsb.mapviewer.model.map.reaction; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.mockito.Mockito; +import lcsb.mapviewer.ModelTestFunctions; import lcsb.mapviewer.common.exception.NotImplementedException; import lcsb.mapviewer.model.graphics.PolylineData; -public class ReactantTest { +public class ReactantTest extends ModelTestFunctions { @Before public void setUp() throws Exception { @@ -24,50 +22,28 @@ public class ReactantTest { @Test public void testSerialization() { - try { - SerializationUtils.serialize(new Reactant()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + SerializationUtils.serialize(new Reactant()); } @Test public void testConstructor() { - try { - Reactant original = new Reactant(); - original.setLine(new PolylineData()); - Reactant reactant = new Reactant(original); - assertNotNull(reactant); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Reactant original = new Reactant(); + original.setLine(new PolylineData()); + Reactant reactant = new Reactant(original); + assertNotNull(reactant); } @Test public void testCopy() { - try { - Reactant original = new Reactant(); - original.setLine(new PolylineData()); - Reactant reactant = original.copy(); - assertNotNull(reactant); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Reactant original = new Reactant(); + original.setLine(new PolylineData()); + Reactant reactant = original.copy(); + assertNotNull(reactant); } - @Test + @Test(expected = NotImplementedException.class) public void testInvalidCopy() { - try { - Mockito.mock(Reactant.class, Mockito.CALLS_REAL_METHODS).copy(); - fail("Exception expected"); - } catch (NotImplementedException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Mockito.mock(Reactant.class, Mockito.CALLS_REAL_METHODS).copy(); } } diff --git a/model/src/test/java/lcsb/mapviewer/model/map/reaction/ReactionComparatorTest.java b/model/src/test/java/lcsb/mapviewer/model/map/reaction/ReactionComparatorTest.java index 1e6f03fae15d4a5aa3f96f72eb987e156bd6faee..2cb92cb9158dc322c114d61888bbe2b22be827a9 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/reaction/ReactionComparatorTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/reaction/ReactionComparatorTest.java @@ -1,28 +1,21 @@ package lcsb.mapviewer.model.map.reaction; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.Assert.*; import java.awt.geom.Point2D; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; +import lcsb.mapviewer.ModelTestFunctions; import lcsb.mapviewer.model.graphics.PolylineData; -import lcsb.mapviewer.model.map.MiriamData; -import lcsb.mapviewer.model.map.MiriamRelationType; -import lcsb.mapviewer.model.map.MiriamType; +import lcsb.mapviewer.model.map.*; import lcsb.mapviewer.model.map.kinetics.SbmlKinetics; import lcsb.mapviewer.model.map.modifier.Catalysis; import lcsb.mapviewer.model.map.reaction.type.StateTransitionReaction; import lcsb.mapviewer.model.map.reaction.type.TransportReaction; -import lcsb.mapviewer.model.map.species.GenericProtein; -import lcsb.mapviewer.model.map.species.SimpleMolecule; -import lcsb.mapviewer.model.map.species.Species; -import lcsb.mapviewer.model.map.species.Unknown; +import lcsb.mapviewer.model.map.species.*; -public class ReactionComparatorTest { +public class ReactionComparatorTest extends ModelTestFunctions { ReactionComparator comparator = new ReactionComparator(); @@ -36,208 +29,177 @@ public class ReactionComparatorTest { @Test public void testEquals() { - try { - Reaction reaction1 = createReaction(); - Reaction reaction2 = createReaction(); - assertEquals(0, comparator.compare(reaction1, reaction2)); - assertEquals(0, comparator.compare(reaction2, reaction1)); - assertEquals(0, comparator.compare(reaction1, reaction1)); - assertEquals(0, comparator.compare(null, null)); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Reaction reaction1 = createReaction(); + Reaction reaction2 = createReaction(); + assertEquals(0, comparator.compare(reaction1, reaction2)); + assertEquals(0, comparator.compare(reaction2, reaction1)); + assertEquals(0, comparator.compare(reaction1, reaction1)); + assertEquals(0, comparator.compare(null, null)); } @Test public void testDifferent3() { - try { - Reaction reaction1 = createReaction(); - Reaction reaction2 = createReaction(); - - reaction1.setNotes("a"); - assertTrue(comparator.compare(reaction1, reaction2) != 0); - assertTrue(comparator.compare(reaction2, reaction1) != 0); + Reaction reaction1 = createReaction(); + Reaction reaction2 = createReaction(); - reaction1 = createReaction(); - reaction2 = createReaction(); + reaction1.setNotes("a"); + assertTrue(comparator.compare(reaction1, reaction2) != 0); + assertTrue(comparator.compare(reaction2, reaction1) != 0); - reaction1.setIdReaction("a"); - assertTrue(comparator.compare(reaction1, reaction2) != 0); - assertTrue(comparator.compare(reaction2, reaction1) != 0); + reaction1 = createReaction(); + reaction2 = createReaction(); - reaction1 = createReaction(); - reaction2 = createReaction(); + reaction1.setIdReaction("a"); + assertTrue(comparator.compare(reaction1, reaction2) != 0); + assertTrue(comparator.compare(reaction2, reaction1) != 0); - reaction1.setSymbol("a"); - assertTrue(comparator.compare(reaction1, reaction2) != 0); - assertTrue(comparator.compare(reaction2, reaction1) != 0); + reaction1 = createReaction(); + reaction2 = createReaction(); - reaction1 = createReaction(); - reaction2 = createReaction(); + reaction1.setSymbol("a"); + assertTrue(comparator.compare(reaction1, reaction2) != 0); + assertTrue(comparator.compare(reaction2, reaction1) != 0); - reaction1.setFormula("a"); - assertTrue(comparator.compare(reaction1, reaction2) != 0); - assertTrue(comparator.compare(reaction2, reaction1) != 0); + reaction1 = createReaction(); + reaction2 = createReaction(); - reaction1 = createReaction(); - reaction2 = createReaction(); + reaction1.setFormula("a"); + assertTrue(comparator.compare(reaction1, reaction2) != 0); + assertTrue(comparator.compare(reaction2, reaction1) != 0); - reaction1.setSubsystem("a"); - assertTrue(comparator.compare(reaction1, reaction2) != 0); - assertTrue(comparator.compare(reaction2, reaction1) != 0); + reaction1 = createReaction(); + reaction2 = createReaction(); - reaction1 = createReaction(); - reaction2 = createReaction(); + reaction1.setSubsystem("a"); + assertTrue(comparator.compare(reaction1, reaction2) != 0); + assertTrue(comparator.compare(reaction2, reaction1) != 0); - reaction1.setGeneProteinReaction("a"); - assertTrue(comparator.compare(reaction1, reaction2) != 0); - assertTrue(comparator.compare(reaction2, reaction1) != 0); + reaction1 = createReaction(); + reaction2 = createReaction(); - reaction1 = createReaction(); - reaction2 = createReaction(); + reaction1.setGeneProteinReaction("a"); + assertTrue(comparator.compare(reaction1, reaction2) != 0); + assertTrue(comparator.compare(reaction2, reaction1) != 0); - reaction1.setMechanicalConfidenceScore(1); - assertTrue(comparator.compare(reaction1, reaction2) != 0); - assertTrue(comparator.compare(reaction2, reaction1) != 0); + reaction1 = createReaction(); + reaction2 = createReaction(); - reaction1 = createReaction(); - reaction2 = createReaction(); + reaction1.setMechanicalConfidenceScore(1); + assertTrue(comparator.compare(reaction1, reaction2) != 0); + assertTrue(comparator.compare(reaction2, reaction1) != 0); - reaction1.setLowerBound(1.2); - assertTrue(comparator.compare(reaction1, reaction2) != 0); - assertTrue(comparator.compare(reaction2, reaction1) != 0); + reaction1 = createReaction(); + reaction2 = createReaction(); - reaction1 = createReaction(); - reaction2 = createReaction(); + reaction1.setLowerBound(1.2); + assertTrue(comparator.compare(reaction1, reaction2) != 0); + assertTrue(comparator.compare(reaction2, reaction1) != 0); - reaction1.setUpperBound(4.3); - assertTrue(comparator.compare(reaction1, reaction2) != 0); - assertTrue(comparator.compare(reaction2, reaction1) != 0); + reaction1 = createReaction(); + reaction2 = createReaction(); - reaction1 = createReaction(); - reaction2 = createReaction(); + reaction1.setUpperBound(4.3); + assertTrue(comparator.compare(reaction1, reaction2) != 0); + assertTrue(comparator.compare(reaction2, reaction1) != 0); - reaction1.addSynonym("syn"); - assertTrue(comparator.compare(reaction1, reaction2) != 0); - assertTrue(comparator.compare(reaction2, reaction1) != 0); + reaction1 = createReaction(); + reaction2 = createReaction(); - reaction1 = createReaction(); - reaction2 = createReaction(); + reaction1.addSynonym("syn"); + assertTrue(comparator.compare(reaction1, reaction2) != 0); + assertTrue(comparator.compare(reaction2, reaction1) != 0); - reaction1.addNode(new AndOperator()); - assertTrue(comparator.compare(reaction1, reaction2) != 0); - assertTrue(comparator.compare(reaction2, reaction1) != 0); + reaction1 = createReaction(); + reaction2 = createReaction(); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + reaction1.addNode(new AndOperator()); + assertTrue(comparator.compare(reaction1, reaction2) != 0); + assertTrue(comparator.compare(reaction2, reaction1) != 0); } @Test public void testDifferent4() { - try { - Reaction reaction1 = createReaction(); - Reaction reaction2 = createReaction(); - - reaction1.addNode(new AndOperator()); - assertTrue(comparator.compare(reaction1, reaction2) != 0); - assertTrue(comparator.compare(reaction2, reaction1) != 0); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Reaction reaction1 = createReaction(); + Reaction reaction2 = createReaction(); + + reaction1.addNode(new AndOperator()); + assertTrue(comparator.compare(reaction1, reaction2) != 0); + assertTrue(comparator.compare(reaction2, reaction1) != 0); } @Test public void testDifferent2() { - try { - Reaction reaction1 = createReaction(); - assertTrue(comparator.compare(reaction1, null) != 0); - assertTrue(comparator.compare(null, reaction1) != 0); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Reaction reaction1 = createReaction(); + assertTrue(comparator.compare(reaction1, null) != 0); + assertTrue(comparator.compare(null, reaction1) != 0); } @Test public void testDifferent() { - try { + assertTrue(comparator.compare(new TransportReaction(), new StateTransitionReaction()) != 0); - assertTrue(comparator.compare(new TransportReaction(), new StateTransitionReaction()) != 0); - - Reaction reaction1 = createReaction(); - Reaction reaction2 = createReaction(); - - reaction1.setReversible(true); - assertTrue(comparator.compare(reaction1, reaction2) != 0); - assertTrue(comparator.compare(reaction2, reaction1) != 0); + Reaction reaction1 = createReaction(); + Reaction reaction2 = createReaction(); - reaction1 = createReaction(); - reaction2 = createReaction(); + reaction1.setReversible(true); + assertTrue(comparator.compare(reaction1, reaction2) != 0); + assertTrue(comparator.compare(reaction2, reaction1) != 0); - reaction1.addModifier(new Modifier()); - assertTrue(comparator.compare(reaction1, reaction2) != 0); - assertTrue(comparator.compare(reaction2, reaction1) != 0); + reaction1 = createReaction(); + reaction2 = createReaction(); - reaction1 = createReaction(); - reaction2 = createReaction(); + reaction1.addModifier(new Modifier()); + assertTrue(comparator.compare(reaction1, reaction2) != 0); + assertTrue(comparator.compare(reaction2, reaction1) != 0); - reaction1.getModifiers().get(0).getElement().setElementId("dfshkj"); - assertTrue(comparator.compare(reaction1, reaction2) != 0); - assertTrue(comparator.compare(reaction2, reaction1) != 0); + reaction1 = createReaction(); + reaction2 = createReaction(); - reaction1 = createReaction(); - reaction2 = createReaction(); + reaction1.getModifiers().get(0).getElement().setElementId("dfshkj"); + assertTrue(comparator.compare(reaction1, reaction2) != 0); + assertTrue(comparator.compare(reaction2, reaction1) != 0); - reaction1.addReactant(new Reactant()); - assertTrue(comparator.compare(reaction1, reaction2) != 0); - assertTrue(comparator.compare(reaction2, reaction1) != 0); + reaction1 = createReaction(); + reaction2 = createReaction(); - reaction1 = createReaction(); - reaction2 = createReaction(); + reaction1.addReactant(new Reactant()); + assertTrue(comparator.compare(reaction1, reaction2) != 0); + assertTrue(comparator.compare(reaction2, reaction1) != 0); - reaction1.getReactants().get(0).getElement().setElementId("dfshkj"); - assertTrue(comparator.compare(reaction1, reaction2) != 0); - assertTrue(comparator.compare(reaction2, reaction1) != 0); + reaction1 = createReaction(); + reaction2 = createReaction(); - reaction1 = createReaction(); - reaction2 = createReaction(); + reaction1.getReactants().get(0).getElement().setElementId("dfshkj"); + assertTrue(comparator.compare(reaction1, reaction2) != 0); + assertTrue(comparator.compare(reaction2, reaction1) != 0); - reaction1.addProduct(new Product()); - assertTrue(comparator.compare(reaction1, reaction2) != 0); - assertTrue(comparator.compare(reaction2, reaction1) != 0); + reaction1 = createReaction(); + reaction2 = createReaction(); - reaction1 = createReaction(); - reaction2 = createReaction(); + reaction1.addProduct(new Product()); + assertTrue(comparator.compare(reaction1, reaction2) != 0); + assertTrue(comparator.compare(reaction2, reaction1) != 0); - reaction1.getProducts().get(0).getElement().setElementId("dfshkj"); - assertTrue(comparator.compare(reaction1, reaction2) != 0); - assertTrue(comparator.compare(reaction2, reaction1) != 0); + reaction1 = createReaction(); + reaction2 = createReaction(); - reaction1 = createReaction(); - reaction2 = createReaction(); + reaction1.getProducts().get(0).getElement().setElementId("dfshkj"); + assertTrue(comparator.compare(reaction1, reaction2) != 0); + assertTrue(comparator.compare(reaction2, reaction1) != 0); - reaction1.getOperators().get(0).getLine().addPoint(new Point2D.Double(2, 2)); - assertTrue(comparator.compare(reaction1, reaction2) != 0); - assertTrue(comparator.compare(reaction2, reaction1) != 0); + reaction1 = createReaction(); + reaction2 = createReaction(); - reaction1 = createReaction(); - reaction2 = createReaction(); + reaction1.getOperators().get(0).getLine().addPoint(new Point2D.Double(2, 2)); + assertTrue(comparator.compare(reaction1, reaction2) != 0); + assertTrue(comparator.compare(reaction2, reaction1) != 0); - reaction1.getMiriamData().add(new MiriamData(MiriamRelationType.BQ_BIOL_ENCODES, MiriamType.UNKNOWN, "c")); - assertTrue(comparator.compare(reaction1, reaction2) != 0); - assertTrue(comparator.compare(reaction2, reaction1) != 0); + reaction1 = createReaction(); + reaction2 = createReaction(); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + reaction1.getMiriamData().add(new MiriamData(MiriamRelationType.BQ_BIOL_ENCODES, MiriamType.UNKNOWN, "c")); + assertTrue(comparator.compare(reaction1, reaction2) != 0); + assertTrue(comparator.compare(reaction2, reaction1) != 0); } private Reaction createReaction() { @@ -273,17 +235,11 @@ public class ReactionComparatorTest { @Test public void testDifferentNewFields() throws Exception { - try { - Reaction reaction1 = createReaction(); - Reaction reaction2 = createReaction(); - reaction2.setAbbreviation("ABRR"); - - assertTrue(comparator.compare(reaction1, reaction2) != 0); + Reaction reaction1 = createReaction(); + Reaction reaction2 = createReaction(); + reaction2.setAbbreviation("ABRR"); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertTrue(comparator.compare(reaction1, reaction2) != 0); } @Test @@ -309,7 +265,7 @@ public class ReactionComparatorTest { assertEquals(0, comparator.compare(reaction1, reaction2)); assertEquals(0, comparator.compare(reaction2, reaction1)); } - + @Test public void testDifferentCenterLine() { Reaction reaction1 = createReaction(); diff --git a/model/src/test/java/lcsb/mapviewer/model/map/reaction/ReactionNodeComparatorTest.java b/model/src/test/java/lcsb/mapviewer/model/map/reaction/ReactionNodeComparatorTest.java index 2b2f878ba9607affcd4d8248ef463b44e1e43767..6d8ff0496cefd78da6ce20d3d128a9486487024e 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/reaction/ReactionNodeComparatorTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/reaction/ReactionNodeComparatorTest.java @@ -1,20 +1,16 @@ package lcsb.mapviewer.model.map.reaction; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.Assert.*; import java.awt.geom.Point2D; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; +import lcsb.mapviewer.ModelTestFunctions; import lcsb.mapviewer.model.graphics.PolylineData; -import lcsb.mapviewer.model.map.species.Gene; -import lcsb.mapviewer.model.map.species.GenericProtein; -import lcsb.mapviewer.model.map.species.Species; +import lcsb.mapviewer.model.map.species.*; -public class ReactionNodeComparatorTest { +public class ReactionNodeComparatorTest extends ModelTestFunctions { ReactionNodeComparator comparator = new ReactionNodeComparator(); @@ -28,68 +24,57 @@ public class ReactionNodeComparatorTest { @Test public void testEquals() { - try { - assertEquals(0, comparator.compare(new Modifier(), new Modifier())); + assertEquals(0, comparator.compare(new Modifier(), new Modifier())); - ReactionNode operator1 = createNodeOperator(); - ReactionNode operator2 = createNodeOperator(); + ReactionNode operator1 = createNodeOperator(); + ReactionNode operator2 = createNodeOperator(); - assertEquals(0, comparator.compare(operator1, operator2)); + assertEquals(0, comparator.compare(operator1, operator2)); - assertEquals(0, comparator.compare(operator1, operator1)); + assertEquals(0, comparator.compare(operator1, operator1)); - assertEquals(0, comparator.compare(null, null)); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, comparator.compare(null, null)); } @Test public void testDifferent() { - try { - ReactionNode operator1 = createNodeOperator(); - ReactionNode operator2 = createNodeOperator(); + ReactionNode operator1 = createNodeOperator(); + ReactionNode operator2 = createNodeOperator(); - operator1.getLine().addPoint(new Point2D.Double(1, 1)); - assertTrue(comparator.compare(operator1, operator2) != 0); - assertTrue(comparator.compare(operator2, operator1) != 0); + operator1.getLine().addPoint(new Point2D.Double(1, 1)); + assertTrue(comparator.compare(operator1, operator2) != 0); + assertTrue(comparator.compare(operator2, operator1) != 0); - operator1 = createNodeOperator(); - operator2 = createNodeOperator(); + operator1 = createNodeOperator(); + operator2 = createNodeOperator(); - operator1 = new Product(); - assertTrue(comparator.compare(operator1, operator2) != 0); - assertTrue(comparator.compare(operator2, operator1) != 0); + operator1 = new Product(); + assertTrue(comparator.compare(operator1, operator2) != 0); + assertTrue(comparator.compare(operator2, operator1) != 0); - operator1 = createNodeOperator(); - operator2 = createNodeOperator(); + operator1 = createNodeOperator(); + operator2 = createNodeOperator(); - operator1 = new Reactant(); - assertTrue(comparator.compare(operator1, operator2) != 0); - assertTrue(comparator.compare(operator2, operator1) != 0); + operator1 = new Reactant(); + assertTrue(comparator.compare(operator1, operator2) != 0); + assertTrue(comparator.compare(operator2, operator1) != 0); - operator1 = createNodeOperator(); - operator2 = createNodeOperator(); + operator1 = createNodeOperator(); + operator2 = createNodeOperator(); - operator1.setElement(new GenericProtein("new_id")); - assertTrue(comparator.compare(operator1, operator2) != 0); - assertTrue(comparator.compare(operator2, operator1) != 0); + operator1.setElement(new GenericProtein("new_id")); + assertTrue(comparator.compare(operator1, operator2) != 0); + assertTrue(comparator.compare(operator2, operator1) != 0); - operator1 = createNodeOperator(); - operator2 = createNodeOperator(); + operator1 = createNodeOperator(); + operator2 = createNodeOperator(); - operator1.getElement().setName("bla"); - assertTrue(comparator.compare(operator1, operator2) != 0); - assertTrue(comparator.compare(operator2, operator1) != 0); + operator1.getElement().setName("bla"); + assertTrue(comparator.compare(operator1, operator2) != 0); + assertTrue(comparator.compare(operator2, operator1) != 0); - assertTrue(comparator.compare(null, operator1) != 0); - assertTrue(comparator.compare(operator2, null) != 0); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertTrue(comparator.compare(null, operator1) != 0); + assertTrue(comparator.compare(operator2, null) != 0); } private ReactionNode createNodeOperator() { @@ -114,24 +99,18 @@ public class ReactionNodeComparatorTest { @Test public void testDifferentStoichiometry() { - try { - ReactionNode operator1 = createNodeOperator(); - ReactionNode operator2 = createNodeOperator(); - - operator1.setStoichiometry(2.0); + ReactionNode operator1 = createNodeOperator(); + ReactionNode operator2 = createNodeOperator(); - assertTrue(0 != comparator.compare(operator1, operator2)); - assertTrue(0 != comparator.compare(operator2, operator1)); + operator1.setStoichiometry(2.0); - operator1.setStoichiometry(3.0); + assertTrue(0 != comparator.compare(operator1, operator2)); + assertTrue(0 != comparator.compare(operator2, operator1)); - assertTrue(0 != comparator.compare(operator1, operator2)); - assertTrue(0 != comparator.compare(operator2, operator1)); + operator1.setStoichiometry(3.0); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertTrue(0 != comparator.compare(operator1, operator2)); + assertTrue(0 != comparator.compare(operator2, operator1)); } } diff --git a/model/src/test/java/lcsb/mapviewer/model/map/reaction/ReactionTest.java b/model/src/test/java/lcsb/mapviewer/model/map/reaction/ReactionTest.java index fb73cf2862953c5a025711c822576196901016ce..7532f4eb70321e47bab726be1c3ba4f07ca19017 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/reaction/ReactionTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/reaction/ReactionTest.java @@ -1,23 +1,14 @@ package lcsb.mapviewer.model.map.reaction; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import java.awt.geom.Point2D; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; +import java.util.*; import org.apache.commons.lang3.SerializationUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.mockito.Mockito; import lcsb.mapviewer.ModelTestFunctions; @@ -29,9 +20,7 @@ import lcsb.mapviewer.model.map.MiriamData; import lcsb.mapviewer.model.map.MiriamType; import lcsb.mapviewer.model.map.kinetics.SbmlKinetics; import lcsb.mapviewer.model.map.kinetics.SbmlKineticsComparator; -import lcsb.mapviewer.model.map.model.Model; -import lcsb.mapviewer.model.map.model.ModelData; -import lcsb.mapviewer.model.map.model.ModelFullIndexed; +import lcsb.mapviewer.model.map.model.*; import lcsb.mapviewer.model.map.modifier.Catalysis; import lcsb.mapviewer.model.map.species.GenericProtein; import lcsb.mapviewer.model.map.species.Species; @@ -53,231 +42,175 @@ public class ReactionTest extends ModelTestFunctions { @Test public void testContainsElement() { - try { - Reaction reaction = new Reaction(); - assertFalse(reaction.containsElement(species)); - Modifier modifier = new Catalysis(species); - reaction.addModifier(modifier); - assertTrue(reaction.containsElement(species)); - assertFalse(reaction.containsElement(new GenericProtein("id"))); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Reaction reaction = new Reaction(); + assertFalse(reaction.containsElement(species)); + Modifier modifier = new Catalysis(species); + reaction.addModifier(modifier); + assertTrue(reaction.containsElement(species)); + assertFalse(reaction.containsElement(new GenericProtein("id"))); } @Test public void testComparator() { - try { - Reaction reaction1 = new Reaction(); - reaction1.setIdReaction("2"); - Reaction reaction2 = new Reaction(); - reaction2.setIdReaction("1"); - Reaction reaction3 = new Reaction(); - reaction3.setIdReaction("3"); - List<Reaction> reactions = new ArrayList<>(); - reactions.add(reaction1); - reactions.add(reaction2); - reactions.add(reaction3); - Collections.sort(reactions, Reaction.ID_COMPARATOR); - assertEquals(reaction2, reactions.get(0)); - assertEquals(reaction1, reactions.get(1)); - assertEquals(reaction3, reactions.get(2)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Reaction reaction1 = new Reaction(); + reaction1.setIdReaction("2"); + Reaction reaction2 = new Reaction(); + reaction2.setIdReaction("1"); + Reaction reaction3 = new Reaction(); + reaction3.setIdReaction("3"); + List<Reaction> reactions = new ArrayList<>(); + reactions.add(reaction1); + reactions.add(reaction2); + reactions.add(reaction3); + Collections.sort(reactions, Reaction.ID_COMPARATOR); + assertEquals(reaction2, reactions.get(0)); + assertEquals(reaction1, reactions.get(1)); + assertEquals(reaction3, reactions.get(2)); } @Test public void testConstructor() { - try { - Reaction reaction1 = createReaction(); - reaction1.addMiriamData(new MiriamData()); - reaction1.addSynonym("s"); - Reaction reaction2 = new Reaction(reaction1); - - assertEquals(1, reaction2.getMiriamData().size()); - assertEquals(1, reaction2.getSynonyms().size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Reaction reaction1 = createReaction(); + reaction1.addMiriamData(new MiriamData()); + reaction1.addSynonym("s"); + Reaction reaction2 = new Reaction(reaction1); + + assertEquals(1, reaction2.getMiriamData().size()); + assertEquals(1, reaction2.getSynonyms().size()); } @Test public void testGetDistanceFromPoint() { - try { - Reaction reaction1 = new Reaction(); - Reactant reactant = new Reactant(); - PolylineData line = new PolylineData(new Point2D.Double(0.0, 0.0), new Point2D.Double(2.0, 0.0)); - reactant.setLine(line); - reaction1.addReactant(reactant); - - assertEquals(0.0, reaction1.getDistanceFromPoint(new Point2D.Double(0.0, 0.0)), Configuration.EPSILON); - assertEquals(0.0, reaction1.getDistanceFromPoint(new Point2D.Double(1.0, 0.0)), Configuration.EPSILON); - assertEquals(1.0, reaction1.getDistanceFromPoint(new Point2D.Double(1.0, 1.0)), Configuration.EPSILON); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Reaction reaction1 = new Reaction(); + Reactant reactant = new Reactant(); + PolylineData line = new PolylineData(new Point2D.Double(0.0, 0.0), new Point2D.Double(2.0, 0.0)); + reactant.setLine(line); + reaction1.addReactant(reactant); + + assertEquals(0.0, reaction1.getDistanceFromPoint(new Point2D.Double(0.0, 0.0)), Configuration.EPSILON); + assertEquals(0.0, reaction1.getDistanceFromPoint(new Point2D.Double(1.0, 0.0)), Configuration.EPSILON); + assertEquals(1.0, reaction1.getDistanceFromPoint(new Point2D.Double(1.0, 1.0)), Configuration.EPSILON); } @Test public void testGetClosestPointTo() { - try { - Reaction reaction1 = new Reaction(); - Reactant reactant = new Reactant(); - PolylineData line = new PolylineData(new Point2D.Double(0.0, 0.0), new Point2D.Double(2.0, 0.0)); - reactant.setLine(line); - reaction1.addReactant(reactant); - - assertEquals(0.0, - reaction1.getClosestPointTo(new Point2D.Double(0.0, 0.0)).distance(new Point2D.Double(0.0, 0.0)), - Configuration.EPSILON); - assertEquals(0.0, - reaction1.getClosestPointTo(new Point2D.Double(1.0, 0.0)).distance(new Point2D.Double(1.0, 0.0)), - Configuration.EPSILON); - assertEquals(0.0, - reaction1.getClosestPointTo(new Point2D.Double(1.0, 1.0)).distance(new Point2D.Double(1.0, 0.0)), - Configuration.EPSILON); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Reaction reaction1 = new Reaction(); + Reactant reactant = new Reactant(); + PolylineData line = new PolylineData(new Point2D.Double(0.0, 0.0), new Point2D.Double(2.0, 0.0)); + reactant.setLine(line); + reaction1.addReactant(reactant); + + assertEquals(0.0, + reaction1.getClosestPointTo(new Point2D.Double(0.0, 0.0)).distance(new Point2D.Double(0.0, 0.0)), + Configuration.EPSILON); + assertEquals(0.0, + reaction1.getClosestPointTo(new Point2D.Double(1.0, 0.0)).distance(new Point2D.Double(1.0, 0.0)), + Configuration.EPSILON); + assertEquals(0.0, + reaction1.getClosestPointTo(new Point2D.Double(1.0, 1.0)).distance(new Point2D.Double(1.0, 0.0)), + Configuration.EPSILON); } @Test public void testAddMiriam() { - try { - Reaction reaction1 = new Reaction(); - - MiriamData md = new MiriamData(MiriamType.CAS, "1"); - reaction1.addMiriamData(md); + Reaction reaction1 = new Reaction(); - assertEquals(1, reaction1.getMiriamData().size()); + MiriamData md = new MiriamData(MiriamType.CAS, "1"); + reaction1.addMiriamData(md); - reaction1.addMiriamData(md); - assertEquals(1, reaction1.getMiriamData().size()); - assertEquals(1, getWarnings().size()); + assertEquals(1, reaction1.getMiriamData().size()); - List<MiriamData> list = new ArrayList<>(); - list.add(md); + reaction1.addMiriamData(md); + assertEquals(1, reaction1.getMiriamData().size()); + assertEquals(1, getWarnings().size()); - reaction1.addMiriamData(list); - assertEquals(2, getWarnings().size()); + List<MiriamData> list = new ArrayList<>(); + list.add(md); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + reaction1.addMiriamData(list); + assertEquals(2, getWarnings().size()); } @Test public void testGetters() { - try { - Reaction reaction1 = new Reaction(); - - assertNotNull(reaction1.getStringType()); - assertNull(reaction1.getReactionRect()); - - int id = 61; - List<AbstractNode> nodes = new ArrayList<>(); - String notes = "dfp"; - - ModelData data = new ModelData(); - Model model = new ModelFullIndexed(data); - String symbol = "sybm"; - String formula = "form"; - Integer mechanicalConfidenceScore = 9908; - Double lowerBound = 9.2; - Double upperBound = 9.2; - String subsystem = "ssyst"; - String geneProteinReaction = "GPR"; - List<String> synonyms = new ArrayList<>(); - - reaction1.setId(id); - reaction1.setNodes(nodes); - reaction1.setNotes(notes); - reaction1.setModel(model); - assertEquals(model, reaction1.getModel()); - reaction1.setModelData(data); - assertEquals(data, reaction1.getModelData()); - reaction1.setSymbol(symbol); - assertEquals(symbol, reaction1.getSymbol()); - reaction1.setFormula(formula); - assertEquals(formula, reaction1.getFormula()); - reaction1.setMechanicalConfidenceScore(mechanicalConfidenceScore); - assertEquals(mechanicalConfidenceScore, reaction1.getMechanicalConfidenceScore()); - reaction1.setLowerBound(lowerBound); - assertEquals(lowerBound, reaction1.getLowerBound()); - reaction1.setUpperBound(upperBound); - assertEquals(upperBound, reaction1.getUpperBound()); - reaction1.setSubsystem(subsystem); - assertEquals(subsystem, reaction1.getSubsystem()); - reaction1.setGeneProteinReaction(geneProteinReaction); - assertEquals(geneProteinReaction, reaction1.getGeneProteinReaction()); - reaction1.setSynonyms(synonyms); - assertEquals(synonyms, reaction1.getSynonyms()); - - assertEquals(id, reaction1.getId()); - assertEquals(nodes, reaction1.getNodes()); - assertEquals(notes, reaction1.getNotes()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Reaction reaction1 = new Reaction(); + + assertNotNull(reaction1.getStringType()); + assertNull(reaction1.getReactionRect()); + + int id = 61; + List<AbstractNode> nodes = new ArrayList<>(); + String notes = "dfp"; + + ModelData data = new ModelData(); + Model model = new ModelFullIndexed(data); + String symbol = "sybm"; + String formula = "form"; + Integer mechanicalConfidenceScore = 9908; + Double lowerBound = 9.2; + Double upperBound = 9.2; + String subsystem = "ssyst"; + String geneProteinReaction = "GPR"; + List<String> synonyms = new ArrayList<>(); + + reaction1.setId(id); + reaction1.setNodes(nodes); + reaction1.setNotes(notes); + reaction1.setModel(model); + assertEquals(model, reaction1.getModel()); + reaction1.setModelData(data); + assertEquals(data, reaction1.getModelData()); + reaction1.setSymbol(symbol); + assertEquals(symbol, reaction1.getSymbol()); + reaction1.setFormula(formula); + assertEquals(formula, reaction1.getFormula()); + reaction1.setMechanicalConfidenceScore(mechanicalConfidenceScore); + assertEquals(mechanicalConfidenceScore, reaction1.getMechanicalConfidenceScore()); + reaction1.setLowerBound(lowerBound); + assertEquals(lowerBound, reaction1.getLowerBound()); + reaction1.setUpperBound(upperBound); + assertEquals(upperBound, reaction1.getUpperBound()); + reaction1.setSubsystem(subsystem); + assertEquals(subsystem, reaction1.getSubsystem()); + reaction1.setGeneProteinReaction(geneProteinReaction); + assertEquals(geneProteinReaction, reaction1.getGeneProteinReaction()); + reaction1.setSynonyms(synonyms); + assertEquals(synonyms, reaction1.getSynonyms()); + + assertEquals(id, reaction1.getId()); + assertEquals(nodes, reaction1.getNodes()); + assertEquals(notes, reaction1.getNotes()); } @Test public void testVisibilityLevel() { - try { - Reaction reaction1 = new Reaction(); - assertEquals("", reaction1.getVisibilityLevel()); - - reaction1.setVisibilityLevel(1); - assertEquals("1", reaction1.getVisibilityLevel()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Reaction reaction1 = new Reaction(); + assertEquals("", reaction1.getVisibilityLevel()); + + reaction1.setVisibilityLevel(1); + assertEquals("1", reaction1.getVisibilityLevel()); } @Test public void testSerialization() { - try { - SerializationUtils.serialize(new Reaction()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + SerializationUtils.serialize(new Reaction()); } @Test public void testRemoveModifier() { - try { - Reaction reaction = new Reaction(); - Modifier modifier = new Modifier(); - reaction.addModifier(modifier); - assertEquals(1, reaction.getModifiers().size()); - reaction.removeModifier(modifier); - assertEquals(0, reaction.getModifiers().size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Reaction reaction = new Reaction(); + Modifier modifier = new Modifier(); + reaction.addModifier(modifier); + assertEquals(1, reaction.getModifiers().size()); + reaction.removeModifier(modifier); + assertEquals(0, reaction.getModifiers().size()); } @Test public void testCopy() { - try { - Reaction original = createReaction(); - Reaction copy = original.copy(); - assertNotNull(copy); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Reaction original = createReaction(); + Reaction copy = original.copy(); + assertNotNull(copy); } private Reaction createReaction() { @@ -289,43 +222,26 @@ public class ReactionTest extends ModelTestFunctions { @Test public void testCopyWithKinetics() { - try { - Reaction original = createReaction(); - original.setKinetics(new SbmlKinetics()); - Reaction copy = original.copy(); - SbmlKineticsComparator kineticsComparator = new SbmlKineticsComparator(); - assertEquals(0, kineticsComparator.compare(original.getKinetics(), copy.getKinetics())); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Reaction original = createReaction(); + original.setKinetics(new SbmlKinetics()); + Reaction copy = original.copy(); + SbmlKineticsComparator kineticsComparator = new SbmlKineticsComparator(); + assertEquals(0, kineticsComparator.compare(original.getKinetics(), copy.getKinetics())); } @Test public void testCopyWithCenterLine() { - try { - Reaction original = createReaction(); - original.setKinetics(new SbmlKinetics()); - original.setLine(new PolylineData()); - Reaction copy = original.copy(); - PolylineDataComparator lineComparator = new PolylineDataComparator(); - assertEquals(0, lineComparator.compare(original.getLine(), copy.getLine())); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Reaction original = createReaction(); + original.setKinetics(new SbmlKinetics()); + original.setLine(new PolylineData()); + Reaction copy = original.copy(); + PolylineDataComparator lineComparator = new PolylineDataComparator(); + assertEquals(0, lineComparator.compare(original.getLine(), copy.getLine())); } - @Test + @Test(expected = NotImplementedException.class) public void testInvalidCopy() { - try { - Mockito.spy(new Reaction()).copy(); - fail("Exception expected"); - } catch (NotImplementedException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Mockito.spy(new Reaction()).copy(); } } diff --git a/model/src/test/java/lcsb/mapviewer/model/map/reaction/SplitOperatorTest.java b/model/src/test/java/lcsb/mapviewer/model/map/reaction/SplitOperatorTest.java index 63d17b64cf6bdc8cd9f35a72bff1f920f65f3e4a..aea738e4512a7f7beff223a39ed52791f9969b0b 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/reaction/SplitOperatorTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/reaction/SplitOperatorTest.java @@ -1,18 +1,16 @@ package lcsb.mapviewer.model.map.reaction; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.mockito.Mockito; +import lcsb.mapviewer.ModelTestFunctions; import lcsb.mapviewer.common.exception.NotImplementedException; import lcsb.mapviewer.model.graphics.PolylineData; -public class SplitOperatorTest { +public class SplitOperatorTest extends ModelTestFunctions { @Before public void setUp() throws Exception { @@ -24,61 +22,34 @@ public class SplitOperatorTest { @Test public void testSerialization() { - try { - SerializationUtils.serialize(new SplitOperator()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + SerializationUtils.serialize(new SplitOperator()); } @Test public void testConstructor() { - try { - SplitOperator op = new SplitOperator(); - op.setLine(new PolylineData()); - SplitOperator operator = new SplitOperator(op); - assertNotNull(operator); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + SplitOperator op = new SplitOperator(); + op.setLine(new PolylineData()); + SplitOperator operator = new SplitOperator(op); + assertNotNull(operator); } @Test public void testGetters() { - try { - assertNotNull(new SplitOperator().getSBGNOperatorText()); - assertNotNull(new SplitOperator().getOperatorText()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertNotNull(new SplitOperator().getSBGNOperatorText()); + assertNotNull(new SplitOperator().getOperatorText()); } @Test public void testCopy1() { - try { - SplitOperator op = new SplitOperator(); - op.setLine(new PolylineData()); - SplitOperator operator = op.copy(); - assertNotNull(operator); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + SplitOperator op = new SplitOperator(); + op.setLine(new PolylineData()); + SplitOperator operator = op.copy(); + assertNotNull(operator); } - @Test + @Test(expected = NotImplementedException.class) public void testCopy2() { - try { - Mockito.mock(SplitOperator.class, Mockito.CALLS_REAL_METHODS).copy(); - fail("Exception expected"); - } catch (NotImplementedException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Mockito.mock(SplitOperator.class, Mockito.CALLS_REAL_METHODS).copy(); } } diff --git a/model/src/test/java/lcsb/mapviewer/model/map/reaction/TruncationOperatorTest.java b/model/src/test/java/lcsb/mapviewer/model/map/reaction/TruncationOperatorTest.java index 5e30099cc98d306c210d1ea3cab3d9ff2a126b30..29b6fdfcf9119893c4ed0f9369008e9b96074836 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/reaction/TruncationOperatorTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/reaction/TruncationOperatorTest.java @@ -1,18 +1,16 @@ package lcsb.mapviewer.model.map.reaction; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.mockito.Mockito; +import lcsb.mapviewer.ModelTestFunctions; import lcsb.mapviewer.common.exception.NotImplementedException; import lcsb.mapviewer.model.graphics.PolylineData; -public class TruncationOperatorTest { +public class TruncationOperatorTest extends ModelTestFunctions { @Before public void setUp() throws Exception { @@ -24,61 +22,34 @@ public class TruncationOperatorTest { @Test public void testSerialization() { - try { - SerializationUtils.serialize(new TruncationOperator()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + SerializationUtils.serialize(new TruncationOperator()); } @Test public void testConstructor() { - try { - TruncationOperator op = new TruncationOperator(); - op.setLine(new PolylineData()); - TruncationOperator operator = new TruncationOperator(op); - assertNotNull(operator); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + TruncationOperator op = new TruncationOperator(); + op.setLine(new PolylineData()); + TruncationOperator operator = new TruncationOperator(op); + assertNotNull(operator); } @Test public void testGetters() { - try { - assertNotNull(new TruncationOperator().getSBGNOperatorText()); - assertNotNull(new TruncationOperator().getOperatorText()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertNotNull(new TruncationOperator().getSBGNOperatorText()); + assertNotNull(new TruncationOperator().getOperatorText()); } @Test public void testCopy1() { - try { - TruncationOperator op = new TruncationOperator(); - op.setLine(new PolylineData()); - TruncationOperator operator = op.copy(); - assertNotNull(operator); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + TruncationOperator op = new TruncationOperator(); + op.setLine(new PolylineData()); + TruncationOperator operator = op.copy(); + assertNotNull(operator); } - @Test + @Test(expected = NotImplementedException.class) public void testCopy2() { - try { - Mockito.mock(TruncationOperator.class, Mockito.CALLS_REAL_METHODS).copy(); - fail("Exception expected"); - } catch (NotImplementedException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Mockito.mock(TruncationOperator.class, Mockito.CALLS_REAL_METHODS).copy(); } } diff --git a/model/src/test/java/lcsb/mapviewer/model/map/reaction/UnknownOperatorTest.java b/model/src/test/java/lcsb/mapviewer/model/map/reaction/UnknownOperatorTest.java index 046b15620ff818ab6ae4b3b8f0285396a7e63d15..4e182a1413526ce933173bedf6f0c128728241a6 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/reaction/UnknownOperatorTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/reaction/UnknownOperatorTest.java @@ -1,19 +1,16 @@ package lcsb.mapviewer.model.map.reaction; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.mockito.Mockito; +import lcsb.mapviewer.ModelTestFunctions; import lcsb.mapviewer.common.exception.NotImplementedException; import lcsb.mapviewer.model.graphics.PolylineData; -public class UnknownOperatorTest { +public class UnknownOperatorTest extends ModelTestFunctions { @Before public void setUp() throws Exception { @@ -25,61 +22,34 @@ public class UnknownOperatorTest { @Test public void testSerialization() { - try { - SerializationUtils.serialize(new UnknownOperator()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + SerializationUtils.serialize(new UnknownOperator()); } @Test public void testConstructor() { - try { - UnknownOperator op = new UnknownOperator(); - op.setLine(new PolylineData()); - UnknownOperator operator = new UnknownOperator(op); - assertNotNull(operator); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + UnknownOperator op = new UnknownOperator(); + op.setLine(new PolylineData()); + UnknownOperator operator = new UnknownOperator(op); + assertNotNull(operator); } @Test public void testGetters() { - try { - assertFalse("".equals(new UnknownOperator().getSBGNOperatorText())); - assertFalse("".equals(new UnknownOperator().getOperatorText())); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertFalse("".equals(new UnknownOperator().getSBGNOperatorText())); + assertFalse("".equals(new UnknownOperator().getOperatorText())); } @Test public void testCopy1() { - try { - UnknownOperator op = new UnknownOperator(); - op.setLine(new PolylineData()); - UnknownOperator operator = op.copy(); - assertNotNull(operator); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + UnknownOperator op = new UnknownOperator(); + op.setLine(new PolylineData()); + UnknownOperator operator = op.copy(); + assertNotNull(operator); } - @Test + @Test(expected = NotImplementedException.class) public void testCopy2() { - try { - Mockito.mock(UnknownOperator.class, Mockito.CALLS_REAL_METHODS).copy(); - fail("Exception expected"); - } catch (NotImplementedException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Mockito.mock(UnknownOperator.class, Mockito.CALLS_REAL_METHODS).copy(); } } diff --git a/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/DissociationReactionTest.java b/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/DissociationReactionTest.java index b3f61c48022497fc705408432abc9d0d62e1bf9a..2a3c6954a8486e63426f4e06fa95bc4c63d4798e 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/DissociationReactionTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/DissociationReactionTest.java @@ -1,21 +1,17 @@ package lcsb.mapviewer.model.map.reaction.type; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.mockito.Mockito; +import lcsb.mapviewer.ModelTestFunctions; import lcsb.mapviewer.common.exception.InvalidArgumentException; import lcsb.mapviewer.common.exception.NotImplementedException; -import lcsb.mapviewer.model.map.reaction.Product; -import lcsb.mapviewer.model.map.reaction.Reactant; -import lcsb.mapviewer.model.map.reaction.Reaction; +import lcsb.mapviewer.model.map.reaction.*; -public class DissociationReactionTest { +public class DissociationReactionTest extends ModelTestFunctions { @Before public void setUp() throws Exception { @@ -27,97 +23,53 @@ public class DissociationReactionTest { @Test public void testSerialization() { - try { - SerializationUtils.serialize(new DissociationReaction()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + SerializationUtils.serialize(new DissociationReaction()); } @Test public void testGetters() { - try { - Reaction reaction = new DissociationReaction(); - assertNotNull(reaction.getStringType()); - assertNotNull(reaction.getReactionRect()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Reaction reaction = new DissociationReaction(); + assertNotNull(reaction.getStringType()); + assertNotNull(reaction.getReactionRect()); } - @Test + @Test(expected = InvalidArgumentException.class) public void testConstructorWithInvalidArg() { - try { - Reaction reaction = new Reaction(); - new DissociationReaction(reaction); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Reaction reaction = new Reaction(); + new DissociationReaction(reaction); } - @Test + @Test(expected = InvalidArgumentException.class) public void testConstructorWithInvalidArg2() { - try { - Reaction reaction = new Reaction(); - reaction.addProduct(new Product()); - reaction.addProduct(new Product()); - new DissociationReaction(reaction); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Reaction reaction = new Reaction(); + reaction.addProduct(new Product()); + reaction.addProduct(new Product()); + new DissociationReaction(reaction); } @Test public void testConstructor() { - try { - Reaction reaction = new Reaction(); - reaction.addProduct(new Product()); - reaction.addProduct(new Product()); - reaction.addReactant(new Reactant()); - DissociationReaction validReaction = new DissociationReaction(reaction); - assertNotNull(validReaction); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Reaction reaction = new Reaction(); + reaction.addProduct(new Product()); + reaction.addProduct(new Product()); + reaction.addReactant(new Reactant()); + DissociationReaction validReaction = new DissociationReaction(reaction); + assertNotNull(validReaction); } @Test public void testCopy() { - try { - DissociationReaction original = new DissociationReaction(); - original.addProduct(new Product()); - original.addProduct(new Product()); - original.addReactant(new Reactant()); - DissociationReaction product = original.copy(); - assertNotNull(product); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + DissociationReaction original = new DissociationReaction(); + original.addProduct(new Product()); + original.addProduct(new Product()); + original.addReactant(new Reactant()); + DissociationReaction product = original.copy(); + assertNotNull(product); } - @Test + @Test(expected = NotImplementedException.class) public void testInvalidCopy() { - try { - Mockito.spy(new DissociationReaction()).copy(); - fail("Exception expected"); - } catch (NotImplementedException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Mockito.spy(new DissociationReaction()).copy(); } } diff --git a/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/HeterodimerAssociationReactionTest.java b/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/HeterodimerAssociationReactionTest.java index 1ef9331a159096f44f7ca10a07bb2afeb0879bfd..4c71a76c5de2029ad24793d49610e58348b97a67 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/HeterodimerAssociationReactionTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/HeterodimerAssociationReactionTest.java @@ -1,21 +1,17 @@ package lcsb.mapviewer.model.map.reaction.type; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.mockito.Mockito; +import lcsb.mapviewer.ModelTestFunctions; import lcsb.mapviewer.common.exception.InvalidArgumentException; import lcsb.mapviewer.common.exception.NotImplementedException; -import lcsb.mapviewer.model.map.reaction.Product; -import lcsb.mapviewer.model.map.reaction.Reactant; -import lcsb.mapviewer.model.map.reaction.Reaction; +import lcsb.mapviewer.model.map.reaction.*; -public class HeterodimerAssociationReactionTest { +public class HeterodimerAssociationReactionTest extends ModelTestFunctions { @Before public void setUp() throws Exception { @@ -27,97 +23,53 @@ public class HeterodimerAssociationReactionTest { @Test public void testSerialization() { - try { - SerializationUtils.serialize(new HeterodimerAssociationReaction()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + SerializationUtils.serialize(new HeterodimerAssociationReaction()); } @Test public void testGetters() { - try { - Reaction reaction = new HeterodimerAssociationReaction(); - assertNotNull(reaction.getStringType()); - assertNotNull(reaction.getReactionRect()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Reaction reaction = new HeterodimerAssociationReaction(); + assertNotNull(reaction.getStringType()); + assertNotNull(reaction.getReactionRect()); } - @Test + @Test(expected = InvalidArgumentException.class) public void testConstructorWithInvalidArg() { - try { - Reaction reaction = new Reaction(); - new HeterodimerAssociationReaction(reaction); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Reaction reaction = new Reaction(); + new HeterodimerAssociationReaction(reaction); } - @Test + @Test(expected = InvalidArgumentException.class) public void testConstructorWithInvalidArg2() { - try { - Reaction reaction = new Reaction(); - reaction.addProduct(new Product()); - reaction.addReactant(new Reactant()); - new HeterodimerAssociationReaction(reaction); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Reaction reaction = new Reaction(); + reaction.addProduct(new Product()); + reaction.addReactant(new Reactant()); + new HeterodimerAssociationReaction(reaction); } @Test public void testConstructor() { - try { - Reaction reaction = new Reaction(); - reaction.addProduct(new Product()); - reaction.addReactant(new Reactant()); - reaction.addReactant(new Reactant()); - HeterodimerAssociationReaction validReaction = new HeterodimerAssociationReaction(reaction); - assertNotNull(validReaction); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Reaction reaction = new Reaction(); + reaction.addProduct(new Product()); + reaction.addReactant(new Reactant()); + reaction.addReactant(new Reactant()); + HeterodimerAssociationReaction validReaction = new HeterodimerAssociationReaction(reaction); + assertNotNull(validReaction); } @Test public void testCopy() { - try { - HeterodimerAssociationReaction original = new HeterodimerAssociationReaction(); - original.addProduct(new Product()); - original.addReactant(new Reactant()); - original.addReactant(new Reactant()); - HeterodimerAssociationReaction product = original.copy(); - assertNotNull(product); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + HeterodimerAssociationReaction original = new HeterodimerAssociationReaction(); + original.addProduct(new Product()); + original.addReactant(new Reactant()); + original.addReactant(new Reactant()); + HeterodimerAssociationReaction product = original.copy(); + assertNotNull(product); } - @Test + @Test(expected = NotImplementedException.class) public void testInvalidCopy() { - try { - Mockito.spy(new HeterodimerAssociationReaction()).copy(); - fail("Exception expected"); - } catch (NotImplementedException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Mockito.spy(new HeterodimerAssociationReaction()).copy(); } } diff --git a/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/KnownTransitionOmittedReactionTest.java b/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/KnownTransitionOmittedReactionTest.java index 09796235aa451e48b08dbc232b5cc489ffa60dc0..485be3d4dfc7de1b43c87145a27a155220540c16 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/KnownTransitionOmittedReactionTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/KnownTransitionOmittedReactionTest.java @@ -1,21 +1,17 @@ package lcsb.mapviewer.model.map.reaction.type; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.mockito.Mockito; +import lcsb.mapviewer.ModelTestFunctions; import lcsb.mapviewer.common.exception.InvalidArgumentException; import lcsb.mapviewer.common.exception.NotImplementedException; -import lcsb.mapviewer.model.map.reaction.Product; -import lcsb.mapviewer.model.map.reaction.Reactant; -import lcsb.mapviewer.model.map.reaction.Reaction; +import lcsb.mapviewer.model.map.reaction.*; -public class KnownTransitionOmittedReactionTest { +public class KnownTransitionOmittedReactionTest extends ModelTestFunctions { @Before public void setUp() throws Exception { @@ -27,95 +23,51 @@ public class KnownTransitionOmittedReactionTest { @Test public void testSerialization() { - try { - SerializationUtils.serialize(new KnownTransitionOmittedReaction()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + SerializationUtils.serialize(new KnownTransitionOmittedReaction()); } - @Test + @Test(expected = InvalidArgumentException.class) public void testConstructorWithInvalidArg() { - try { - Reaction reaction = new Reaction(); - new KnownTransitionOmittedReaction(reaction); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Reaction reaction = new Reaction(); + new KnownTransitionOmittedReaction(reaction); } - @Test + @Test(expected = InvalidArgumentException.class) public void testConstructorWithInvalidArg2() { - try { - Reaction reaction = new Reaction(); - reaction.addProduct(new Product()); - new KnownTransitionOmittedReaction(reaction); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Reaction reaction = new Reaction(); + reaction.addProduct(new Product()); + new KnownTransitionOmittedReaction(reaction); } @Test public void testConstructor() { - try { - Reaction reaction = new Reaction(); - reaction.addProduct(new Product()); - reaction.addReactant(new Reactant()); - KnownTransitionOmittedReaction validReaction = new KnownTransitionOmittedReaction(reaction); - assertNotNull(validReaction); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Reaction reaction = new Reaction(); + reaction.addProduct(new Product()); + reaction.addReactant(new Reactant()); + KnownTransitionOmittedReaction validReaction = new KnownTransitionOmittedReaction(reaction); + assertNotNull(validReaction); } @Test public void testCopy() { - try { - KnownTransitionOmittedReaction original = new KnownTransitionOmittedReaction(); - original.addProduct(new Product()); - original.addReactant(new Reactant()); - original.addReactant(new Reactant()); - KnownTransitionOmittedReaction product = original.copy(); - assertNotNull(product); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + KnownTransitionOmittedReaction original = new KnownTransitionOmittedReaction(); + original.addProduct(new Product()); + original.addReactant(new Reactant()); + original.addReactant(new Reactant()); + KnownTransitionOmittedReaction product = original.copy(); + assertNotNull(product); } - @Test + @Test(expected = NotImplementedException.class) public void testInvalidCopy() { - try { - Mockito.spy(new KnownTransitionOmittedReaction()).copy(); - fail("Exception expected"); - } catch (NotImplementedException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Mockito.spy(new KnownTransitionOmittedReaction()).copy(); } @Test public void testGetters() { - try { - KnownTransitionOmittedReaction original = new KnownTransitionOmittedReaction(); - assertNotNull(original.getReactionRect()); - assertNotNull(original.getStringType()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + KnownTransitionOmittedReaction original = new KnownTransitionOmittedReaction(); + assertNotNull(original.getReactionRect()); + assertNotNull(original.getStringType()); } } diff --git a/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/NegativeInfluenceReactionTest.java b/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/NegativeInfluenceReactionTest.java index 1f4b88049cb1fc627255d7632a25e9ea1304d815..0e19c70bf1acb50a1055ebcc45a30137a606bf81 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/NegativeInfluenceReactionTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/NegativeInfluenceReactionTest.java @@ -1,22 +1,17 @@ package lcsb.mapviewer.model.map.reaction.type; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.mockito.Mockito; +import lcsb.mapviewer.ModelTestFunctions; import lcsb.mapviewer.common.exception.InvalidArgumentException; import lcsb.mapviewer.common.exception.NotImplementedException; -import lcsb.mapviewer.model.map.reaction.Product; -import lcsb.mapviewer.model.map.reaction.Reactant; -import lcsb.mapviewer.model.map.reaction.Reaction; +import lcsb.mapviewer.model.map.reaction.*; -public class NegativeInfluenceReactionTest { +public class NegativeInfluenceReactionTest extends ModelTestFunctions { @Before public void setUp() throws Exception { @@ -28,95 +23,51 @@ public class NegativeInfluenceReactionTest { @Test public void testSerialization() { - try { - SerializationUtils.serialize(new NegativeInfluenceReaction()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + SerializationUtils.serialize(new NegativeInfluenceReaction()); } - @Test + @Test(expected = InvalidArgumentException.class) public void testConstructorWithInvalidArg() { - try { - Reaction reaction = new Reaction(); - new NegativeInfluenceReaction(reaction); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Reaction reaction = new Reaction(); + new NegativeInfluenceReaction(reaction); } - @Test + @Test(expected = InvalidArgumentException.class) public void testConstructorWithInvalidArg2() { - try { - Reaction reaction = new Reaction(); - reaction.addProduct(new Product()); - new NegativeInfluenceReaction(reaction); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Reaction reaction = new Reaction(); + reaction.addProduct(new Product()); + new NegativeInfluenceReaction(reaction); } @Test public void testConstructor() { - try { - Reaction reaction = new Reaction(); - reaction.addProduct(new Product()); - reaction.addReactant(new Reactant()); - NegativeInfluenceReaction validReaction = new NegativeInfluenceReaction(reaction); - assertNotNull(validReaction); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Reaction reaction = new Reaction(); + reaction.addProduct(new Product()); + reaction.addReactant(new Reactant()); + NegativeInfluenceReaction validReaction = new NegativeInfluenceReaction(reaction); + assertNotNull(validReaction); } @Test public void testCopy() { - try { - NegativeInfluenceReaction original = new NegativeInfluenceReaction(); - original.addProduct(new Product()); - original.addReactant(new Reactant()); - original.addReactant(new Reactant()); - NegativeInfluenceReaction product = original.copy(); - assertNotNull(product); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + NegativeInfluenceReaction original = new NegativeInfluenceReaction(); + original.addProduct(new Product()); + original.addReactant(new Reactant()); + original.addReactant(new Reactant()); + NegativeInfluenceReaction product = original.copy(); + assertNotNull(product); } - @Test + @Test(expected = NotImplementedException.class) public void testInvalidCopy() { - try { - Mockito.spy(new NegativeInfluenceReaction()).copy(); - fail("Exception expected"); - } catch (NotImplementedException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Mockito.spy(new NegativeInfluenceReaction()).copy(); } @Test public void testGetters() { - try { - NegativeInfluenceReaction original = new NegativeInfluenceReaction(); - assertNull(original.getReactionRect()); - assertNotNull(original.getStringType()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + NegativeInfluenceReaction original = new NegativeInfluenceReaction(); + assertNull(original.getReactionRect()); + assertNotNull(original.getStringType()); } } diff --git a/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/PositiveInfluenceReactionTest.java b/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/PositiveInfluenceReactionTest.java index d0685b4988f203a0c9b36f6878a9213dafc1a016..626447a36a13dfd6b50ce244153e07227306f101 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/PositiveInfluenceReactionTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/PositiveInfluenceReactionTest.java @@ -1,22 +1,17 @@ package lcsb.mapviewer.model.map.reaction.type; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.mockito.Mockito; +import lcsb.mapviewer.ModelTestFunctions; import lcsb.mapviewer.common.exception.InvalidArgumentException; import lcsb.mapviewer.common.exception.NotImplementedException; -import lcsb.mapviewer.model.map.reaction.Product; -import lcsb.mapviewer.model.map.reaction.Reactant; -import lcsb.mapviewer.model.map.reaction.Reaction; +import lcsb.mapviewer.model.map.reaction.*; -public class PositiveInfluenceReactionTest { +public class PositiveInfluenceReactionTest extends ModelTestFunctions { @Before public void setUp() throws Exception { @@ -28,95 +23,51 @@ public class PositiveInfluenceReactionTest { @Test public void testSerialization() { - try { - SerializationUtils.serialize(new PositiveInfluenceReaction()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + SerializationUtils.serialize(new PositiveInfluenceReaction()); } - @Test + @Test(expected = InvalidArgumentException.class) public void testConstructorWithInvalidArg() { - try { - Reaction reaction = new Reaction(); - new PositiveInfluenceReaction(reaction); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Reaction reaction = new Reaction(); + new PositiveInfluenceReaction(reaction); } - @Test + @Test(expected = InvalidArgumentException.class) public void testConstructorWithInvalidArg2() { - try { - Reaction reaction = new Reaction(); - reaction.addProduct(new Product()); - new PositiveInfluenceReaction(reaction); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Reaction reaction = new Reaction(); + reaction.addProduct(new Product()); + new PositiveInfluenceReaction(reaction); } @Test public void testConstructor() { - try { - Reaction reaction = new Reaction(); - reaction.addProduct(new Product()); - reaction.addReactant(new Reactant()); - PositiveInfluenceReaction validReaction = new PositiveInfluenceReaction(reaction); - assertNotNull(validReaction); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Reaction reaction = new Reaction(); + reaction.addProduct(new Product()); + reaction.addReactant(new Reactant()); + PositiveInfluenceReaction validReaction = new PositiveInfluenceReaction(reaction); + assertNotNull(validReaction); } @Test public void testCopy() { - try { - PositiveInfluenceReaction original = new PositiveInfluenceReaction(); - original.addProduct(new Product()); - original.addReactant(new Reactant()); - original.addReactant(new Reactant()); - PositiveInfluenceReaction product = original.copy(); - assertNotNull(product); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + PositiveInfluenceReaction original = new PositiveInfluenceReaction(); + original.addProduct(new Product()); + original.addReactant(new Reactant()); + original.addReactant(new Reactant()); + PositiveInfluenceReaction product = original.copy(); + assertNotNull(product); } - @Test + @Test(expected = NotImplementedException.class) public void testInvalidCopy() { - try { - Mockito.spy(new PositiveInfluenceReaction()).copy(); - fail("Exception expected"); - } catch (NotImplementedException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Mockito.spy(new PositiveInfluenceReaction()).copy(); } @Test public void testGetters() { - try { - PositiveInfluenceReaction original = new PositiveInfluenceReaction(); - assertNull(original.getReactionRect()); - assertNotNull(original.getStringType()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + PositiveInfluenceReaction original = new PositiveInfluenceReaction(); + assertNull(original.getReactionRect()); + assertNotNull(original.getStringType()); } } diff --git a/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/ReducedModulationReactionTest.java b/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/ReducedModulationReactionTest.java index 1437d6a1f2fca0ffc76b8628a30ce3040f9f0671..3af121e9e71e0df34e7bb1a15ba3b6c57e27f6b7 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/ReducedModulationReactionTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/ReducedModulationReactionTest.java @@ -1,22 +1,17 @@ package lcsb.mapviewer.model.map.reaction.type; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.mockito.Mockito; +import lcsb.mapviewer.ModelTestFunctions; import lcsb.mapviewer.common.exception.InvalidArgumentException; import lcsb.mapviewer.common.exception.NotImplementedException; -import lcsb.mapviewer.model.map.reaction.Product; -import lcsb.mapviewer.model.map.reaction.Reactant; -import lcsb.mapviewer.model.map.reaction.Reaction; +import lcsb.mapviewer.model.map.reaction.*; -public class ReducedModulationReactionTest { +public class ReducedModulationReactionTest extends ModelTestFunctions { @Before public void setUp() throws Exception { @@ -28,94 +23,50 @@ public class ReducedModulationReactionTest { @Test public void testSerialization() { - try { - SerializationUtils.serialize(new ReducedModulationReaction()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + SerializationUtils.serialize(new ReducedModulationReaction()); } - @Test + @Test(expected = InvalidArgumentException.class) public void testConstructorWithInvalidArg() { - try { - Reaction reaction = new Reaction(); - new ReducedModulationReaction(reaction); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Reaction reaction = new Reaction(); + new ReducedModulationReaction(reaction); } - @Test + @Test(expected = InvalidArgumentException.class) public void testConstructorWithInvalidArg2() { - try { - Reaction reaction = new Reaction(); - reaction.addProduct(new Product()); - new ReducedModulationReaction(reaction); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Reaction reaction = new Reaction(); + reaction.addProduct(new Product()); + new ReducedModulationReaction(reaction); } @Test public void testConstructor() { - try { - Reaction reaction = new Reaction(); - reaction.addProduct(new Product()); - reaction.addReactant(new Reactant()); - ReducedModulationReaction validReaction = new ReducedModulationReaction(reaction); - assertNotNull(validReaction); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Reaction reaction = new Reaction(); + reaction.addProduct(new Product()); + reaction.addReactant(new Reactant()); + ReducedModulationReaction validReaction = new ReducedModulationReaction(reaction); + assertNotNull(validReaction); } @Test public void testCopy() { - try { - ReducedModulationReaction original = new ReducedModulationReaction(); - original.addProduct(new Product()); - original.addReactant(new Reactant()); - original.addReactant(new Reactant()); - ReducedModulationReaction product = original.copy(); - assertNotNull(product); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + ReducedModulationReaction original = new ReducedModulationReaction(); + original.addProduct(new Product()); + original.addReactant(new Reactant()); + original.addReactant(new Reactant()); + ReducedModulationReaction product = original.copy(); + assertNotNull(product); } - @Test + @Test(expected = NotImplementedException.class) public void testInvalidCopy() { - try { - Mockito.spy(new ReducedModulationReaction()).copy(); - fail("Exception expected"); - } catch (NotImplementedException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Mockito.spy(new ReducedModulationReaction()).copy(); } @Test public void testGetters() { - try { - ReducedModulationReaction original = new ReducedModulationReaction(); - assertNull(original.getReactionRect()); - assertNotNull(original.getStringType()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + ReducedModulationReaction original = new ReducedModulationReaction(); + assertNull(original.getReactionRect()); + assertNotNull(original.getStringType()); } } diff --git a/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/ReducedPhysicalStimulationReactionTest.java b/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/ReducedPhysicalStimulationReactionTest.java index d065e75a383728de5d2aab474e7098f5cef904bf..2e36146965ef05845cddb232db2db57f802442cd 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/ReducedPhysicalStimulationReactionTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/ReducedPhysicalStimulationReactionTest.java @@ -1,22 +1,17 @@ package lcsb.mapviewer.model.map.reaction.type; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.mockito.Mockito; +import lcsb.mapviewer.ModelTestFunctions; import lcsb.mapviewer.common.exception.InvalidArgumentException; import lcsb.mapviewer.common.exception.NotImplementedException; -import lcsb.mapviewer.model.map.reaction.Product; -import lcsb.mapviewer.model.map.reaction.Reactant; -import lcsb.mapviewer.model.map.reaction.Reaction; +import lcsb.mapviewer.model.map.reaction.*; -public class ReducedPhysicalStimulationReactionTest { +public class ReducedPhysicalStimulationReactionTest extends ModelTestFunctions { @Before public void setUp() throws Exception { @@ -28,94 +23,50 @@ public class ReducedPhysicalStimulationReactionTest { @Test public void testSerialization() { - try { - SerializationUtils.serialize(new ReducedPhysicalStimulationReaction()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + SerializationUtils.serialize(new ReducedPhysicalStimulationReaction()); } - @Test + @Test(expected = InvalidArgumentException.class) public void testConstructorWithInvalidArg() { - try { - Reaction reaction = new Reaction(); - new ReducedPhysicalStimulationReaction(reaction); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Reaction reaction = new Reaction(); + new ReducedPhysicalStimulationReaction(reaction); } - @Test + @Test(expected = InvalidArgumentException.class) public void testConstructorWithInvalidArg2() { - try { - Reaction reaction = new Reaction(); - reaction.addProduct(new Product()); - new ReducedPhysicalStimulationReaction(reaction); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Reaction reaction = new Reaction(); + reaction.addProduct(new Product()); + new ReducedPhysicalStimulationReaction(reaction); } @Test public void testConstructor() { - try { - Reaction reaction = new Reaction(); - reaction.addProduct(new Product()); - reaction.addReactant(new Reactant()); - ReducedPhysicalStimulationReaction validReaction = new ReducedPhysicalStimulationReaction(reaction); - assertNotNull(validReaction); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Reaction reaction = new Reaction(); + reaction.addProduct(new Product()); + reaction.addReactant(new Reactant()); + ReducedPhysicalStimulationReaction validReaction = new ReducedPhysicalStimulationReaction(reaction); + assertNotNull(validReaction); } @Test public void testCopy() { - try { - ReducedPhysicalStimulationReaction original = new ReducedPhysicalStimulationReaction(); - original.addProduct(new Product()); - original.addReactant(new Reactant()); - original.addReactant(new Reactant()); - ReducedPhysicalStimulationReaction product = original.copy(); - assertNotNull(product); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + ReducedPhysicalStimulationReaction original = new ReducedPhysicalStimulationReaction(); + original.addProduct(new Product()); + original.addReactant(new Reactant()); + original.addReactant(new Reactant()); + ReducedPhysicalStimulationReaction product = original.copy(); + assertNotNull(product); } - @Test + @Test(expected = NotImplementedException.class) public void testInvalidCopy() { - try { - Mockito.spy(new ReducedPhysicalStimulationReaction()).copy(); - fail("Exception expected"); - } catch (NotImplementedException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Mockito.spy(new ReducedPhysicalStimulationReaction()).copy(); } @Test public void testGetters() { - try { - ReducedPhysicalStimulationReaction original = new ReducedPhysicalStimulationReaction(); - assertNull(original.getReactionRect()); - assertNotNull(original.getStringType()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + ReducedPhysicalStimulationReaction original = new ReducedPhysicalStimulationReaction(); + assertNull(original.getReactionRect()); + assertNotNull(original.getStringType()); } } diff --git a/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/ReducedTriggerReactionTest.java b/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/ReducedTriggerReactionTest.java index 04c8ad80bddf07e90ab5d108b7e33e888ac6cc97..dc6e20698ee3a8e66330f0fb1b11790c1d1cacb5 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/ReducedTriggerReactionTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/ReducedTriggerReactionTest.java @@ -1,22 +1,17 @@ package lcsb.mapviewer.model.map.reaction.type; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.mockito.Mockito; +import lcsb.mapviewer.ModelTestFunctions; import lcsb.mapviewer.common.exception.InvalidArgumentException; import lcsb.mapviewer.common.exception.NotImplementedException; -import lcsb.mapviewer.model.map.reaction.Product; -import lcsb.mapviewer.model.map.reaction.Reactant; -import lcsb.mapviewer.model.map.reaction.Reaction; +import lcsb.mapviewer.model.map.reaction.*; -public class ReducedTriggerReactionTest { +public class ReducedTriggerReactionTest extends ModelTestFunctions { @Before public void setUp() throws Exception { @@ -28,94 +23,50 @@ public class ReducedTriggerReactionTest { @Test public void testSerialization() { - try { - SerializationUtils.serialize(new ReducedTriggerReaction()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + SerializationUtils.serialize(new ReducedTriggerReaction()); } - @Test + @Test(expected = InvalidArgumentException.class) public void testConstructorWithInvalidArg() { - try { - Reaction reaction = new Reaction(); - new ReducedTriggerReaction(reaction); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Reaction reaction = new Reaction(); + new ReducedTriggerReaction(reaction); } - @Test + @Test(expected = InvalidArgumentException.class) public void testConstructorWithInvalidArg2() { - try { - Reaction reaction = new Reaction(); - reaction.addProduct(new Product()); - new ReducedTriggerReaction(reaction); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Reaction reaction = new Reaction(); + reaction.addProduct(new Product()); + new ReducedTriggerReaction(reaction); } @Test public void testConstructor() { - try { - Reaction reaction = new Reaction(); - reaction.addProduct(new Product()); - reaction.addReactant(new Reactant()); - ReducedTriggerReaction validReaction = new ReducedTriggerReaction(reaction); - assertNotNull(validReaction); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Reaction reaction = new Reaction(); + reaction.addProduct(new Product()); + reaction.addReactant(new Reactant()); + ReducedTriggerReaction validReaction = new ReducedTriggerReaction(reaction); + assertNotNull(validReaction); } @Test public void testCopy() { - try { - ReducedTriggerReaction original = new ReducedTriggerReaction(); - original.addProduct(new Product()); - original.addReactant(new Reactant()); - original.addReactant(new Reactant()); - ReducedTriggerReaction product = original.copy(); - assertNotNull(product); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + ReducedTriggerReaction original = new ReducedTriggerReaction(); + original.addProduct(new Product()); + original.addReactant(new Reactant()); + original.addReactant(new Reactant()); + ReducedTriggerReaction product = original.copy(); + assertNotNull(product); } - @Test + @Test(expected = NotImplementedException.class) public void testInvalidCopy() { - try { - Mockito.spy(new ReducedTriggerReaction()).copy(); - fail("Exception expected"); - } catch (NotImplementedException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Mockito.spy(new ReducedTriggerReaction()).copy(); } @Test public void testGetters() { - try { - ReducedTriggerReaction original = new ReducedTriggerReaction(); - assertNull(original.getReactionRect()); - assertNotNull(original.getStringType()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + ReducedTriggerReaction original = new ReducedTriggerReaction(); + assertNull(original.getReactionRect()); + assertNotNull(original.getStringType()); } } diff --git a/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/StateTransitionReactionTest.java b/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/StateTransitionReactionTest.java index 1dbd6cb0c484dfdb00a2fdb795e50182152747ae..63766df9cdf5d7b50ee7c57a41b415418206fabd 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/StateTransitionReactionTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/StateTransitionReactionTest.java @@ -1,21 +1,17 @@ package lcsb.mapviewer.model.map.reaction.type; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.mockito.Mockito; +import lcsb.mapviewer.ModelTestFunctions; import lcsb.mapviewer.common.exception.InvalidArgumentException; import lcsb.mapviewer.common.exception.NotImplementedException; -import lcsb.mapviewer.model.map.reaction.Product; -import lcsb.mapviewer.model.map.reaction.Reactant; -import lcsb.mapviewer.model.map.reaction.Reaction; +import lcsb.mapviewer.model.map.reaction.*; -public class StateTransitionReactionTest { +public class StateTransitionReactionTest extends ModelTestFunctions { @Before public void setUp() throws Exception { @@ -27,94 +23,50 @@ public class StateTransitionReactionTest { @Test public void testSerialization() { - try { - SerializationUtils.serialize(new StateTransitionReaction()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + SerializationUtils.serialize(new StateTransitionReaction()); } - @Test + @Test(expected = InvalidArgumentException.class) public void testConstructorWithInvalidArg() { - try { - Reaction reaction = new Reaction(); - new StateTransitionReaction(reaction); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Reaction reaction = new Reaction(); + new StateTransitionReaction(reaction); } - @Test + @Test(expected = InvalidArgumentException.class) public void testConstructorWithInvalidArg2() { - try { - Reaction reaction = new Reaction(); - reaction.addProduct(new Product()); - new StateTransitionReaction(reaction); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Reaction reaction = new Reaction(); + reaction.addProduct(new Product()); + new StateTransitionReaction(reaction); } @Test public void testConstructor() { - try { - Reaction reaction = new Reaction(); - reaction.addProduct(new Product()); - reaction.addReactant(new Reactant()); - StateTransitionReaction validReaction = new StateTransitionReaction(reaction); - assertNotNull(validReaction); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Reaction reaction = new Reaction(); + reaction.addProduct(new Product()); + reaction.addReactant(new Reactant()); + StateTransitionReaction validReaction = new StateTransitionReaction(reaction); + assertNotNull(validReaction); } @Test public void testCopy() { - try { - StateTransitionReaction original = new StateTransitionReaction(); - original.addProduct(new Product()); - original.addReactant(new Reactant()); - original.addReactant(new Reactant()); - StateTransitionReaction product = original.copy(); - assertNotNull(product); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + StateTransitionReaction original = new StateTransitionReaction(); + original.addProduct(new Product()); + original.addReactant(new Reactant()); + original.addReactant(new Reactant()); + StateTransitionReaction product = original.copy(); + assertNotNull(product); } - @Test + @Test(expected = NotImplementedException.class) public void testInvalidCopy() { - try { - Mockito.spy(new StateTransitionReaction()).copy(); - fail("Exception expected"); - } catch (NotImplementedException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Mockito.spy(new StateTransitionReaction()).copy(); } @Test public void testGetters() { - try { - StateTransitionReaction original = new StateTransitionReaction(); - assertNotNull(original.getReactionRect()); - assertNotNull(original.getStringType()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + StateTransitionReaction original = new StateTransitionReaction(); + assertNotNull(original.getReactionRect()); + assertNotNull(original.getStringType()); } } diff --git a/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/TranscriptionReactionTest.java b/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/TranscriptionReactionTest.java index b670fab8bd456c2351e35ae63fcda1671c05054c..a5a0efa99e5111bf17695189e5b855ce9aa7ad1c 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/TranscriptionReactionTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/TranscriptionReactionTest.java @@ -1,21 +1,17 @@ package lcsb.mapviewer.model.map.reaction.type; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.mockito.Mockito; +import lcsb.mapviewer.ModelTestFunctions; import lcsb.mapviewer.common.exception.InvalidArgumentException; import lcsb.mapviewer.common.exception.NotImplementedException; -import lcsb.mapviewer.model.map.reaction.Product; -import lcsb.mapviewer.model.map.reaction.Reactant; -import lcsb.mapviewer.model.map.reaction.Reaction; +import lcsb.mapviewer.model.map.reaction.*; -public class TranscriptionReactionTest { +public class TranscriptionReactionTest extends ModelTestFunctions { @Before public void setUp() throws Exception { @@ -27,94 +23,50 @@ public class TranscriptionReactionTest { @Test public void testSerialization() { - try { - SerializationUtils.serialize(new TranscriptionReaction()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + SerializationUtils.serialize(new TranscriptionReaction()); } - @Test + @Test(expected = InvalidArgumentException.class) public void testConstructorWithInvalidArg() { - try { - Reaction reaction = new Reaction(); - new TranscriptionReaction(reaction); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Reaction reaction = new Reaction(); + new TranscriptionReaction(reaction); } - @Test + @Test(expected = InvalidArgumentException.class) public void testConstructorWithInvalidArg2() { - try { - Reaction reaction = new Reaction(); - reaction.addProduct(new Product()); - new TranscriptionReaction(reaction); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Reaction reaction = new Reaction(); + reaction.addProduct(new Product()); + new TranscriptionReaction(reaction); } @Test public void testConstructor() { - try { - Reaction reaction = new Reaction(); - reaction.addProduct(new Product()); - reaction.addReactant(new Reactant()); - TranscriptionReaction validReaction = new TranscriptionReaction(reaction); - assertNotNull(validReaction); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Reaction reaction = new Reaction(); + reaction.addProduct(new Product()); + reaction.addReactant(new Reactant()); + TranscriptionReaction validReaction = new TranscriptionReaction(reaction); + assertNotNull(validReaction); } @Test public void testCopy() { - try { - TranscriptionReaction original = new TranscriptionReaction(); - original.addProduct(new Product()); - original.addReactant(new Reactant()); - original.addReactant(new Reactant()); - TranscriptionReaction product = original.copy(); - assertNotNull(product); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + TranscriptionReaction original = new TranscriptionReaction(); + original.addProduct(new Product()); + original.addReactant(new Reactant()); + original.addReactant(new Reactant()); + TranscriptionReaction product = original.copy(); + assertNotNull(product); } - @Test + @Test(expected = NotImplementedException.class) public void testInvalidCopy() { - try { - Mockito.spy(new TranscriptionReaction()).copy(); - fail("Exception expected"); - } catch (NotImplementedException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Mockito.spy(new TranscriptionReaction()).copy(); } @Test public void testGetters() { - try { - TranscriptionReaction original = new TranscriptionReaction(); - assertNotNull(original.getReactionRect()); - assertNotNull(original.getStringType()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + TranscriptionReaction original = new TranscriptionReaction(); + assertNotNull(original.getReactionRect()); + assertNotNull(original.getStringType()); } } diff --git a/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/TranslationReactionTest.java b/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/TranslationReactionTest.java index 1a4100eb721208b4b861388cd869e64333147757..797f530353edbfc703bd48e34096f2340c78fda3 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/TranslationReactionTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/TranslationReactionTest.java @@ -1,21 +1,17 @@ package lcsb.mapviewer.model.map.reaction.type; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.mockito.Mockito; +import lcsb.mapviewer.ModelTestFunctions; import lcsb.mapviewer.common.exception.InvalidArgumentException; import lcsb.mapviewer.common.exception.NotImplementedException; -import lcsb.mapviewer.model.map.reaction.Product; -import lcsb.mapviewer.model.map.reaction.Reactant; -import lcsb.mapviewer.model.map.reaction.Reaction; +import lcsb.mapviewer.model.map.reaction.*; -public class TranslationReactionTest { +public class TranslationReactionTest extends ModelTestFunctions { @Before public void setUp() throws Exception { @@ -27,94 +23,50 @@ public class TranslationReactionTest { @Test public void testSerialization() { - try { - SerializationUtils.serialize(new TranslationReaction()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + SerializationUtils.serialize(new TranslationReaction()); } - @Test + @Test(expected = InvalidArgumentException.class) public void testConstructorWithInvalidArg() { - try { - Reaction reaction = new Reaction(); - new TranslationReaction(reaction); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Reaction reaction = new Reaction(); + new TranslationReaction(reaction); } - @Test + @Test(expected = InvalidArgumentException.class) public void testConstructorWithInvalidArg2() { - try { - Reaction reaction = new Reaction(); - reaction.addProduct(new Product()); - new TranslationReaction(reaction); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Reaction reaction = new Reaction(); + reaction.addProduct(new Product()); + new TranslationReaction(reaction); } @Test public void testConstructor() { - try { - Reaction reaction = new Reaction(); - reaction.addProduct(new Product()); - reaction.addReactant(new Reactant()); - TranslationReaction validReaction = new TranslationReaction(reaction); - assertNotNull(validReaction); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Reaction reaction = new Reaction(); + reaction.addProduct(new Product()); + reaction.addReactant(new Reactant()); + TranslationReaction validReaction = new TranslationReaction(reaction); + assertNotNull(validReaction); } @Test public void testCopy() { - try { - TranslationReaction original = new TranslationReaction(); - original.addProduct(new Product()); - original.addReactant(new Reactant()); - original.addReactant(new Reactant()); - TranslationReaction product = original.copy(); - assertNotNull(product); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + TranslationReaction original = new TranslationReaction(); + original.addProduct(new Product()); + original.addReactant(new Reactant()); + original.addReactant(new Reactant()); + TranslationReaction product = original.copy(); + assertNotNull(product); } - @Test + @Test(expected = NotImplementedException.class) public void testInvalidCopy() { - try { - Mockito.spy(new TranslationReaction()).copy(); - fail("Exception expected"); - } catch (NotImplementedException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Mockito.spy(new TranslationReaction()).copy(); } @Test public void testGetters() { - try { - TranslationReaction original = new TranslationReaction(); - assertNotNull(original.getReactionRect()); - assertNotNull(original.getStringType()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + TranslationReaction original = new TranslationReaction(); + assertNotNull(original.getReactionRect()); + assertNotNull(original.getStringType()); } } diff --git a/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/TransportReactionTest.java b/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/TransportReactionTest.java index 9d601e4b387259862ac1c9d5b17321a957b3a87a..550d9713575fb6d0dae789c9e4dadcb4cc7acaa0 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/TransportReactionTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/TransportReactionTest.java @@ -1,21 +1,17 @@ package lcsb.mapviewer.model.map.reaction.type; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.mockito.Mockito; +import lcsb.mapviewer.ModelTestFunctions; import lcsb.mapviewer.common.exception.InvalidArgumentException; import lcsb.mapviewer.common.exception.NotImplementedException; -import lcsb.mapviewer.model.map.reaction.Product; -import lcsb.mapviewer.model.map.reaction.Reactant; -import lcsb.mapviewer.model.map.reaction.Reaction; +import lcsb.mapviewer.model.map.reaction.*; -public class TransportReactionTest { +public class TransportReactionTest extends ModelTestFunctions { @Before public void setUp() throws Exception { @@ -27,94 +23,50 @@ public class TransportReactionTest { @Test public void testSerialization() { - try { - SerializationUtils.serialize(new TransportReaction()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + SerializationUtils.serialize(new TransportReaction()); } - @Test + @Test(expected = InvalidArgumentException.class) public void testConstructorWithInvalidArg() { - try { - Reaction reaction = new Reaction(); - new TransportReaction(reaction); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Reaction reaction = new Reaction(); + new TransportReaction(reaction); } - @Test + @Test(expected = InvalidArgumentException.class) public void testConstructorWithInvalidArg2() { - try { - Reaction reaction = new Reaction(); - reaction.addProduct(new Product()); - new TransportReaction(reaction); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Reaction reaction = new Reaction(); + reaction.addProduct(new Product()); + new TransportReaction(reaction); } @Test public void testConstructor() { - try { - Reaction reaction = new Reaction(); - reaction.addProduct(new Product()); - reaction.addReactant(new Reactant()); - TransportReaction validReaction = new TransportReaction(reaction); - assertNotNull(validReaction); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Reaction reaction = new Reaction(); + reaction.addProduct(new Product()); + reaction.addReactant(new Reactant()); + TransportReaction validReaction = new TransportReaction(reaction); + assertNotNull(validReaction); } @Test public void testCopy() { - try { - TransportReaction original = new TransportReaction(); - original.addProduct(new Product()); - original.addReactant(new Reactant()); - original.addReactant(new Reactant()); - TransportReaction product = original.copy(); - assertNotNull(product); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + TransportReaction original = new TransportReaction(); + original.addProduct(new Product()); + original.addReactant(new Reactant()); + original.addReactant(new Reactant()); + TransportReaction product = original.copy(); + assertNotNull(product); } - @Test + @Test(expected = NotImplementedException.class) public void testInvalidCopy() { - try { - Mockito.spy(new TransportReaction()).copy(); - fail("Exception expected"); - } catch (NotImplementedException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Mockito.spy(new TransportReaction()).copy(); } @Test public void testGetters() { - try { - TransportReaction original = new TransportReaction(); - assertNotNull(original.getReactionRect()); - assertNotNull(original.getStringType()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + TransportReaction original = new TransportReaction(); + assertNotNull(original.getReactionRect()); + assertNotNull(original.getStringType()); } } diff --git a/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/TruncationReactionTest.java b/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/TruncationReactionTest.java index 7a19cc9d59b54edbcddfd7d796b690cc26f4f257..172e3a1b5e6b29a609c1e4b52a52d3b1e9644148 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/TruncationReactionTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/TruncationReactionTest.java @@ -1,21 +1,17 @@ package lcsb.mapviewer.model.map.reaction.type; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.mockito.Mockito; +import lcsb.mapviewer.ModelTestFunctions; import lcsb.mapviewer.common.exception.InvalidArgumentException; import lcsb.mapviewer.common.exception.NotImplementedException; -import lcsb.mapviewer.model.map.reaction.Product; -import lcsb.mapviewer.model.map.reaction.Reactant; -import lcsb.mapviewer.model.map.reaction.Reaction; +import lcsb.mapviewer.model.map.reaction.*; -public class TruncationReactionTest { +public class TruncationReactionTest extends ModelTestFunctions { @Before public void setUp() throws Exception { @@ -27,97 +23,53 @@ public class TruncationReactionTest { @Test public void testSerialization() { - try { - SerializationUtils.serialize(new TruncationReaction()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + SerializationUtils.serialize(new TruncationReaction()); } - @Test + @Test(expected = InvalidArgumentException.class) public void testConstructorWithInvalidArg() { - try { - Reaction reaction = new Reaction(); - new TruncationReaction(reaction); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Reaction reaction = new Reaction(); + new TruncationReaction(reaction); } - @Test + @Test(expected = InvalidArgumentException.class) public void testConstructorWithInvalidArg2() { - try { - Reaction reaction = new Reaction(); - reaction.addProduct(new Product()); - reaction.addProduct(new Product()); - new TruncationReaction(reaction); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Reaction reaction = new Reaction(); + reaction.addProduct(new Product()); + reaction.addProduct(new Product()); + new TruncationReaction(reaction); } @Test public void testConstructor() { - try { - Reaction reaction = new Reaction(); - reaction.addProduct(new Product()); - reaction.addProduct(new Product()); - reaction.addReactant(new Reactant()); - TruncationReaction validReaction = new TruncationReaction(reaction); - assertNotNull(validReaction); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Reaction reaction = new Reaction(); + reaction.addProduct(new Product()); + reaction.addProduct(new Product()); + reaction.addReactant(new Reactant()); + TruncationReaction validReaction = new TruncationReaction(reaction); + assertNotNull(validReaction); } @Test public void testCopy() { - try { - TruncationReaction original = new TruncationReaction(); - original.addProduct(new Product()); - original.addProduct(new Product()); - original.addReactant(new Reactant()); - TruncationReaction product = original.copy(); - assertNotNull(product); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + TruncationReaction original = new TruncationReaction(); + original.addProduct(new Product()); + original.addProduct(new Product()); + original.addReactant(new Reactant()); + TruncationReaction product = original.copy(); + assertNotNull(product); } - @Test + @Test(expected = NotImplementedException.class) public void testInvalidCopy() { - try { - Mockito.spy(new TruncationReaction()).copy(); - fail("Exception expected"); - } catch (NotImplementedException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Mockito.spy(new TruncationReaction()).copy(); } @Test public void testGetters() { - try { - Reaction reaction = new TruncationReaction(); - assertNotNull(reaction.getStringType()); - assertNotNull(reaction.getReactionRect()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Reaction reaction = new TruncationReaction(); + assertNotNull(reaction.getStringType()); + assertNotNull(reaction.getReactionRect()); } } diff --git a/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/UnknownNegativeInfluenceReactionTest.java b/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/UnknownNegativeInfluenceReactionTest.java index 65b27ab7243746a8b4fd1131472df02de566bfde..41657d5ef443a47e9c7b60490d3fac6083ace87f 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/UnknownNegativeInfluenceReactionTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/UnknownNegativeInfluenceReactionTest.java @@ -1,22 +1,17 @@ package lcsb.mapviewer.model.map.reaction.type; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.mockito.Mockito; +import lcsb.mapviewer.ModelTestFunctions; import lcsb.mapviewer.common.exception.InvalidArgumentException; import lcsb.mapviewer.common.exception.NotImplementedException; -import lcsb.mapviewer.model.map.reaction.Product; -import lcsb.mapviewer.model.map.reaction.Reactant; -import lcsb.mapviewer.model.map.reaction.Reaction; +import lcsb.mapviewer.model.map.reaction.*; -public class UnknownNegativeInfluenceReactionTest { +public class UnknownNegativeInfluenceReactionTest extends ModelTestFunctions { @Before public void setUp() throws Exception { @@ -28,94 +23,50 @@ public class UnknownNegativeInfluenceReactionTest { @Test public void testSerialization() { - try { - SerializationUtils.serialize(new UnknownNegativeInfluenceReaction()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + SerializationUtils.serialize(new UnknownNegativeInfluenceReaction()); } - @Test + @Test(expected = InvalidArgumentException.class) public void testConstructorWithInvalidArg() { - try { - Reaction reaction = new Reaction(); - new UnknownNegativeInfluenceReaction(reaction); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Reaction reaction = new Reaction(); + new UnknownNegativeInfluenceReaction(reaction); } - @Test + @Test(expected = InvalidArgumentException.class) public void testConstructorWithInvalidArg2() { - try { - Reaction reaction = new Reaction(); - reaction.addProduct(new Product()); - new UnknownNegativeInfluenceReaction(reaction); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Reaction reaction = new Reaction(); + reaction.addProduct(new Product()); + new UnknownNegativeInfluenceReaction(reaction); } @Test public void testConstructor() { - try { - Reaction reaction = new Reaction(); - reaction.addProduct(new Product()); - reaction.addReactant(new Reactant()); - UnknownNegativeInfluenceReaction validReaction = new UnknownNegativeInfluenceReaction(reaction); - assertNotNull(validReaction); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Reaction reaction = new Reaction(); + reaction.addProduct(new Product()); + reaction.addReactant(new Reactant()); + UnknownNegativeInfluenceReaction validReaction = new UnknownNegativeInfluenceReaction(reaction); + assertNotNull(validReaction); } @Test public void testCopy() { - try { - UnknownNegativeInfluenceReaction original = new UnknownNegativeInfluenceReaction(); - original.addProduct(new Product()); - original.addReactant(new Reactant()); - original.addReactant(new Reactant()); - UnknownNegativeInfluenceReaction product = original.copy(); - assertNotNull(product); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + UnknownNegativeInfluenceReaction original = new UnknownNegativeInfluenceReaction(); + original.addProduct(new Product()); + original.addReactant(new Reactant()); + original.addReactant(new Reactant()); + UnknownNegativeInfluenceReaction product = original.copy(); + assertNotNull(product); } - @Test + @Test(expected = NotImplementedException.class) public void testInvalidCopy() { - try { - Mockito.spy(new UnknownNegativeInfluenceReaction()).copy(); - fail("Exception expected"); - } catch (NotImplementedException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Mockito.spy(new UnknownNegativeInfluenceReaction()).copy(); } @Test public void testGetters() { - try { - UnknownNegativeInfluenceReaction original = new UnknownNegativeInfluenceReaction(); - assertNull(original.getReactionRect()); - assertNotNull(original.getStringType()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + UnknownNegativeInfluenceReaction original = new UnknownNegativeInfluenceReaction(); + assertNull(original.getReactionRect()); + assertNotNull(original.getStringType()); } } diff --git a/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/UnknownPositiveInfluenceReactionTest.java b/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/UnknownPositiveInfluenceReactionTest.java index 92ecf983a1eb020b999e30faba64685427a4ef75..f6064bf915259b37f0defb90adb8af6caf6c3780 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/UnknownPositiveInfluenceReactionTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/UnknownPositiveInfluenceReactionTest.java @@ -1,22 +1,17 @@ package lcsb.mapviewer.model.map.reaction.type; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.mockito.Mockito; +import lcsb.mapviewer.ModelTestFunctions; import lcsb.mapviewer.common.exception.InvalidArgumentException; import lcsb.mapviewer.common.exception.NotImplementedException; -import lcsb.mapviewer.model.map.reaction.Product; -import lcsb.mapviewer.model.map.reaction.Reactant; -import lcsb.mapviewer.model.map.reaction.Reaction; +import lcsb.mapviewer.model.map.reaction.*; -public class UnknownPositiveInfluenceReactionTest { +public class UnknownPositiveInfluenceReactionTest extends ModelTestFunctions { @Before public void setUp() throws Exception { @@ -28,94 +23,50 @@ public class UnknownPositiveInfluenceReactionTest { @Test public void testSerialization() { - try { - SerializationUtils.serialize(new UnknownPositiveInfluenceReaction()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + SerializationUtils.serialize(new UnknownPositiveInfluenceReaction()); } - @Test + @Test(expected = InvalidArgumentException.class) public void testConstructorWithInvalidArg() { - try { - Reaction reaction = new Reaction(); - new UnknownPositiveInfluenceReaction(reaction); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Reaction reaction = new Reaction(); + new UnknownPositiveInfluenceReaction(reaction); } - @Test + @Test(expected = InvalidArgumentException.class) public void testConstructorWithInvalidArg2() { - try { - Reaction reaction = new Reaction(); - reaction.addProduct(new Product()); - new UnknownPositiveInfluenceReaction(reaction); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Reaction reaction = new Reaction(); + reaction.addProduct(new Product()); + new UnknownPositiveInfluenceReaction(reaction); } @Test public void testConstructor() { - try { - Reaction reaction = new Reaction(); - reaction.addProduct(new Product()); - reaction.addReactant(new Reactant()); - UnknownPositiveInfluenceReaction validReaction = new UnknownPositiveInfluenceReaction(reaction); - assertNotNull(validReaction); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Reaction reaction = new Reaction(); + reaction.addProduct(new Product()); + reaction.addReactant(new Reactant()); + UnknownPositiveInfluenceReaction validReaction = new UnknownPositiveInfluenceReaction(reaction); + assertNotNull(validReaction); } @Test public void testCopy() { - try { - UnknownPositiveInfluenceReaction original = new UnknownPositiveInfluenceReaction(); - original.addProduct(new Product()); - original.addReactant(new Reactant()); - original.addReactant(new Reactant()); - UnknownPositiveInfluenceReaction product = original.copy(); - assertNotNull(product); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + UnknownPositiveInfluenceReaction original = new UnknownPositiveInfluenceReaction(); + original.addProduct(new Product()); + original.addReactant(new Reactant()); + original.addReactant(new Reactant()); + UnknownPositiveInfluenceReaction product = original.copy(); + assertNotNull(product); } - @Test + @Test(expected = NotImplementedException.class) public void testInvalidCopy() { - try { - Mockito.spy(new UnknownPositiveInfluenceReaction()).copy(); - fail("Exception expected"); - } catch (NotImplementedException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Mockito.spy(new UnknownPositiveInfluenceReaction()).copy(); } @Test public void testGetters() { - try { - UnknownPositiveInfluenceReaction original = new UnknownPositiveInfluenceReaction(); - assertNull(original.getReactionRect()); - assertNotNull(original.getStringType()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + UnknownPositiveInfluenceReaction original = new UnknownPositiveInfluenceReaction(); + assertNull(original.getReactionRect()); + assertNotNull(original.getStringType()); } } diff --git a/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/UnknownReducedModulationReactionTest.java b/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/UnknownReducedModulationReactionTest.java index 3a02c97aabb5ad917002283a533d4df591366bba..fdd9447caf8313d82b249b6d0f94269edc1d4ce5 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/UnknownReducedModulationReactionTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/UnknownReducedModulationReactionTest.java @@ -1,22 +1,17 @@ package lcsb.mapviewer.model.map.reaction.type; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.mockito.Mockito; +import lcsb.mapviewer.ModelTestFunctions; import lcsb.mapviewer.common.exception.InvalidArgumentException; import lcsb.mapviewer.common.exception.NotImplementedException; -import lcsb.mapviewer.model.map.reaction.Product; -import lcsb.mapviewer.model.map.reaction.Reactant; -import lcsb.mapviewer.model.map.reaction.Reaction; +import lcsb.mapviewer.model.map.reaction.*; -public class UnknownReducedModulationReactionTest { +public class UnknownReducedModulationReactionTest extends ModelTestFunctions { @Before public void setUp() throws Exception { @@ -28,94 +23,50 @@ public class UnknownReducedModulationReactionTest { @Test public void testSerialization() { - try { - SerializationUtils.serialize(new UnknownReducedModulationReaction()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + SerializationUtils.serialize(new UnknownReducedModulationReaction()); } - @Test + @Test(expected = InvalidArgumentException.class) public void testConstructorWithInvalidArg() { - try { - Reaction reaction = new Reaction(); - new UnknownReducedModulationReaction(reaction); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Reaction reaction = new Reaction(); + new UnknownReducedModulationReaction(reaction); } - @Test + @Test(expected = InvalidArgumentException.class) public void testConstructorWithInvalidArg2() { - try { - Reaction reaction = new Reaction(); - reaction.addProduct(new Product()); - new UnknownReducedModulationReaction(reaction); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Reaction reaction = new Reaction(); + reaction.addProduct(new Product()); + new UnknownReducedModulationReaction(reaction); } @Test public void testConstructor() { - try { - Reaction reaction = new Reaction(); - reaction.addProduct(new Product()); - reaction.addReactant(new Reactant()); - UnknownReducedModulationReaction validReaction = new UnknownReducedModulationReaction(reaction); - assertNotNull(validReaction); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Reaction reaction = new Reaction(); + reaction.addProduct(new Product()); + reaction.addReactant(new Reactant()); + UnknownReducedModulationReaction validReaction = new UnknownReducedModulationReaction(reaction); + assertNotNull(validReaction); } @Test public void testCopy() { - try { - UnknownReducedModulationReaction original = new UnknownReducedModulationReaction(); - original.addProduct(new Product()); - original.addReactant(new Reactant()); - original.addReactant(new Reactant()); - UnknownReducedModulationReaction product = original.copy(); - assertNotNull(product); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + UnknownReducedModulationReaction original = new UnknownReducedModulationReaction(); + original.addProduct(new Product()); + original.addReactant(new Reactant()); + original.addReactant(new Reactant()); + UnknownReducedModulationReaction product = original.copy(); + assertNotNull(product); } - @Test + @Test(expected = NotImplementedException.class) public void testInvalidCopy() { - try { - Mockito.spy(new UnknownReducedModulationReaction()).copy(); - fail("Exception expected"); - } catch (NotImplementedException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Mockito.spy(new UnknownReducedModulationReaction()).copy(); } @Test public void testGetters() { - try { - UnknownReducedModulationReaction original = new UnknownReducedModulationReaction(); - assertNull(original.getReactionRect()); - assertNotNull(original.getStringType()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + UnknownReducedModulationReaction original = new UnknownReducedModulationReaction(); + assertNull(original.getReactionRect()); + assertNotNull(original.getStringType()); } } diff --git a/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/UnknownReducedPhysicalStimulationReactionTest.java b/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/UnknownReducedPhysicalStimulationReactionTest.java index 7ec12810fd446bc8cabd5285a36246b5ac5cd72a..3a2f2787cc2e4d3e20494167ca544161144b2424 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/UnknownReducedPhysicalStimulationReactionTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/UnknownReducedPhysicalStimulationReactionTest.java @@ -1,22 +1,17 @@ package lcsb.mapviewer.model.map.reaction.type; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.mockito.Mockito; +import lcsb.mapviewer.ModelTestFunctions; import lcsb.mapviewer.common.exception.InvalidArgumentException; import lcsb.mapviewer.common.exception.NotImplementedException; -import lcsb.mapviewer.model.map.reaction.Product; -import lcsb.mapviewer.model.map.reaction.Reactant; -import lcsb.mapviewer.model.map.reaction.Reaction; +import lcsb.mapviewer.model.map.reaction.*; -public class UnknownReducedPhysicalStimulationReactionTest { +public class UnknownReducedPhysicalStimulationReactionTest extends ModelTestFunctions { @Before public void setUp() throws Exception { @@ -28,94 +23,50 @@ public class UnknownReducedPhysicalStimulationReactionTest { @Test public void testSerialization() { - try { - SerializationUtils.serialize(new UnknownReducedPhysicalStimulationReaction()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + SerializationUtils.serialize(new UnknownReducedPhysicalStimulationReaction()); } - @Test + @Test(expected = InvalidArgumentException.class) public void testConstructorWithInvalidArg() { - try { - Reaction reaction = new Reaction(); - new UnknownReducedPhysicalStimulationReaction(reaction); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Reaction reaction = new Reaction(); + new UnknownReducedPhysicalStimulationReaction(reaction); } - @Test + @Test(expected = InvalidArgumentException.class) public void testConstructorWithInvalidArg2() { - try { - Reaction reaction = new Reaction(); - reaction.addProduct(new Product()); - new UnknownReducedPhysicalStimulationReaction(reaction); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Reaction reaction = new Reaction(); + reaction.addProduct(new Product()); + new UnknownReducedPhysicalStimulationReaction(reaction); } @Test public void testConstructor() { - try { - Reaction reaction = new Reaction(); - reaction.addProduct(new Product()); - reaction.addReactant(new Reactant()); - UnknownReducedPhysicalStimulationReaction validReaction = new UnknownReducedPhysicalStimulationReaction(reaction); - assertNotNull(validReaction); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Reaction reaction = new Reaction(); + reaction.addProduct(new Product()); + reaction.addReactant(new Reactant()); + UnknownReducedPhysicalStimulationReaction validReaction = new UnknownReducedPhysicalStimulationReaction(reaction); + assertNotNull(validReaction); } @Test public void testCopy() { - try { - UnknownReducedPhysicalStimulationReaction original = new UnknownReducedPhysicalStimulationReaction(); - original.addProduct(new Product()); - original.addReactant(new Reactant()); - original.addReactant(new Reactant()); - UnknownReducedPhysicalStimulationReaction product = original.copy(); - assertNotNull(product); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + UnknownReducedPhysicalStimulationReaction original = new UnknownReducedPhysicalStimulationReaction(); + original.addProduct(new Product()); + original.addReactant(new Reactant()); + original.addReactant(new Reactant()); + UnknownReducedPhysicalStimulationReaction product = original.copy(); + assertNotNull(product); } - @Test + @Test(expected = NotImplementedException.class) public void testInvalidCopy() { - try { - Mockito.spy(new UnknownReducedPhysicalStimulationReaction()).copy(); - fail("Exception expected"); - } catch (NotImplementedException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Mockito.spy(new UnknownReducedPhysicalStimulationReaction()).copy(); } @Test public void testGetters() { - try { - UnknownReducedPhysicalStimulationReaction original = new UnknownReducedPhysicalStimulationReaction(); - assertNull(original.getReactionRect()); - assertNotNull(original.getStringType()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + UnknownReducedPhysicalStimulationReaction original = new UnknownReducedPhysicalStimulationReaction(); + assertNull(original.getReactionRect()); + assertNotNull(original.getStringType()); } } diff --git a/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/UnknownReducedTriggerReactionTest.java b/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/UnknownReducedTriggerReactionTest.java index 4292d82dce4e7de83c3764dffab05e7019eb7a0c..19392e66558355a4facb1bc6d54ad4f764b0d7f9 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/UnknownReducedTriggerReactionTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/UnknownReducedTriggerReactionTest.java @@ -1,22 +1,17 @@ package lcsb.mapviewer.model.map.reaction.type; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.mockito.Mockito; +import lcsb.mapviewer.ModelTestFunctions; import lcsb.mapviewer.common.exception.InvalidArgumentException; import lcsb.mapviewer.common.exception.NotImplementedException; -import lcsb.mapviewer.model.map.reaction.Product; -import lcsb.mapviewer.model.map.reaction.Reactant; -import lcsb.mapviewer.model.map.reaction.Reaction; +import lcsb.mapviewer.model.map.reaction.*; -public class UnknownReducedTriggerReactionTest { +public class UnknownReducedTriggerReactionTest extends ModelTestFunctions { @Before public void setUp() throws Exception { @@ -28,94 +23,50 @@ public class UnknownReducedTriggerReactionTest { @Test public void testSerialization() { - try { - SerializationUtils.serialize(new UnknownReducedTriggerReaction()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + SerializationUtils.serialize(new UnknownReducedTriggerReaction()); } - @Test + @Test(expected = InvalidArgumentException.class) public void testConstructorWithInvalidArg() { - try { - Reaction reaction = new Reaction(); - new UnknownReducedTriggerReaction(reaction); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Reaction reaction = new Reaction(); + new UnknownReducedTriggerReaction(reaction); } - @Test + @Test(expected = InvalidArgumentException.class) public void testConstructorWithInvalidArg2() { - try { - Reaction reaction = new Reaction(); - reaction.addProduct(new Product()); - new UnknownReducedTriggerReaction(reaction); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Reaction reaction = new Reaction(); + reaction.addProduct(new Product()); + new UnknownReducedTriggerReaction(reaction); } @Test public void testConstructor() { - try { - Reaction reaction = new Reaction(); - reaction.addProduct(new Product()); - reaction.addReactant(new Reactant()); - UnknownReducedTriggerReaction validReaction = new UnknownReducedTriggerReaction(reaction); - assertNotNull(validReaction); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Reaction reaction = new Reaction(); + reaction.addProduct(new Product()); + reaction.addReactant(new Reactant()); + UnknownReducedTriggerReaction validReaction = new UnknownReducedTriggerReaction(reaction); + assertNotNull(validReaction); } @Test public void testCopy() { - try { - UnknownReducedTriggerReaction original = new UnknownReducedTriggerReaction(); - original.addProduct(new Product()); - original.addReactant(new Reactant()); - original.addReactant(new Reactant()); - UnknownReducedTriggerReaction product = original.copy(); - assertNotNull(product); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + UnknownReducedTriggerReaction original = new UnknownReducedTriggerReaction(); + original.addProduct(new Product()); + original.addReactant(new Reactant()); + original.addReactant(new Reactant()); + UnknownReducedTriggerReaction product = original.copy(); + assertNotNull(product); } - @Test + @Test(expected = NotImplementedException.class) public void testInvalidCopy() { - try { - Mockito.spy(new UnknownReducedTriggerReaction()).copy(); - fail("Exception expected"); - } catch (NotImplementedException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Mockito.spy(new UnknownReducedTriggerReaction()).copy(); } @Test public void testGetters() { - try { - UnknownReducedTriggerReaction original = new UnknownReducedTriggerReaction(); - assertNull(original.getReactionRect()); - assertNotNull(original.getStringType()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + UnknownReducedTriggerReaction original = new UnknownReducedTriggerReaction(); + assertNull(original.getReactionRect()); + assertNotNull(original.getStringType()); } } diff --git a/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/UnknownTransitionReactionTest.java b/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/UnknownTransitionReactionTest.java index cfe2c20ec8e2ebd2a2c844bf2e77b3dcb58e1023..181de50eb17c60b6ff4d73b74ffc6d49ea874837 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/UnknownTransitionReactionTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/UnknownTransitionReactionTest.java @@ -1,21 +1,17 @@ package lcsb.mapviewer.model.map.reaction.type; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.mockito.Mockito; +import lcsb.mapviewer.ModelTestFunctions; import lcsb.mapviewer.common.exception.InvalidArgumentException; import lcsb.mapviewer.common.exception.NotImplementedException; -import lcsb.mapviewer.model.map.reaction.Product; -import lcsb.mapviewer.model.map.reaction.Reactant; -import lcsb.mapviewer.model.map.reaction.Reaction; +import lcsb.mapviewer.model.map.reaction.*; -public class UnknownTransitionReactionTest { +public class UnknownTransitionReactionTest extends ModelTestFunctions { @Before public void setUp() throws Exception { @@ -27,94 +23,50 @@ public class UnknownTransitionReactionTest { @Test public void testSerialization() { - try { - SerializationUtils.serialize(new UnknownTransitionReaction()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + SerializationUtils.serialize(new UnknownTransitionReaction()); } - @Test + @Test(expected = InvalidArgumentException.class) public void testConstructorWithInvalidArg() { - try { - Reaction reaction = new Reaction(); - new UnknownTransitionReaction(reaction); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Reaction reaction = new Reaction(); + new UnknownTransitionReaction(reaction); } - @Test + @Test(expected = InvalidArgumentException.class) public void testConstructorWithInvalidArg2() { - try { - Reaction reaction = new Reaction(); - reaction.addProduct(new Product()); - new UnknownTransitionReaction(reaction); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Reaction reaction = new Reaction(); + reaction.addProduct(new Product()); + new UnknownTransitionReaction(reaction); } @Test public void testConstructor() { - try { - Reaction reaction = new Reaction(); - reaction.addProduct(new Product()); - reaction.addReactant(new Reactant()); - UnknownTransitionReaction validReaction = new UnknownTransitionReaction(reaction); - assertNotNull(validReaction); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Reaction reaction = new Reaction(); + reaction.addProduct(new Product()); + reaction.addReactant(new Reactant()); + UnknownTransitionReaction validReaction = new UnknownTransitionReaction(reaction); + assertNotNull(validReaction); } @Test public void testCopy() { - try { - UnknownTransitionReaction original = new UnknownTransitionReaction(); - original.addProduct(new Product()); - original.addReactant(new Reactant()); - original.addReactant(new Reactant()); - UnknownTransitionReaction product = original.copy(); - assertNotNull(product); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + UnknownTransitionReaction original = new UnknownTransitionReaction(); + original.addProduct(new Product()); + original.addReactant(new Reactant()); + original.addReactant(new Reactant()); + UnknownTransitionReaction product = original.copy(); + assertNotNull(product); } - @Test + @Test(expected = NotImplementedException.class) public void testInvalidCopy() { - try { - Mockito.spy(new UnknownTransitionReaction()).copy(); - fail("Exception expected"); - } catch (NotImplementedException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Mockito.spy(new UnknownTransitionReaction()).copy(); } @Test public void testGetters() { - try { - UnknownTransitionReaction original = new UnknownTransitionReaction(); - assertNotNull(original.getReactionRect()); - assertNotNull(original.getStringType()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + UnknownTransitionReaction original = new UnknownTransitionReaction(); + assertNotNull(original.getReactionRect()); + assertNotNull(original.getStringType()); } } diff --git a/model/src/test/java/lcsb/mapviewer/model/map/species/AntisenseRnaComparatorTest.java b/model/src/test/java/lcsb/mapviewer/model/map/species/AntisenseRnaComparatorTest.java index 858bc750babe6c6ce639b6f1165734a2c660d1d7..00f16843063ca1ce3889ba429b5cf0a23cd07ecc 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/species/AntisenseRnaComparatorTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/species/AntisenseRnaComparatorTest.java @@ -1,20 +1,17 @@ package lcsb.mapviewer.model.map.species; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import java.awt.geom.Point2D; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.mockito.Mockito; +import lcsb.mapviewer.ModelTestFunctions; import lcsb.mapviewer.common.exception.NotImplementedException; import lcsb.mapviewer.model.map.species.field.CodingRegion; -public class AntisenseRnaComparatorTest { +public class AntisenseRnaComparatorTest extends ModelTestFunctions { AntisenseRnaComparator comparator = new AntisenseRnaComparator(); @@ -28,51 +25,40 @@ public class AntisenseRnaComparatorTest { @Test public void testEquals() { - try { - AntisenseRna aRna1 = createAntisenseRna(); - AntisenseRna aRna2 = createAntisenseRna(); + AntisenseRna aRna1 = createAntisenseRna(); + AntisenseRna aRna2 = createAntisenseRna(); - assertEquals(0, comparator.compare(aRna1, aRna1)); + assertEquals(0, comparator.compare(aRna1, aRna1)); - assertEquals(0, comparator.compare(aRna1, aRna2)); - assertEquals(0, comparator.compare(aRna2, aRna1)); - - } catch (Exception e) { - e.printStackTrace(); - fail("Unknowne exception occurred"); - } + assertEquals(0, comparator.compare(aRna1, aRna2)); + assertEquals(0, comparator.compare(aRna2, aRna1)); } @Test public void testDifferent() { - try { - AntisenseRna aRna1 = createAntisenseRna(); - AntisenseRna aRna2 = createAntisenseRna(); - aRna1.getRegions().get(0).setName("bla"); - assertTrue(comparator.compare(aRna1, aRna2) != 0); - assertTrue(comparator.compare(aRna2, aRna1) != 0); - - aRna1 = createAntisenseRna(); - aRna2 = createAntisenseRna(); - aRna1.getRegions().clear(); - assertTrue(comparator.compare(aRna1, aRna2) != 0); - assertTrue(comparator.compare(aRna2, aRna1) != 0); - - aRna1 = createAntisenseRna(); - aRna2 = createAntisenseRna(); - assertTrue(comparator.compare(null, aRna2) != 0); - assertTrue(comparator.compare(aRna2, null) != 0); - assertTrue(comparator.compare(null, null) == 0); - - AntisenseRna unknown = createAntisenseRna(); - unknown.setName("n"); - assertTrue(comparator.compare(unknown, aRna2) != 0); - - assertTrue(comparator.compare(unknown, Mockito.mock(AntisenseRna.class)) != 0); - } catch (Exception e) { - e.printStackTrace(); - fail("Unknowne exception occurred"); - } + AntisenseRna aRna1 = createAntisenseRna(); + AntisenseRna aRna2 = createAntisenseRna(); + aRna1.getRegions().get(0).setName("bla"); + assertTrue(comparator.compare(aRna1, aRna2) != 0); + assertTrue(comparator.compare(aRna2, aRna1) != 0); + + aRna1 = createAntisenseRna(); + aRna2 = createAntisenseRna(); + aRna1.getRegions().clear(); + assertTrue(comparator.compare(aRna1, aRna2) != 0); + assertTrue(comparator.compare(aRna2, aRna1) != 0); + + aRna1 = createAntisenseRna(); + aRna2 = createAntisenseRna(); + assertTrue(comparator.compare(null, aRna2) != 0); + assertTrue(comparator.compare(aRna2, null) != 0); + assertTrue(comparator.compare(null, null) == 0); + + AntisenseRna unknown = createAntisenseRna(); + unknown.setName("n"); + assertTrue(comparator.compare(unknown, aRna2) != 0); + + assertTrue(comparator.compare(unknown, Mockito.mock(AntisenseRna.class)) != 0); } public AntisenseRna createAntisenseRna() { diff --git a/model/src/test/java/lcsb/mapviewer/model/map/species/AntisenseRnaTest.java b/model/src/test/java/lcsb/mapviewer/model/map/species/AntisenseRnaTest.java index 102da4683c57e6641882cad666d0dc2b0ce0528c..d43b90d1bd3e927ea7f4259e86683de4b2167c7f 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/species/AntisenseRnaTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/species/AntisenseRnaTest.java @@ -1,23 +1,20 @@ package lcsb.mapviewer.model.map.species; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import java.util.ArrayList; import java.util.List; import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.mockito.Mockito; +import lcsb.mapviewer.ModelTestFunctions; import lcsb.mapviewer.common.exception.NotImplementedException; import lcsb.mapviewer.model.map.species.field.CodingRegion; import lcsb.mapviewer.model.map.species.field.ModificationResidue; -public class AntisenseRnaTest { +public class AntisenseRnaTest extends ModelTestFunctions { @Before public void setUp() throws Exception { @@ -29,66 +26,39 @@ public class AntisenseRnaTest { @Test public void testSerialization() { - try { - SerializationUtils.serialize(new AntisenseRna()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + SerializationUtils.serialize(new AntisenseRna()); } @Test public void testConstructor1() { - try { - AntisenseRna original = new AntisenseRna(); - original.addCodingRegion(new CodingRegion()); - AntisenseRna aRna = new AntisenseRna(original); - assertNotNull(aRna); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + AntisenseRna original = new AntisenseRna(); + original.addCodingRegion(new CodingRegion()); + AntisenseRna aRna = new AntisenseRna(original); + assertNotNull(aRna); } @Test public void testGetters() { - try { - AntisenseRna aRna = new AntisenseRna("id"); - assertNotNull(aRna.getStringType()); + AntisenseRna aRna = new AntisenseRna("id"); + assertNotNull(aRna.getStringType()); - List<ModificationResidue> regions = new ArrayList<>(); + List<ModificationResidue> regions = new ArrayList<>(); - aRna.setRegions(regions); + aRna.setRegions(regions); - assertEquals(regions, aRna.getRegions()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(regions, aRna.getRegions()); } @Test public void testCopy() { - try { - AntisenseRna aRna = new AntisenseRna().copy(); - assertNotNull(aRna); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + AntisenseRna aRna = new AntisenseRna().copy(); + assertNotNull(aRna); } - @Test + @Test(expected = NotImplementedException.class) public void testInvalidCopy() { - try { - AntisenseRna element = Mockito.spy(AntisenseRna.class); - element.copy(); - fail("Exception expected"); - } catch (NotImplementedException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + AntisenseRna element = Mockito.spy(AntisenseRna.class); + element.copy(); } } diff --git a/model/src/test/java/lcsb/mapviewer/model/map/species/ChemicalComparatorTest.java b/model/src/test/java/lcsb/mapviewer/model/map/species/ChemicalComparatorTest.java index 9599938630d6d645cb24df3b518d975a6fd9c33f..9d509a9d6fdfb19c6931623712bfb2095a0179b5 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/species/ChemicalComparatorTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/species/ChemicalComparatorTest.java @@ -1,17 +1,14 @@ package lcsb.mapviewer.model.map.species; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.mockito.Mockito; +import lcsb.mapviewer.ModelTestFunctions; import lcsb.mapviewer.common.exception.NotImplementedException; -public class ChemicalComparatorTest { +public class ChemicalComparatorTest extends ModelTestFunctions { ChemicalComparator comparator = new ChemicalComparator(); @@ -25,39 +22,27 @@ public class ChemicalComparatorTest { @Test public void testEquals() { - try { - Chemical drug1 = createChemical(); - Chemical drug2 = createChemical(); + Chemical drug1 = createChemical(); + Chemical drug2 = createChemical(); - assertEquals(0, comparator.compare(drug1, drug1)); + assertEquals(0, comparator.compare(drug1, drug1)); - assertEquals(0, comparator.compare(drug1, drug2)); - assertEquals(0, comparator.compare(drug2, drug1)); - - } catch (Exception e) { - e.printStackTrace(); - fail("Unknowne exception occurred"); - } + assertEquals(0, comparator.compare(drug1, drug2)); + assertEquals(0, comparator.compare(drug2, drug1)); } @Test public void testDifferent() { - try { - Chemical drug2 = createChemical(); - assertTrue(comparator.compare(null, drug2) != 0); - assertTrue(comparator.compare(drug2, null) != 0); - assertTrue(comparator.compare(null, null) == 0); - - Chemical drug = createChemical(); - drug.setName("n"); - assertTrue(comparator.compare(drug, drug2) != 0); - - assertTrue(comparator.compare(drug, Mockito.mock(Chemical.class)) != 0); - - } catch (Exception e) { - e.printStackTrace(); - fail("Unknowne exception occurred"); - } + Chemical drug2 = createChemical(); + assertTrue(comparator.compare(null, drug2) != 0); + assertTrue(comparator.compare(drug2, null) != 0); + assertTrue(comparator.compare(null, null) == 0); + + Chemical drug = createChemical(); + drug.setName("n"); + assertTrue(comparator.compare(drug, drug2) != 0); + + assertTrue(comparator.compare(drug, Mockito.mock(Chemical.class)) != 0); } public Chemical createChemical() { diff --git a/model/src/test/java/lcsb/mapviewer/model/map/species/ComplexComparatorTest.java b/model/src/test/java/lcsb/mapviewer/model/map/species/ComplexComparatorTest.java index d673e3d8b7a1a8ba4eb44cdee96f81794bff50ca..b0d7480a512b69c52420cb25be8b5b752d8c4d30 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/species/ComplexComparatorTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/species/ComplexComparatorTest.java @@ -1,22 +1,20 @@ package lcsb.mapviewer.model.map.species; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; -import static org.mockito.Mockito.when; +import static org.junit.Assert.*; +import static org.mockito.Mockito.*; import java.awt.Color; -import org.apache.logging.log4j.*; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.junit.*; import org.mockito.Mockito; +import lcsb.mapviewer.ModelTestFunctions; import lcsb.mapviewer.common.exception.InvalidArgumentException; import lcsb.mapviewer.common.exception.NotImplementedException; -public class ComplexComparatorTest { +public class ComplexComparatorTest extends ModelTestFunctions { Logger logger = LogManager.getLogger(ComplexComparatorTest.class); ComplexComparator comparator = new ComplexComparator(); @@ -31,18 +29,12 @@ public class ComplexComparatorTest { @Test public void testEquals() { - try { - Complex complex1 = createComplex2(); - Complex complex2 = createComplex2(); + Complex complex1 = createComplex2(); + Complex complex2 = createComplex2(); - assertEquals(0, comparator.compare(complex1, complex2)); + assertEquals(0, comparator.compare(complex1, complex2)); - assertEquals(0, comparator.compare(null, null)); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, comparator.compare(null, null)); } private Complex createComplex2() { @@ -67,82 +59,68 @@ public class ComplexComparatorTest { @Test public void testDifferent() { - try { - Complex complex1 = createComplex2(); - Complex complex2 = createComplex2(); - - assertTrue(comparator.compare(complex1, null) != 0); - assertTrue(comparator.compare(null, complex1) != 0); + Complex complex1 = createComplex2(); + Complex complex2 = createComplex2(); - complex1 = createComplex2(); - complex2 = createComplex2(); + assertTrue(comparator.compare(complex1, null) != 0); + assertTrue(comparator.compare(null, complex1) != 0); - complex1.setElementId("tmp"); + complex1 = createComplex2(); + complex2 = createComplex2(); - assertTrue(comparator.compare(complex1, complex2) != 0); - assertTrue(comparator.compare(complex2, complex1) != 0); + complex1.setElementId("tmp"); - complex1 = createComplex2(); - complex2 = createComplex2(); + assertTrue(comparator.compare(complex1, complex2) != 0); + assertTrue(comparator.compare(complex2, complex1) != 0); - complex1.addSpecies(new GenericProtein("id")); + complex1 = createComplex2(); + complex2 = createComplex2(); - assertTrue(comparator.compare(complex1, complex2) != 0); - assertTrue(comparator.compare(complex2, complex1) != 0); + complex1.addSpecies(new GenericProtein("id")); - complex1 = createComplex2(); - complex2 = createComplex2(); + assertTrue(comparator.compare(complex1, complex2) != 0); + assertTrue(comparator.compare(complex2, complex1) != 0); - complex1.getElements().iterator().next().setElementId("bnu"); + complex1 = createComplex2(); + complex2 = createComplex2(); - assertTrue(comparator.compare(complex1, complex2) != 0); - assertTrue(comparator.compare(complex2, complex1) != 0); + complex1.getElements().iterator().next().setElementId("bnu"); - complex1 = createComplex2(); - complex2 = createComplex2(); + assertTrue(comparator.compare(complex1, complex2) != 0); + assertTrue(comparator.compare(complex2, complex1) != 0); - Species species = (Species) complex1.getElements().iterator().next(); - species.setName("new namne"); + complex1 = createComplex2(); + complex2 = createComplex2(); - assertTrue(comparator.compare(complex1, complex2) != 0); - assertTrue(comparator.compare(complex2, complex1) != 0); + Species species = (Species) complex1.getElements().iterator().next(); + species.setName("new namne"); - complex1 = createComplex2(); - complex2 = createComplex2(); + assertTrue(comparator.compare(complex1, complex2) != 0); + assertTrue(comparator.compare(complex2, complex1) != 0); - complex1.setName("new namne"); + complex1 = createComplex2(); + complex2 = createComplex2(); - assertTrue(comparator.compare(complex1, complex2) != 0); - assertTrue(comparator.compare(complex2, complex1) != 0); + complex1.setName("new namne"); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertTrue(comparator.compare(complex1, complex2) != 0); + assertTrue(comparator.compare(complex2, complex1) != 0); } - @Test + @Test(expected = InvalidArgumentException.class) public void testInvalid() { - try { - Complex complex1 = createComplex2(); - Complex complex2 = createComplex2(); - - GenericProtein protein = new GenericProtein("1"); - complex1.getElements().add(protein); - protein = new GenericProtein("1"); - complex1.getElements().add(protein); - - complex2.getElements().add(new GenericProtein("b")); - complex2.getElements().add(new GenericProtein("a")); - - comparator.compare(complex1, complex2); - fail("Exception expected"); - - } catch (InvalidArgumentException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Complex complex1 = createComplex2(); + Complex complex2 = createComplex2(); + + GenericProtein protein = new GenericProtein("1"); + complex1.getElements().add(protein); + protein = new GenericProtein("1"); + complex1.getElements().add(protein); + + complex2.getElements().add(new GenericProtein("b")); + complex2.getElements().add(new GenericProtein("a")); + + comparator.compare(complex1, complex2); } @Test(expected = NotImplementedException.class) @@ -153,210 +131,157 @@ public class ComplexComparatorTest { } - @Test + @Test(expected = InvalidArgumentException.class) public void testInvalid2() { - try { - Complex complex1 = createComplex2(); - Complex complex2 = createComplex2(); - - Species protein = new GenericProtein("1"); - complex1.getElements().add(protein); - protein = new GenericProtein("1"); - complex1.getElements().add(protein); - - complex2.getElements().add(new GenericProtein("A")); - complex2.getElements().add(new GenericProtein("B")); - - comparator.compare(complex2, complex1); - fail("Exception expected"); - - } catch (InvalidArgumentException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Complex complex1 = createComplex2(); + Complex complex2 = createComplex2(); + + Species protein = new GenericProtein("1"); + complex1.getElements().add(protein); + protein = new GenericProtein("1"); + complex1.getElements().add(protein); + + complex2.getElements().add(new GenericProtein("A")); + complex2.getElements().add(new GenericProtein("B")); + + comparator.compare(complex2, complex1); } @Test public void testEquals2() { - try { - Complex complex1 = createComplex(); - Complex complex2 = createComplex(); - - assertEquals(0, comparator.compare(complex1, complex1)); - - assertEquals(0, comparator.compare(complex1, complex2)); - assertEquals(0, comparator.compare(complex2, complex1)); - - complex2.addSpecies(new GenericProtein("test")); - complex1.addSpecies(new GenericProtein("test")); - assertEquals(0, comparator.compare(complex1, complex2)); - assertEquals(0, comparator.compare(complex2, complex1)); - } catch (Exception e) { - e.printStackTrace(); - fail("Unknowne exception occurred"); - } + Complex complex1 = createComplex(); + Complex complex2 = createComplex(); + + assertEquals(0, comparator.compare(complex1, complex1)); + + assertEquals(0, comparator.compare(complex1, complex2)); + assertEquals(0, comparator.compare(complex2, complex1)); + + complex2.addSpecies(new GenericProtein("test")); + complex1.addSpecies(new GenericProtein("test")); + assertEquals(0, comparator.compare(complex1, complex2)); + assertEquals(0, comparator.compare(complex2, complex1)); } - @Test + @Test(expected = NotImplementedException.class) public void testInvalidComp2() throws Exception { - try { - Complex complex1 = createComplex(); - Complex complex2 = createComplex(); - - Species mock = Mockito.mock(Species.class); - when(mock.getElementId()).thenReturn("id"); - complex1.addSpecies(mock); - complex2.addSpecies(mock); - comparator.compare(complex1, complex2); - comparator.compare(complex2, complex1); - fail("Exception expected"); - } catch (NotImplementedException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - + Complex complex1 = createComplex(); + Complex complex2 = createComplex(); + + Species mock = Mockito.mock(Species.class); + when(mock.getElementId()).thenReturn("id"); + complex1.addSpecies(mock); + complex2.addSpecies(mock); + comparator.compare(complex1, complex2); + comparator.compare(complex2, complex1); } - @Test + @Test(expected = NotImplementedException.class) public void testInvalidComp3() throws Exception { - try { - Complex complex1 = createComplex(); - Complex complex2 = createComplex(); - GenericProtein c = new GenericProtein("test"); - complex2.addSpecies(c); - complex1.addSpecies(new GenericProtein("test")); - Species mock = Mockito.mock(Species.class); - when(mock.getElementId()).thenReturn("id"); - complex1.addSpecies(mock); - complex2.addSpecies(mock); - comparator.compare(complex2, complex1); - fail("Exception expected"); - } catch (NotImplementedException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - + Complex complex1 = createComplex(); + Complex complex2 = createComplex(); + GenericProtein c = new GenericProtein("test"); + complex2.addSpecies(c); + complex1.addSpecies(new GenericProtein("test")); + Species mock = Mockito.mock(Species.class); + when(mock.getElementId()).thenReturn("id"); + complex1.addSpecies(mock); + complex2.addSpecies(mock); + comparator.compare(complex2, complex1); } @Test public void testDifferent5() throws Exception { - try { - Complex complex1 = createComplex(); - Complex complex2 = createComplex(); - complex1.setHomodimer(123); - assertTrue(comparator.compare(complex1, complex2) != 0); - assertTrue(comparator.compare(complex2, complex1) != 0); - - complex1 = createComplex(); - complex2 = createComplex(); - complex1.getElements().iterator().next().setNotes("bla"); - assertTrue(comparator.compare(complex1, complex2) != 0); - assertTrue(comparator.compare(complex2, complex1) != 0); - - complex1 = createComplex(); - complex2 = createComplex(); - complex1.getElements().clear(); - assertTrue(comparator.compare(complex1, complex2) != 0); - assertTrue(comparator.compare(complex2, complex1) != 0); - - complex1 = createComplex(); - complex2 = createComplex(); - assertTrue(comparator.compare(null, complex2) != 0); - assertTrue(comparator.compare(complex2, null) != 0); - assertTrue(comparator.compare(null, null) == 0); - - complex1 = createComplex(); - complex2 = createComplex(); - Complex child = (Complex) complex1.getElements().iterator().next(); - child.getElements().iterator().next().setNotes("grand child notes"); - assertTrue(comparator.compare(complex1, complex2) != 0); - assertTrue(comparator.compare(complex2, complex1) != 0); - - complex1 = createComplex(); - complex2 = createComplex(); - Protein prot = new GenericProtein(); - prot.setElementId("test"); - complex1.addSpecies(prot); - assertTrue(comparator.compare(complex1, complex2) != 0); - assertTrue(comparator.compare(complex2, complex1) != 0); - - complex1 = createComplex(); - complex2 = createComplex(); - complex1.setStructuralState("str"); - assertTrue(comparator.compare(complex1, complex2) != 0); - assertTrue(comparator.compare(complex2, complex1) != 0); - - assertTrue(comparator.compare(new Complex(), Mockito.mock(Complex.class)) != 0); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Complex complex1 = createComplex(); + Complex complex2 = createComplex(); + complex1.setHomodimer(123); + assertTrue(comparator.compare(complex1, complex2) != 0); + assertTrue(comparator.compare(complex2, complex1) != 0); + + complex1 = createComplex(); + complex2 = createComplex(); + complex1.getElements().iterator().next().setNotes("bla"); + assertTrue(comparator.compare(complex1, complex2) != 0); + assertTrue(comparator.compare(complex2, complex1) != 0); + + complex1 = createComplex(); + complex2 = createComplex(); + complex1.getElements().clear(); + assertTrue(comparator.compare(complex1, complex2) != 0); + assertTrue(comparator.compare(complex2, complex1) != 0); + + complex1 = createComplex(); + complex2 = createComplex(); + assertTrue(comparator.compare(null, complex2) != 0); + assertTrue(comparator.compare(complex2, null) != 0); + assertTrue(comparator.compare(null, null) == 0); + + complex1 = createComplex(); + complex2 = createComplex(); + Complex child = (Complex) complex1.getElements().iterator().next(); + child.getElements().iterator().next().setNotes("grand child notes"); + assertTrue(comparator.compare(complex1, complex2) != 0); + assertTrue(comparator.compare(complex2, complex1) != 0); + + complex1 = createComplex(); + complex2 = createComplex(); + Protein prot = new GenericProtein(); + prot.setElementId("test"); + complex1.addSpecies(prot); + assertTrue(comparator.compare(complex1, complex2) != 0); + assertTrue(comparator.compare(complex2, complex1) != 0); + + complex1 = createComplex(); + complex2 = createComplex(); + complex1.setStructuralState("str"); + assertTrue(comparator.compare(complex1, complex2) != 0); + assertTrue(comparator.compare(complex2, complex1) != 0); + + assertTrue(comparator.compare(new Complex(), Mockito.mock(Complex.class)) != 0); } @Test public void testDifferent3() throws Exception { - try { - Complex complex1 = createComplex(); - Complex complex2 = createComplex(); - GenericProtein prot = new GenericProtein(); - prot.setElementId("test"); - complex1.addSpecies(prot); - prot = new GenericProtein(); - prot.setElementId("test2"); - complex2.addSpecies(prot); - assertTrue(comparator.compare(complex1, complex2) != 0); - assertTrue(comparator.compare(complex2, complex1) != 0); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Complex complex1 = createComplex(); + Complex complex2 = createComplex(); + GenericProtein prot = new GenericProtein(); + prot.setElementId("test"); + complex1.addSpecies(prot); + prot = new GenericProtein(); + prot.setElementId("test2"); + complex2.addSpecies(prot); + assertTrue(comparator.compare(complex1, complex2) != 0); + assertTrue(comparator.compare(complex2, complex1) != 0); } @Test public void testDifferent4() throws Exception { - try { - Complex complex1 = createComplex(); - Complex complex2 = createComplex(); - GenericProtein c = new GenericProtein("test"); - c.setName("a"); - complex2.addSpecies(c); - complex2.addSpecies(new GenericProtein("test")); - c.setName(""); - - complex1.addSpecies(new GenericProtein("test")); - GenericProtein d = new GenericProtein("test2"); - d.setName("a"); - complex1.addSpecies(d); - assertTrue(comparator.compare(complex1, complex2) != 0); - assertTrue(comparator.compare(complex2, complex1) != 0); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Complex complex1 = createComplex(); + Complex complex2 = createComplex(); + GenericProtein c = new GenericProtein("test"); + c.setName("a"); + complex2.addSpecies(c); + complex2.addSpecies(new GenericProtein("test")); + c.setName(""); + + complex1.addSpecies(new GenericProtein("test")); + GenericProtein d = new GenericProtein("test2"); + d.setName("a"); + complex1.addSpecies(d); + assertTrue(comparator.compare(complex1, complex2) != 0); + assertTrue(comparator.compare(complex2, complex1) != 0); } @Test public void testDifferent2() throws Exception { - try { - Complex complex1 = createComplex(); - Complex complex2 = createComplex(); - GenericProtein comp = new GenericProtein("test"); - comp.setFullName("X"); - complex1.addSpecies(comp); - complex2.addSpecies(new GenericProtein("test")); - assertTrue(comparator.compare(complex1, complex2) != 0); - assertTrue(comparator.compare(complex2, complex1) != 0); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Complex complex1 = createComplex(); + Complex complex2 = createComplex(); + GenericProtein comp = new GenericProtein("test"); + comp.setFullName("X"); + complex1.addSpecies(comp); + complex2.addSpecies(new GenericProtein("test")); + assertTrue(comparator.compare(complex1, complex2) != 0); + assertTrue(comparator.compare(complex2, complex1) != 0); } public Complex createComplex() { diff --git a/model/src/test/java/lcsb/mapviewer/model/map/species/ComplexTest.java b/model/src/test/java/lcsb/mapviewer/model/map/species/ComplexTest.java index 1af1ed5d4c73c53518769837f5dcd49951fe8a4f..cb686002abb05fba56172eefa6f552df998bdc96 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/species/ComplexTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/species/ComplexTest.java @@ -1,13 +1,9 @@ package lcsb.mapviewer.model.map.species; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.mockito.Mockito; import lcsb.mapviewer.ModelTestFunctions; @@ -15,167 +11,111 @@ import lcsb.mapviewer.common.exception.NotImplementedException; public class ComplexTest extends ModelTestFunctions { - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testSerialization() { - try { - SerializationUtils.serialize(new Complex()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testConstructor() { - try { - Complex complex = new Complex(); - complex.addSpecies(new GenericProtein()); - Complex copy = new Complex(complex); - assertNotNull(copy); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testAddElement() { - try { - Complex complex = new Complex(); - Species species = new GenericProtein("id1"); - complex.addSpecies(species); - assertEquals(1, complex.getAllChildren().size()); - complex.addSpecies(species); - assertEquals(1, complex.getAllChildren().size()); - Species protein2 = new GenericProtein("s"); - complex.addSpecies(protein2); - assertEquals(2, complex.getAllChildren().size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testGetAllChildren() { - try { - Complex complex = new Complex(); - - complex.addSpecies(new GenericProtein("1")); - Complex complex2 = new Complex("c3"); - complex2.addSpecies(new GenericProtein("2")); - complex2.addSpecies(new GenericProtein("4")); - - complex.addSpecies(complex2); - - assertEquals(4, complex.getAllChildren().size()); - assertEquals(2, complex.getElements().size()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testRemoveElement() { - try { - Complex complex = new Complex(); - - Species protein = new GenericProtein("1"); - complex.addSpecies(protein); - complex.addSpecies(new GenericProtein("2")); - complex.addSpecies(new GenericProtein("4")); - - assertEquals(3, complex.getElements().size()); - complex.removeElement(protein); - assertEquals(2, complex.getElements().size()); - complex.removeElement(protein); - assertEquals(2, complex.getElements().size()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testRemoveNonExistingElement() { - try { - Complex complex = new Complex(); - Complex complex2 = new Complex(); - - Species protein = new GenericProtein("1"); - protein.setComplex(complex2); - complex.removeElement(protein); - - assertEquals(1, super.getWarnings().size()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testCopy() { - try { - Complex original = new Complex(); - Complex copy = original.copy(); - assertNotNull(copy); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testGetters() { - try { - Complex original = new Complex(); - assertNotNull(original.getStringType()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testGetAllSimpleChildren() { - try { - Complex child = new Complex(); - child.addSpecies(new GenericProtein("id2")); - Complex original = new Complex(); - original.addSpecies(child); - original.addSpecies(new Complex()); - original.addSpecies(new GenericProtein("id")); - assertEquals(2, original.getAllSimpleChildren().size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testInvalidCopy() { - try { - Complex object = Mockito.spy(Complex.class); - object.copy(); - fail("Exception expected"); - } catch (NotImplementedException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testSerialization() { + SerializationUtils.serialize(new Complex()); + } + + @Test + public void testConstructor() { + Complex complex = new Complex(); + complex.addSpecies(new GenericProtein()); + Complex copy = new Complex(complex); + assertNotNull(copy); + } + + @Test + public void testAddElement() { + Complex complex = new Complex(); + Species species = new GenericProtein("id1"); + complex.addSpecies(species); + assertEquals(1, complex.getAllChildren().size()); + complex.addSpecies(species); + assertEquals(1, complex.getAllChildren().size()); + Species protein2 = new GenericProtein("s"); + complex.addSpecies(protein2); + assertEquals(2, complex.getAllChildren().size()); + } + + @Test + public void testGetAllChildren() { + Complex complex = new Complex(); + + complex.addSpecies(new GenericProtein("1")); + Complex complex2 = new Complex("c3"); + complex2.addSpecies(new GenericProtein("2")); + complex2.addSpecies(new GenericProtein("4")); + + complex.addSpecies(complex2); + + assertEquals(4, complex.getAllChildren().size()); + assertEquals(2, complex.getElements().size()); + } + + @Test + public void testRemoveElement() { + Complex complex = new Complex(); + + Species protein = new GenericProtein("1"); + complex.addSpecies(protein); + complex.addSpecies(new GenericProtein("2")); + complex.addSpecies(new GenericProtein("4")); + + assertEquals(3, complex.getElements().size()); + complex.removeElement(protein); + assertEquals(2, complex.getElements().size()); + complex.removeElement(protein); + assertEquals(2, complex.getElements().size()); + } + + @Test + public void testRemoveNonExistingElement() { + Complex complex = new Complex(); + Complex complex2 = new Complex(); + + Species protein = new GenericProtein("1"); + protein.setComplex(complex2); + complex.removeElement(protein); + + assertEquals(1, super.getWarnings().size()); + } + + @Test + public void testCopy() { + Complex original = new Complex(); + Complex copy = original.copy(); + assertNotNull(copy); + } + + @Test + public void testGetters() { + Complex original = new Complex(); + assertNotNull(original.getStringType()); + } + + @Test + public void testGetAllSimpleChildren() { + Complex child = new Complex(); + child.addSpecies(new GenericProtein("id2")); + Complex original = new Complex(); + original.addSpecies(child); + original.addSpecies(new Complex()); + original.addSpecies(new GenericProtein("id")); + assertEquals(2, original.getAllSimpleChildren().size()); + } + + @Test(expected = NotImplementedException.class) + public void testInvalidCopy() { + Complex object = Mockito.spy(Complex.class); + object.copy(); + } } diff --git a/model/src/test/java/lcsb/mapviewer/model/map/species/DegradedComparatorTest.java b/model/src/test/java/lcsb/mapviewer/model/map/species/DegradedComparatorTest.java index 9a9ed82eeba7eaf2aa568a47d5d95fecde816036..24aff10c4ba080e06763ad098c7f62092f5a5a72 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/species/DegradedComparatorTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/species/DegradedComparatorTest.java @@ -1,17 +1,14 @@ package lcsb.mapviewer.model.map.species; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.mockito.Mockito; +import lcsb.mapviewer.ModelTestFunctions; import lcsb.mapviewer.common.exception.NotImplementedException; -public class DegradedComparatorTest { +public class DegradedComparatorTest extends ModelTestFunctions { DegradedComparator comparator = new DegradedComparator(); @@ -25,47 +22,36 @@ public class DegradedComparatorTest { @Test public void testEquals() { - try { - Degraded degraded1 = createDegraded(); - Degraded degraded2 = createDegraded(); + Degraded degraded1 = createDegraded(); + Degraded degraded2 = createDegraded(); - assertEquals(0, comparator.compare(degraded1, degraded1)); + assertEquals(0, comparator.compare(degraded1, degraded1)); - assertEquals(0, comparator.compare(degraded1, degraded2)); - assertEquals(0, comparator.compare(degraded2, degraded1)); - - } catch (Exception e) { - e.printStackTrace(); - fail("Unknowne exception occurred"); - } + assertEquals(0, comparator.compare(degraded1, degraded2)); + assertEquals(0, comparator.compare(degraded2, degraded1)); } @Test public void testDifferent() { - try { - Degraded degraded1 = createDegraded(); - Degraded degraded2 = createDegraded(); - degraded1 = createDegraded(); - degraded2 = createDegraded(); - degraded1.setCharge(54); - assertTrue(comparator.compare(degraded1, degraded2) != 0); - assertTrue(comparator.compare(degraded2, degraded1) != 0); - - degraded1 = createDegraded(); - degraded2 = createDegraded(); - assertTrue(comparator.compare(null, degraded2) != 0); - assertTrue(comparator.compare(degraded2, null) != 0); - assertTrue(comparator.compare(null, null) == 0); - - Degraded degraded = createDegraded(); - degraded.setName("n"); - assertTrue(comparator.compare(degraded, degraded1) != 0); - - assertTrue(comparator.compare(degraded, Mockito.mock(Degraded.class)) != 0); - } catch (Exception e) { - e.printStackTrace(); - fail("Unknowne exception occurred"); - } + Degraded degraded1 = createDegraded(); + Degraded degraded2 = createDegraded(); + degraded1 = createDegraded(); + degraded2 = createDegraded(); + degraded1.setCharge(54); + assertTrue(comparator.compare(degraded1, degraded2) != 0); + assertTrue(comparator.compare(degraded2, degraded1) != 0); + + degraded1 = createDegraded(); + degraded2 = createDegraded(); + assertTrue(comparator.compare(null, degraded2) != 0); + assertTrue(comparator.compare(degraded2, null) != 0); + assertTrue(comparator.compare(null, null) == 0); + + Degraded degraded = createDegraded(); + degraded.setName("n"); + assertTrue(comparator.compare(degraded, degraded1) != 0); + + assertTrue(comparator.compare(degraded, Mockito.mock(Degraded.class)) != 0); } public Degraded createDegraded() { diff --git a/model/src/test/java/lcsb/mapviewer/model/map/species/DegradedTest.java b/model/src/test/java/lcsb/mapviewer/model/map/species/DegradedTest.java index 49e886ebf577b9bf27ed41f23b1105bdab7b0179..68ee746e1e0f353d07e19d35ce5fe9c20dfb7118 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/species/DegradedTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/species/DegradedTest.java @@ -1,80 +1,51 @@ package lcsb.mapviewer.model.map.species; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.mockito.Mockito; +import lcsb.mapviewer.ModelTestFunctions; import lcsb.mapviewer.common.exception.NotImplementedException; -public class DegradedTest { - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testSerialization() { - try { - SerializationUtils.serialize(new Degraded()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testConstructor1() { - try { - Degraded degraded = new Degraded(""); - assertNotNull(degraded); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testGetters() { - try { - Degraded degraded = new Degraded(new Degraded()); - assertNotNull(degraded.getStringType()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testCopy() { - try { - Degraded degraded = new Degraded().copy(); - assertNotNull(degraded); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testInvalidCopy() { - try { - Degraded object = Mockito.spy(Degraded.class); - object.copy(); - fail("Exception expected"); - } catch (NotImplementedException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } +public class DegradedTest extends ModelTestFunctions { + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testSerialization() { + SerializationUtils.serialize(new Degraded()); + } + + @Test + public void testConstructor1() { + Degraded degraded = new Degraded(""); + assertNotNull(degraded); + } + + @Test + public void testGetters() { + Degraded degraded = new Degraded(new Degraded()); + assertNotNull(degraded.getStringType()); + } + + @Test + public void testCopy() { + Degraded degraded = new Degraded().copy(); + assertNotNull(degraded); + } + + @Test(expected = NotImplementedException.class) + public void testInvalidCopy() { + Degraded object = Mockito.spy(Degraded.class); + object.copy(); + } } diff --git a/model/src/test/java/lcsb/mapviewer/model/map/species/DrugComparatorTest.java b/model/src/test/java/lcsb/mapviewer/model/map/species/DrugComparatorTest.java index 2351016ea2a5e39bfc595214a637c4026a2df3b0..ae3b3a1b05d5608b479700e0dbeb28515f4f3492 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/species/DrugComparatorTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/species/DrugComparatorTest.java @@ -1,17 +1,14 @@ package lcsb.mapviewer.model.map.species; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.mockito.Mockito; +import lcsb.mapviewer.ModelTestFunctions; import lcsb.mapviewer.common.exception.NotImplementedException; -public class DrugComparatorTest { +public class DrugComparatorTest extends ModelTestFunctions { DrugComparator comparator = new DrugComparator(); @@ -25,39 +22,27 @@ public class DrugComparatorTest { @Test public void testEquals() { - try { - Drug drug1 = createDrug(); - Drug drug2 = createDrug(); + Drug drug1 = createDrug(); + Drug drug2 = createDrug(); - assertEquals(0, comparator.compare(drug1, drug1)); + assertEquals(0, comparator.compare(drug1, drug1)); - assertEquals(0, comparator.compare(drug1, drug2)); - assertEquals(0, comparator.compare(drug2, drug1)); - - } catch (Exception e) { - e.printStackTrace(); - fail("Unknowne exception occurred"); - } + assertEquals(0, comparator.compare(drug1, drug2)); + assertEquals(0, comparator.compare(drug2, drug1)); } @Test public void testDifferent() { - try { - Drug drug2 = createDrug(); - assertTrue(comparator.compare(null, drug2) != 0); - assertTrue(comparator.compare(drug2, null) != 0); - assertTrue(comparator.compare(null, null) == 0); - - Drug drug = createDrug(); - drug.setName("n"); - assertTrue(comparator.compare(drug, drug2) != 0); - - assertTrue(comparator.compare(drug, Mockito.mock(Drug.class)) != 0); - - } catch (Exception e) { - e.printStackTrace(); - fail("Unknowne exception occurred"); - } + Drug drug2 = createDrug(); + assertTrue(comparator.compare(null, drug2) != 0); + assertTrue(comparator.compare(drug2, null) != 0); + assertTrue(comparator.compare(null, null) == 0); + + Drug drug = createDrug(); + drug.setName("n"); + assertTrue(comparator.compare(drug, drug2) != 0); + + assertTrue(comparator.compare(drug, Mockito.mock(Drug.class)) != 0); } public Drug createDrug() { diff --git a/model/src/test/java/lcsb/mapviewer/model/map/species/DrugTest.java b/model/src/test/java/lcsb/mapviewer/model/map/species/DrugTest.java index 1bebe8771b290e8996e3970af1b8577be8047189..70f973bfc116f498e151bed15524a02891f3883a 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/species/DrugTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/species/DrugTest.java @@ -1,80 +1,51 @@ package lcsb.mapviewer.model.map.species; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.mockito.Mockito; +import lcsb.mapviewer.ModelTestFunctions; import lcsb.mapviewer.common.exception.NotImplementedException; -public class DrugTest { - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testSerialization() { - try { - SerializationUtils.serialize(new Drug()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testConstructor1() { - try { - Drug degraded = new Drug(""); - assertNotNull(degraded); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testGetters() { - try { - Drug degraded = new Drug(new Drug()); - assertNotNull(degraded.getStringType()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testCopy() { - try { - Drug degraded = new Drug().copy(); - assertNotNull(degraded); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testInvalidCopy() { - try { - Drug drug = Mockito.spy(Drug.class); - drug.copy(); - fail("Exception expected"); - } catch (NotImplementedException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } +public class DrugTest extends ModelTestFunctions { + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testSerialization() { + SerializationUtils.serialize(new Drug()); + } + + @Test + public void testConstructor1() { + Drug degraded = new Drug(""); + assertNotNull(degraded); + } + + @Test + public void testGetters() { + Drug degraded = new Drug(new Drug()); + assertNotNull(degraded.getStringType()); + } + + @Test + public void testCopy() { + Drug degraded = new Drug().copy(); + assertNotNull(degraded); + } + + @Test(expected = NotImplementedException.class) + public void testInvalidCopy() { + Drug drug = Mockito.spy(Drug.class); + drug.copy(); + } } diff --git a/model/src/test/java/lcsb/mapviewer/model/map/species/ElementComparatorTest.java b/model/src/test/java/lcsb/mapviewer/model/map/species/ElementComparatorTest.java index 43c37006a98b7f1c320e39edacbb545af60b8c61..a9b75ad52ae92b0ffb2c29e775efbf0e8f755613 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/species/ElementComparatorTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/species/ElementComparatorTest.java @@ -1,31 +1,23 @@ package lcsb.mapviewer.model.map.species; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import java.awt.Color; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.mockito.Mockito; +import lcsb.mapviewer.ModelTestFunctions; import lcsb.mapviewer.common.exception.InvalidClassException; import lcsb.mapviewer.common.exception.NotImplementedException; -import lcsb.mapviewer.model.map.MiriamData; -import lcsb.mapviewer.model.map.MiriamRelationType; -import lcsb.mapviewer.model.map.MiriamType; +import lcsb.mapviewer.model.map.*; import lcsb.mapviewer.model.map.compartment.Compartment; import lcsb.mapviewer.model.map.layout.graphics.Layer; -import lcsb.mapviewer.model.map.model.ElementSubmodelConnection; -import lcsb.mapviewer.model.map.model.Model; -import lcsb.mapviewer.model.map.model.ModelFullIndexed; -import lcsb.mapviewer.model.map.model.SubmodelType; +import lcsb.mapviewer.model.map.model.*; import lcsb.mapviewer.model.map.reaction.Reaction; import lcsb.mapviewer.model.map.species.field.PositionToCompartment; -public class ElementComparatorTest { +public class ElementComparatorTest extends ModelTestFunctions { ElementComparator comparator = new ElementComparator(); @@ -37,88 +29,67 @@ public class ElementComparatorTest { public void tearDown() throws Exception { } - @Test + @Test(expected = NotImplementedException.class) public void testCompareException() throws Exception { - try { - comparator.compare(Mockito.mock(Element.class), Mockito.mock(Element.class)); - - fail("Exception should occur"); - } catch (NotImplementedException e) { - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + comparator.compare(Mockito.mock(Element.class), Mockito.mock(Element.class)); } @Test public void testDifferent() throws Exception { - try { - assertTrue(comparator.compare(new GenericProtein("id2"), new GenericProtein("id1")) != 0); - - assertTrue(comparator.compare(null, new GenericProtein()) != 0); - assertTrue(comparator.compare(new GenericProtein(), null) != 0); - assertTrue(comparator.compare(new GenericProtein(), new Complex()) != 0); - - Species sa1 = new GenericProtein("id2"); - Species sa2 = new GenericProtein("id2"); - sa2.setX(2); - assertTrue(comparator.compare(sa1, sa2) != 0); - - sa1 = new GenericProtein("id2"); - sa2 = new GenericProtein("id2"); - sa2.setY(2); - assertTrue(comparator.compare(sa1, sa2) != 0); - - sa1 = new GenericProtein("id2"); - sa2 = new GenericProtein("id2"); - sa2.setHeight(2); - assertTrue(comparator.compare(sa1, sa2) != 0); - - sa1 = new GenericProtein("id2"); - sa2 = new GenericProtein("id2"); - sa2.setFontSize(2); - assertTrue(comparator.compare(sa1, sa2) != 0); - - sa1 = new GenericProtein("id2"); - sa2 = new GenericProtein("id2"); - sa2.setColor(Color.BLUE); - assertTrue(comparator.compare(sa1, sa2) != 0); - - sa1 = new GenericProtein("id2"); - sa2 = new GenericProtein("id2"); - sa2.setVisibilityLevel(6); - assertTrue(comparator.compare(sa1, sa2) != 0); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertTrue(comparator.compare(new GenericProtein("id2"), new GenericProtein("id1")) != 0); + + assertTrue(comparator.compare(null, new GenericProtein()) != 0); + assertTrue(comparator.compare(new GenericProtein(), null) != 0); + assertTrue(comparator.compare(new GenericProtein(), new Complex()) != 0); + + Species sa1 = new GenericProtein("id2"); + Species sa2 = new GenericProtein("id2"); + sa2.setX(2); + assertTrue(comparator.compare(sa1, sa2) != 0); + + sa1 = new GenericProtein("id2"); + sa2 = new GenericProtein("id2"); + sa2.setY(2); + assertTrue(comparator.compare(sa1, sa2) != 0); + + sa1 = new GenericProtein("id2"); + sa2 = new GenericProtein("id2"); + sa2.setHeight(2); + assertTrue(comparator.compare(sa1, sa2) != 0); + + sa1 = new GenericProtein("id2"); + sa2 = new GenericProtein("id2"); + sa2.setFontSize(2); + assertTrue(comparator.compare(sa1, sa2) != 0); + + sa1 = new GenericProtein("id2"); + sa2 = new GenericProtein("id2"); + sa2.setColor(Color.BLUE); + assertTrue(comparator.compare(sa1, sa2) != 0); + + sa1 = new GenericProtein("id2"); + sa2 = new GenericProtein("id2"); + sa2.setVisibilityLevel(6); + assertTrue(comparator.compare(sa1, sa2) != 0); } @Test public void testCompareSubmodel() throws Exception { - try { - Element element1 = createElement(); - Element element2 = createElement(); - assertEquals(0, comparator.compare(element1, element2)); + Element element1 = createElement(); + Element element2 = createElement(); + assertEquals(0, comparator.compare(element1, element2)); - element1.setSubmodel(null); - assertTrue(comparator.compare(element1, element2) != 0); - assertTrue(comparator.compare(element2, element1) != 0); + element1.setSubmodel(null); + assertTrue(comparator.compare(element1, element2) != 0); + assertTrue(comparator.compare(element2, element1) != 0); - element1 = createElement(); - element2 = createElement(); + element1 = createElement(); + element2 = createElement(); - element1.getSubmodel().setName("Na"); + element1.getSubmodel().setName("Na"); - assertTrue(comparator.compare(element1, element2) != 0); - assertTrue(comparator.compare(element2, element1) != 0); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertTrue(comparator.compare(element1, element2) != 0); + assertTrue(comparator.compare(element2, element1) != 0); } private Element createElement() { @@ -150,141 +121,112 @@ public class ElementComparatorTest { return model; } - @Test + @Test(expected = NotImplementedException.class) public void testException() { - try { - Element el = Mockito.mock(Element.class); - comparator.compare(el, el); - - fail("Exception should occur"); - } catch (NotImplementedException e) { - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Element el = Mockito.mock(Element.class); + comparator.compare(el, el); } @Test public void testInternalCompare() { - try { - SimpleMolecule species1 = createSimpleMolecule(); - assertTrue(comparator.internalCompare(species1, null) != 0); - assertTrue(comparator.internalCompare(null, species1) != 0); - - assertEquals(0, comparator.internalCompare(null, null)); - - } catch (InvalidClassException e) { + SimpleMolecule species1 = createSimpleMolecule(); + assertTrue(comparator.internalCompare(species1, null) != 0); + assertTrue(comparator.internalCompare(null, species1) != 0); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, comparator.internalCompare(null, null)); } @Test public void testDifferent2() { - try { - SimpleMolecule species1 = createSimpleMolecule(); - SimpleMolecule species2 = createSimpleMolecule(); - - species1.setCharge(99); - assertTrue(comparator.compare(species1, species2) != 0); - assertTrue(comparator.compare(species2, species1) != 0); - - species1 = createSimpleMolecule(); - species2 = createSimpleMolecule(); - species1.setHomodimer(233); - assertTrue(comparator.compare(species1, species2) != 0); - assertTrue(comparator.compare(species2, species1) != 0); - - species1 = createSimpleMolecule(); - species2 = createSimpleMolecule(); - species1.setFormula("a"); - assertTrue(comparator.compare(species1, species2) != 0); - assertTrue(comparator.compare(species2, species1) != 0); - - species1 = createSimpleMolecule(); - species2 = createSimpleMolecule(); - species1.setElementId(""); - species1.setElementId("ASD"); - assertTrue(comparator.compare(species1, species2) != 0); - assertTrue(comparator.compare(species2, species1) != 0); - - species1 = createSimpleMolecule(); - species2 = createSimpleMolecule(); - species1.setNotes("ASD"); - assertTrue(comparator.compare(species1, species2) != 0); - assertTrue(comparator.compare(species2, species1) != 0); - - species1 = createSimpleMolecule(); - species2 = createSimpleMolecule(); - species1.setPositionToCompartment(PositionToCompartment.INSIDE); - assertTrue(comparator.compare(species1, species2) != 0); - assertTrue(comparator.compare(species2, species1) != 0); - - species1 = createSimpleMolecule(); - species2 = createSimpleMolecule(); - species1.getMiriamData().clear(); - assertTrue(comparator.compare(species1, species2) != 0); - assertTrue(comparator.compare(species2, species1) != 0); - - species1 = createSimpleMolecule(); - species2 = createSimpleMolecule(); - species1.getMiriamData().iterator().next().setRelationType(MiriamRelationType.BQ_BIOL_HAS_PART); - assertTrue(comparator.compare(species1, species2) != 0); - assertTrue(comparator.compare(species2, species1) != 0); - - species1 = createSimpleMolecule(); - species2 = createSimpleMolecule(); - species1.addMiriamData(new MiriamData()); - assertTrue(comparator.compare(species1, species2) != 0); - assertTrue(comparator.compare(species2, species1) != 0); - - assertTrue(comparator.compare(species1, null) != 0); - assertTrue(comparator.compare(null, species1) != 0); - - } catch (Exception e) { - e.printStackTrace(); - fail("Unkowne exception"); - } + SimpleMolecule species1 = createSimpleMolecule(); + SimpleMolecule species2 = createSimpleMolecule(); + + species1.setCharge(99); + assertTrue(comparator.compare(species1, species2) != 0); + assertTrue(comparator.compare(species2, species1) != 0); + + species1 = createSimpleMolecule(); + species2 = createSimpleMolecule(); + species1.setHomodimer(233); + assertTrue(comparator.compare(species1, species2) != 0); + assertTrue(comparator.compare(species2, species1) != 0); + + species1 = createSimpleMolecule(); + species2 = createSimpleMolecule(); + species1.setFormula("a"); + assertTrue(comparator.compare(species1, species2) != 0); + assertTrue(comparator.compare(species2, species1) != 0); + + species1 = createSimpleMolecule(); + species2 = createSimpleMolecule(); + species1.setElementId(""); + species1.setElementId("ASD"); + assertTrue(comparator.compare(species1, species2) != 0); + assertTrue(comparator.compare(species2, species1) != 0); + + species1 = createSimpleMolecule(); + species2 = createSimpleMolecule(); + species1.setNotes("ASD"); + assertTrue(comparator.compare(species1, species2) != 0); + assertTrue(comparator.compare(species2, species1) != 0); + + species1 = createSimpleMolecule(); + species2 = createSimpleMolecule(); + species1.setPositionToCompartment(PositionToCompartment.INSIDE); + assertTrue(comparator.compare(species1, species2) != 0); + assertTrue(comparator.compare(species2, species1) != 0); + + species1 = createSimpleMolecule(); + species2 = createSimpleMolecule(); + species1.getMiriamData().clear(); + assertTrue(comparator.compare(species1, species2) != 0); + assertTrue(comparator.compare(species2, species1) != 0); + + species1 = createSimpleMolecule(); + species2 = createSimpleMolecule(); + species1.getMiriamData().iterator().next().setRelationType(MiriamRelationType.BQ_BIOL_HAS_PART); + assertTrue(comparator.compare(species1, species2) != 0); + assertTrue(comparator.compare(species2, species1) != 0); + + species1 = createSimpleMolecule(); + species2 = createSimpleMolecule(); + species1.addMiriamData(new MiriamData()); + assertTrue(comparator.compare(species1, species2) != 0); + assertTrue(comparator.compare(species2, species1) != 0); + + assertTrue(comparator.compare(species1, null) != 0); + assertTrue(comparator.compare(null, species1) != 0); } @Test public void testDifferentNewFields() throws Exception { - try { - SimpleMolecule species1 = createSimpleMolecule(); - SimpleMolecule species2 = createSimpleMolecule(); + SimpleMolecule species1 = createSimpleMolecule(); + SimpleMolecule species2 = createSimpleMolecule(); - species1.setSymbol("some symbol"); - assertTrue(comparator.compare(species1, species2) != 0); - assertTrue(comparator.compare(species2, species1) != 0); + species1.setSymbol("some symbol"); + assertTrue(comparator.compare(species1, species2) != 0); + assertTrue(comparator.compare(species2, species1) != 0); - species1 = createSimpleMolecule(); - species2 = createSimpleMolecule(); + species1 = createSimpleMolecule(); + species2 = createSimpleMolecule(); - species1.setFullName("some symbol"); - assertTrue(comparator.compare(species1, species2) != 0); - assertTrue(comparator.compare(species2, species1) != 0); + species1.setFullName("some symbol"); + assertTrue(comparator.compare(species1, species2) != 0); + assertTrue(comparator.compare(species2, species1) != 0); - species1 = createSimpleMolecule(); - species2 = createSimpleMolecule(); + species1 = createSimpleMolecule(); + species2 = createSimpleMolecule(); - species1.getSynonyms().add("asd"); - assertTrue(comparator.compare(species1, species2) != 0); - assertTrue(comparator.compare(species2, species1) != 0); + species1.getSynonyms().add("asd"); + assertTrue(comparator.compare(species1, species2) != 0); + assertTrue(comparator.compare(species2, species1) != 0); - species1 = createSimpleMolecule(); - species2 = createSimpleMolecule(); + species1 = createSimpleMolecule(); + species2 = createSimpleMolecule(); - species1.getFormerSymbols().add("asd"); - assertTrue(comparator.compare(species1, species2) != 0); - assertTrue(comparator.compare(species2, species1) != 0); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + species1.getFormerSymbols().add("asd"); + assertTrue(comparator.compare(species1, species2) != 0); + assertTrue(comparator.compare(species2, species1) != 0); } public SimpleMolecule createSimpleMolecule() { @@ -304,52 +246,40 @@ public class ElementComparatorTest { @Test public void testDifferentNewReconFields() throws Exception { - try { - SimpleMolecule element1 = createSimpleMolecule(); - - SimpleMolecule element2 = createSimpleMolecule(); - element2.setAbbreviation("ABRR"); + SimpleMolecule element1 = createSimpleMolecule(); - assertTrue(comparator.compare(element1, element2) != 0); + SimpleMolecule element2 = createSimpleMolecule(); + element2.setAbbreviation("ABRR"); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertTrue(comparator.compare(element1, element2) != 0); } @Test public void testCompareZIndex() throws Exception { - try { - SimpleMolecule species1 = createSimpleMolecule(); - SimpleMolecule species2 = createSimpleMolecule(); - - species1.setZ(12); - assertTrue(comparator.compare(species1, species2) != 0); - assertTrue(comparator.compare(species2, species1) != 0); + SimpleMolecule species1 = createSimpleMolecule(); + SimpleMolecule species2 = createSimpleMolecule(); - species1 = createSimpleMolecule(); - species2 = createSimpleMolecule(); + species1.setZ(12); + assertTrue(comparator.compare(species1, species2) != 0); + assertTrue(comparator.compare(species2, species1) != 0); - species1.setZ(12); - species2.setZ(13); + species1 = createSimpleMolecule(); + species2 = createSimpleMolecule(); - assertTrue(comparator.compare(species1, species2) != 0); - assertTrue(comparator.compare(species2, species1) != 0); + species1.setZ(12); + species2.setZ(13); - species1 = createSimpleMolecule(); - species2 = createSimpleMolecule(); + assertTrue(comparator.compare(species1, species2) != 0); + assertTrue(comparator.compare(species2, species1) != 0); - species1.setZ(12); - species2.setZ(12); + species1 = createSimpleMolecule(); + species2 = createSimpleMolecule(); - assertEquals(0, comparator.compare(species1, species2)); - assertEquals(0, comparator.compare(species2, species1)); + species1.setZ(12); + species2.setZ(12); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, comparator.compare(species1, species2)); + assertEquals(0, comparator.compare(species2, species1)); } } diff --git a/model/src/test/java/lcsb/mapviewer/model/map/species/ElementTest.java b/model/src/test/java/lcsb/mapviewer/model/map/species/ElementTest.java index 0806862ac6938468d5f054aa8e4b4e8ca4245fdb..13119ca59757055d1188ae36b3448fb24685ae2e 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/species/ElementTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/species/ElementTest.java @@ -1,434 +1,363 @@ package lcsb.mapviewer.model.map.species; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import java.awt.geom.Point2D; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import java.util.*; + +import org.junit.*; import org.mockito.Mockito; import lcsb.mapviewer.ModelTestFunctions; import lcsb.mapviewer.common.Configuration; import lcsb.mapviewer.common.exception.InvalidArgumentException; -import lcsb.mapviewer.model.map.MiriamData; -import lcsb.mapviewer.model.map.MiriamType; -import lcsb.mapviewer.model.map.SearchIndex; +import lcsb.mapviewer.model.map.*; import lcsb.mapviewer.model.map.compartment.Compartment; import lcsb.mapviewer.model.map.layout.graphics.Glyph; import lcsb.mapviewer.model.map.layout.graphics.LayerText; -import lcsb.mapviewer.model.map.model.ElementSubmodelConnection; -import lcsb.mapviewer.model.map.model.Model; -import lcsb.mapviewer.model.map.model.ModelData; -import lcsb.mapviewer.model.map.model.ModelFullIndexed; +import lcsb.mapviewer.model.map.model.*; public class ElementTest extends ModelTestFunctions { - private static double EPSILON = Configuration.EPSILON; - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testDistance1() { - Species species = new GenericProtein(); - species.setWidth(10); - species.setHeight(20); - species.setX(100.0); - species.setY(200.0); - double distance = species.getDistanceFromPoint(species.getCenter()); - assertEquals(0, distance, EPSILON); - } - - @Test - public void testDistance2() { - Species species = new GenericProtein(); - species.setWidth(10); - species.setHeight(20); - species.setX(100.0); - species.setY(200.0); - double distance = species.getDistanceFromPoint(new Point2D.Double(100, 205)); - assertEquals(0, distance, EPSILON); - } - - @Test - public void testDistance6() { - Species species = new GenericProtein(); - species.setWidth(10); - species.setHeight(20); - species.setX(100.0); - species.setY(200.0); - double distance = species.getDistanceFromPoint(new Point2D.Double(105, 95)); - assertEquals(105, distance, EPSILON); - } - - @Test - public void testDistance3() { - Species species = new GenericProtein(); - species.setWidth(10); - species.setHeight(20); - species.setX(100.0); - species.setY(200.0); - double distance = species.getDistanceFromPoint(new Point2D.Double(50, 205)); - assertEquals(50, distance, EPSILON); - } - - @Test - public void testDistance4() { - Species species = new GenericProtein(); - species.setWidth(10); - species.setHeight(20); - species.setX(100.0); - species.setY(200.0); - double distance = species.getDistanceFromPoint(new Point2D.Double(120, 230)); - assertEquals(Math.sqrt(200), distance, EPSILON); - } - - @Test - public void testConstructor() { - try { - GenericProtein protein = new GenericProtein(); - protein.addSearchIndex(new SearchIndex()); - protein.setSubmodel(new ElementSubmodelConnection()); - Element copy = new GenericProtein(protein); - assertNotNull(copy); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + private static double EPSILON = Configuration.EPSILON; + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testDistance1() { + Species species = new GenericProtein(); + species.setWidth(10); + species.setHeight(20); + species.setX(100.0); + species.setY(200.0); + double distance = species.getDistanceFromPoint(species.getCenter()); + assertEquals(0, distance, EPSILON); + } + + @Test + public void testDistance2() { + Species species = new GenericProtein(); + species.setWidth(10); + species.setHeight(20); + species.setX(100.0); + species.setY(200.0); + double distance = species.getDistanceFromPoint(new Point2D.Double(100, 205)); + assertEquals(0, distance, EPSILON); + } + + @Test + public void testDistance6() { + Species species = new GenericProtein(); + species.setWidth(10); + species.setHeight(20); + species.setX(100.0); + species.setY(200.0); + double distance = species.getDistanceFromPoint(new Point2D.Double(105, 95)); + assertEquals(105, distance, EPSILON); + } + + @Test + public void testDistance3() { + Species species = new GenericProtein(); + species.setWidth(10); + species.setHeight(20); + species.setX(100.0); + species.setY(200.0); + double distance = species.getDistanceFromPoint(new Point2D.Double(50, 205)); + assertEquals(50, distance, EPSILON); + } + + @Test + public void testDistance4() { + Species species = new GenericProtein(); + species.setWidth(10); + species.setHeight(20); + species.setX(100.0); + species.setY(200.0); + double distance = species.getDistanceFromPoint(new Point2D.Double(120, 230)); + assertEquals(Math.sqrt(200), distance, EPSILON); + } + + @Test + public void testConstructor() { + GenericProtein protein = new GenericProtein(); + protein.addSearchIndex(new SearchIndex()); + protein.setSubmodel(new ElementSubmodelConnection()); + Element copy = new GenericProtein(protein); + assertNotNull(copy); + } + + @Test + public void testCopyGlyph() { + GenericProtein protein = new GenericProtein(); + protein.addSearchIndex(new SearchIndex()); + protein.setSubmodel(new ElementSubmodelConnection()); + protein.setGlyph(new Glyph()); + Element copy = new GenericProtein(protein); + assertNotNull(copy.getGlyph()); + ElementComparator comparator = new ElementComparator(); + assertEquals(0, comparator.compare(copy, protein)); + } + + @Test + public void testCopyWithoutGlyph() { + GenericProtein protein = new GenericProtein(); + Element copy = new GenericProtein(protein); + assertNull(copy.getGlyph()); + } + + @Test + public void testIncreaseBorder() { + Species protein = new GenericProtein(); + assertEquals(0.0, protein.getSize(), Configuration.EPSILON); + protein.increaseBorder(2); + assertEquals(16.0, protein.getSize(), Configuration.EPSILON); + } + + @Test(expected = InvalidArgumentException.class) + public void testSetInvalidWidth() { + Element element = new GenericProtein(); + element.setWidth("as"); + } + + @Test(expected = InvalidArgumentException.class) + public void testSetInvalidHeight() { + Element element = new GenericProtein(); + element.setHeight("as"); + } + + @Test + public void testGetters() { + Element element = new GenericProtein(); + Double nullDouble = null; + String xStr = "1.2"; + Double x = 1.2; + String yStr = "1.3"; + Double y = 1.3; + String fontSizeStr = "5.0"; + Double fontSize = 5.0; + int fontSizeInt = 5; + String widthStr = "3.0"; + Double width = 3.0; + String heightStr = "4.0"; + Double height = 4.0; + ModelData modelData = new ModelData(); + Set<MiriamData> miriamData = new HashSet<>(); + Compartment compartment = new Compartment("idd"); + int id = 72; + String transparencyLevel = "2"; + Model model = new ModelFullIndexed(modelData); + List<SearchIndex> indexes = new ArrayList<>(); + indexes.add(new SearchIndex()); + + element.setMiriamData(miriamData); + assertEquals(miriamData, element.getMiriamData()); + + element.setX(xStr); + assertEquals(x, element.getX(), Configuration.EPSILON); + element.setX(nullDouble); + assertNull(element.getX()); + element.setX(x); + assertEquals(x, element.getX(), Configuration.EPSILON); + + element.setY(yStr); + assertEquals(y, element.getY(), Configuration.EPSILON); + element.setY(nullDouble); + assertNull(element.getY()); + element.setY(y); + assertEquals(y, element.getY(), Configuration.EPSILON); + + element.setFontSize(fontSizeStr); + assertEquals(fontSize, element.getFontSize(), Configuration.EPSILON); + element.setFontSize(nullDouble); + assertNull(element.getFontSize()); + element.setFontSize(fontSize); + assertEquals(fontSize, element.getFontSize(), Configuration.EPSILON); + element.setFontSize(nullDouble); + assertNull(element.getFontSize()); + element.setFontSize(fontSizeInt); + assertEquals(fontSize, element.getFontSize(), Configuration.EPSILON); + + element.setWidth(widthStr); + assertEquals(width, element.getWidth(), Configuration.EPSILON); + element.setWidth(nullDouble); + assertNull(element.getWidth()); + element.setWidth(width); + assertEquals(width, element.getWidth(), Configuration.EPSILON); + + element.setHeight(heightStr); + assertEquals(height, element.getHeight(), Configuration.EPSILON); + element.setHeight(nullDouble); + assertNull(element.getHeight()); + element.setHeight(height); + assertEquals(height, element.getHeight(), Configuration.EPSILON); + + element.setCompartment(compartment); + assertEquals(compartment, element.getCompartment()); + element.setId(id); + assertEquals(id, element.getId()); + element.setTransparencyLevel(transparencyLevel); + assertEquals(transparencyLevel, element.getTransparencyLevel()); + element.setModel(model); + assertEquals(model, element.getModel()); + element.setModelData(modelData); + assertEquals(modelData, element.getModelData()); + element.setSearchIndexes(indexes); + assertEquals(indexes, element.getSearchIndexes()); + + assertNotNull(element.getBorder()); + + element = Mockito.spy(Element.class); + List<String> synonyms = new ArrayList<>(); + List<String> formerSymbols = new ArrayList<>(); + String formula = "some_form"; + + element.setSynonyms(synonyms); + element.setFormerSymbols(formerSymbols); + element.setModel(model); + element.setFormula(formula); + + assertEquals(synonyms, element.getSynonyms()); + assertEquals(formerSymbols, element.getFormerSymbols()); + assertEquals(model.getModelData(), element.getModelData()); + assertEquals(formula, element.getFormula()); + } + + @Test + public void testContainsElement() { + Species element = new GenericProtein(); + element.setWidth(100); + element.setHeight(100); + Species element2 = new GenericProtein(); + element2.setX(-2); + element2.setY(-2); + element2.setWidth(100); + element2.setHeight(100); + + assertTrue(element.contains(element2)); + element2.setX(2); + element2.setY(2); + assertTrue(element.contains(element2)); + element2.setX(-2); + element2.setY(2); + assertTrue(element.contains(element2)); + element2.setX(2); + element2.setY(-2); + assertTrue(element.contains(element2)); + + element2.setX(-2); + element2.setY(-2); + element2.setWidth(200); + element2.setHeight(200); + assertFalse(element.contains(element2)); + + Compartment compartment = new Compartment("idd"); + compartment.setX(2); + compartment.setY(2); + compartment.setWidth(10); + compartment.setHeight(100); + assertFalse(element.contains(compartment)); + + compartment.setWidth(100); + compartment.setHeight(10); + assertFalse(element.contains(compartment)); + + compartment.setWidth(10); + compartment.setHeight(10); + assertTrue(element.contains(compartment)); + + compartment.setWidth(100); + compartment.setHeight(100); + compartment.setX(-2); + compartment.setY(2); + assertFalse(element.contains(compartment)); + compartment.setX(2); + compartment.setY(-2); + assertFalse(element.contains(compartment)); + compartment.setX(-2); + compartment.setY(-2); + assertFalse(element.contains(compartment)); + } + + @Test + public void testContainsLayerText() { + Species protein = new GenericProtein(); + protein.setWidth(100); + protein.setHeight(100); + LayerText layerText = new LayerText(); + layerText.setX(2.0); + layerText.setY(2.0); + layerText.setWidth(100.0); + layerText.setHeight(100.0); + + assertFalse(protein.contains(layerText)); + layerText.setWidth(10.0); + layerText.setHeight(10.0); + assertTrue(protein.contains(layerText)); + } + + @Test + public void testAddMiriamCollection() { + List<MiriamData> list = new ArrayList<>(); + list.add(new MiriamData(MiriamType.CAS, "1")); + list.add(new MiriamData(MiriamType.CAS, "1")); + Element element = Mockito.spy(Element.class); + element.addMiriamData(list); + assertEquals(1, element.getMiriamData().size()); + assertEquals(1, getWarnings().size()); + + element.addMiriamData(list); + assertEquals(3, getWarnings().size()); + } + + @Test(expected = InvalidArgumentException.class) + public void testSetNotes() { + Element element = Mockito.spy(Element.class); + element.setNotes("</html>"); + } + + @Test + public void testAddSynonym() { + Element element = Mockito.spy(Element.class); + List<String> synonyms = new ArrayList<>(); + synonyms.add("syn"); + element.addSynonyms(synonyms); + element.addSynonym("syn2"); + assertEquals("syn", element.getSynonyms().get(0)); + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < 300; i++) { + sb.append("a"); } - - @Test - public void testCopyGlyph() { - try { - GenericProtein protein = new GenericProtein(); - protein.addSearchIndex(new SearchIndex()); - protein.setSubmodel(new ElementSubmodelConnection()); - protein.setGlyph(new Glyph()); - Element copy = new GenericProtein(protein); - assertNotNull(copy.getGlyph()); - ElementComparator comparator = new ElementComparator(); - assertEquals(0, comparator.compare(copy, protein)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String syn = sb.toString(); + synonyms = new ArrayList<>(); + synonyms.add(syn); + element.addSynonyms(synonyms); + assertFalse(syn.equals(element.getSynonyms().get(1))); + } + + @Test + public void testAddFormerSymbols() { + Element element = Mockito.spy(Element.class); + List<String> formerSymbols = new ArrayList<>(); + formerSymbols.add("symbol"); + element.addFormerSymbols(formerSymbols); + element.addFormerSymbol("symbol2"); + assertEquals("symbol", element.getFormerSymbols().get(0)); + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < 300; i++) { + sb.append("a"); } - - @Test - public void testCopyWithoutGlyph() { - try { - GenericProtein protein = new GenericProtein(); - Element copy = new GenericProtein(protein); - assertNull(copy.getGlyph()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testIncreaseBorder() { - try { - Species protein = new GenericProtein(); - assertEquals(0.0, protein.getSize(), Configuration.EPSILON); - protein.increaseBorder(2); - assertEquals(16.0, protein.getSize(), Configuration.EPSILON); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testGetters() { - try { - Element element = new GenericProtein(); - Double nullDouble = null; - String xStr = "1.2"; - Double x = 1.2; - String yStr = "1.3"; - Double y = 1.3; - String fontSizeStr = "5.0"; - Double fontSize = 5.0; - int fontSizeInt = 5; - String widthStr = "3.0"; - Double width = 3.0; - String heightStr = "4.0"; - Double height = 4.0; - ModelData modelData = new ModelData(); - Set<MiriamData> miriamData = new HashSet<>(); - Compartment compartment = new Compartment("idd"); - int id = 72; - String transparencyLevel = "2"; - Model model = new ModelFullIndexed(modelData); - List<SearchIndex> indexes = new ArrayList<>(); - indexes.add(new SearchIndex()); - - element.setMiriamData(miriamData); - assertEquals(miriamData, element.getMiriamData()); - - element.setX(xStr); - assertEquals(x, element.getX(), Configuration.EPSILON); - element.setX(nullDouble); - assertNull(element.getX()); - element.setX(x); - assertEquals(x, element.getX(), Configuration.EPSILON); - - element.setY(yStr); - assertEquals(y, element.getY(), Configuration.EPSILON); - element.setY(nullDouble); - assertNull(element.getY()); - element.setY(y); - assertEquals(y, element.getY(), Configuration.EPSILON); - - element.setFontSize(fontSizeStr); - assertEquals(fontSize, element.getFontSize(), Configuration.EPSILON); - element.setFontSize(nullDouble); - assertNull(element.getFontSize()); - element.setFontSize(fontSize); - assertEquals(fontSize, element.getFontSize(), Configuration.EPSILON); - element.setFontSize(nullDouble); - assertNull(element.getFontSize()); - element.setFontSize(fontSizeInt); - assertEquals(fontSize, element.getFontSize(), Configuration.EPSILON); - - element.setWidth(widthStr); - assertEquals(width, element.getWidth(), Configuration.EPSILON); - element.setWidth(nullDouble); - assertNull(element.getWidth()); - element.setWidth(width); - assertEquals(width, element.getWidth(), Configuration.EPSILON); - try { - element.setWidth("as"); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - } - - element.setHeight(heightStr); - assertEquals(height, element.getHeight(), Configuration.EPSILON); - element.setHeight(nullDouble); - assertNull(element.getHeight()); - element.setHeight(height); - assertEquals(height, element.getHeight(), Configuration.EPSILON); - try { - element.setHeight("as"); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - } - - element.setCompartment(compartment); - assertEquals(compartment, element.getCompartment()); - element.setId(id); - assertEquals(id, element.getId()); - element.setTransparencyLevel(transparencyLevel); - assertEquals(transparencyLevel, element.getTransparencyLevel()); - element.setModel(model); - assertEquals(model, element.getModel()); - element.setModelData(modelData); - assertEquals(modelData, element.getModelData()); - element.setSearchIndexes(indexes); - assertEquals(indexes, element.getSearchIndexes()); - - assertNotNull(element.getBorder()); - - element = Mockito.spy(Element.class); - List<String> synonyms = new ArrayList<>(); - List<String> formerSymbols = new ArrayList<>(); - String formula = "some_form"; - - element.setSynonyms(synonyms); - element.setFormerSymbols(formerSymbols); - element.setModel(model); - element.setFormula(formula); - - assertEquals(synonyms, element.getSynonyms()); - assertEquals(formerSymbols, element.getFormerSymbols()); - assertEquals(model.getModelData(), element.getModelData()); - assertEquals(formula, element.getFormula()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testContainsElement() { - try { - Species element = new GenericProtein(); - element.setWidth(100); - element.setHeight(100); - Species element2 = new GenericProtein(); - element2.setX(-2); - element2.setY(-2); - element2.setWidth(100); - element2.setHeight(100); - - assertTrue(element.contains(element2)); - element2.setX(2); - element2.setY(2); - assertTrue(element.contains(element2)); - element2.setX(-2); - element2.setY(2); - assertTrue(element.contains(element2)); - element2.setX(2); - element2.setY(-2); - assertTrue(element.contains(element2)); - - element2.setX(-2); - element2.setY(-2); - element2.setWidth(200); - element2.setHeight(200); - assertFalse(element.contains(element2)); - - Compartment compartment = new Compartment("idd"); - compartment.setX(2); - compartment.setY(2); - compartment.setWidth(10); - compartment.setHeight(100); - assertFalse(element.contains(compartment)); - - compartment.setWidth(100); - compartment.setHeight(10); - assertFalse(element.contains(compartment)); - - compartment.setWidth(10); - compartment.setHeight(10); - assertTrue(element.contains(compartment)); - - compartment.setWidth(100); - compartment.setHeight(100); - compartment.setX(-2); - compartment.setY(2); - assertFalse(element.contains(compartment)); - compartment.setX(2); - compartment.setY(-2); - assertFalse(element.contains(compartment)); - compartment.setX(-2); - compartment.setY(-2); - assertFalse(element.contains(compartment)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testContainsLayerText() { - try { - Species protein = new GenericProtein(); - protein.setWidth(100); - protein.setHeight(100); - LayerText layerText = new LayerText(); - layerText.setX(2.0); - layerText.setY(2.0); - layerText.setWidth(100.0); - layerText.setHeight(100.0); - - assertFalse(protein.contains(layerText)); - layerText.setWidth(10.0); - layerText.setHeight(10.0); - assertTrue(protein.contains(layerText)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testAddMiriamCollection() { - try { - List<MiriamData> list = new ArrayList<>(); - list.add(new MiriamData(MiriamType.CAS, "1")); - list.add(new MiriamData(MiriamType.CAS, "1")); - Element element = Mockito.spy(Element.class); - element.addMiriamData(list); - assertEquals(1, element.getMiriamData().size()); - assertEquals(1, getWarnings().size()); - - element.addMiriamData(list); - assertEquals(3, getWarnings().size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testSetNotes() { - try { - Element element = Mockito.spy(Element.class); - element.setNotes("</html>"); - fail("Exception epxected"); - } catch (InvalidArgumentException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testAddSynonym() { - try { - Element element = Mockito.spy(Element.class); - List<String> synonyms = new ArrayList<>(); - synonyms.add("syn"); - element.addSynonyms(synonyms); - element.addSynonym("syn2"); - assertEquals("syn", element.getSynonyms().get(0)); - StringBuilder sb = new StringBuilder(); - for (int i = 0; i < 300; i++) { - sb.append("a"); - } - String syn = sb.toString(); - synonyms = new ArrayList<>(); - synonyms.add(syn); - element.addSynonyms(synonyms); - assertFalse(syn.equals(element.getSynonyms().get(1))); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testAddFormerSymbols() { - try { - Element element = Mockito.spy(Element.class); - List<String> formerSymbols = new ArrayList<>(); - formerSymbols.add("symbol"); - element.addFormerSymbols(formerSymbols); - element.addFormerSymbol("symbol2"); - assertEquals("symbol", element.getFormerSymbols().get(0)); - StringBuilder sb = new StringBuilder(); - for (int i = 0; i < 300; i++) { - sb.append("a"); - } - String syn = sb.toString(); - formerSymbols = new ArrayList<>(); - formerSymbols.add(syn); - element.addFormerSymbols(formerSymbols); - assertFalse(syn.equals(element.getFormerSymbols().get(1))); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } + String syn = sb.toString(); + formerSymbols = new ArrayList<>(); + formerSymbols.add(syn); + element.addFormerSymbols(formerSymbols); + assertFalse(syn.equals(element.getFormerSymbols().get(1))); + } } diff --git a/model/src/test/java/lcsb/mapviewer/model/map/species/GeneComparatorTest.java b/model/src/test/java/lcsb/mapviewer/model/map/species/GeneComparatorTest.java index 4af40967c90ac8c0764e2c41f5fb376eb2c3724d..f39b00f3c949efac06ff21a6917bc3c58d6bf14d 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/species/GeneComparatorTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/species/GeneComparatorTest.java @@ -1,21 +1,18 @@ package lcsb.mapviewer.model.map.species; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import java.awt.geom.Point2D; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.mockito.Mockito; +import lcsb.mapviewer.ModelTestFunctions; import lcsb.mapviewer.common.exception.NotImplementedException; import lcsb.mapviewer.model.map.species.field.ModificationSite; import lcsb.mapviewer.model.map.species.field.ModificationState; -public class GeneComparatorTest { +public class GeneComparatorTest extends ModelTestFunctions { GeneComparator comparator = new GeneComparator(); @@ -29,52 +26,40 @@ public class GeneComparatorTest { @Test public void testEquals() { - try { - Gene gene1 = createGene(); - Gene gene2 = createGene(); + Gene gene1 = createGene(); + Gene gene2 = createGene(); - assertEquals(0, comparator.compare(gene1, gene1)); + assertEquals(0, comparator.compare(gene1, gene1)); - assertEquals(0, comparator.compare(gene1, gene2)); - assertEquals(0, comparator.compare(gene2, gene1)); - - } catch (Exception e) { - e.printStackTrace(); - fail("Unknowne exception occurred"); - } + assertEquals(0, comparator.compare(gene1, gene2)); + assertEquals(0, comparator.compare(gene2, gene1)); } @Test public void testDifferent() { - try { - Gene gene1 = createGene(); - Gene gene2 = createGene(); - gene1.getModificationResidues().get(0).setName("bla"); - assertTrue(comparator.compare(gene1, gene2) != 0); - assertTrue(comparator.compare(gene2, gene1) != 0); - - gene1 = createGene(); - gene2 = createGene(); - gene1.getModificationResidues().clear(); - assertTrue(comparator.compare(gene1, gene2) != 0); - assertTrue(comparator.compare(gene2, gene1) != 0); - - gene1 = createGene(); - gene2 = createGene(); - assertTrue(comparator.compare(null, gene2) != 0); - assertTrue(comparator.compare(gene2, null) != 0); - assertTrue(comparator.compare(null, null) == 0); - - Gene gene = createGene(); - gene.setName("n"); - assertTrue(comparator.compare(gene, gene2) != 0); - - assertTrue(comparator.compare(gene, Mockito.mock(Gene.class)) != 0); - - } catch (Exception e) { - e.printStackTrace(); - fail("Unknowne exception occurred"); - } + Gene gene1 = createGene(); + Gene gene2 = createGene(); + gene1.getModificationResidues().get(0).setName("bla"); + assertTrue(comparator.compare(gene1, gene2) != 0); + assertTrue(comparator.compare(gene2, gene1) != 0); + + gene1 = createGene(); + gene2 = createGene(); + gene1.getModificationResidues().clear(); + assertTrue(comparator.compare(gene1, gene2) != 0); + assertTrue(comparator.compare(gene2, gene1) != 0); + + gene1 = createGene(); + gene2 = createGene(); + assertTrue(comparator.compare(null, gene2) != 0); + assertTrue(comparator.compare(gene2, null) != 0); + assertTrue(comparator.compare(null, null) == 0); + + Gene gene = createGene(); + gene.setName("n"); + assertTrue(comparator.compare(gene, gene2) != 0); + + assertTrue(comparator.compare(gene, Mockito.mock(Gene.class)) != 0); } public Gene createGene() { @@ -91,20 +76,11 @@ public class GeneComparatorTest { return result; } - @Test + @Test(expected = NotImplementedException.class) public void testInvalid() { - try { - Gene object = Mockito.mock(Gene.class); - - comparator.compare(object, object); - - fail("Exception expected"); - } catch (NotImplementedException e) { + Gene object = Mockito.mock(Gene.class); - } catch (Exception e) { - e.printStackTrace(); - fail("Unknowne exception occurred"); - } + comparator.compare(object, object); } } diff --git a/model/src/test/java/lcsb/mapviewer/model/map/species/GeneTest.java b/model/src/test/java/lcsb/mapviewer/model/map/species/GeneTest.java index f79e6affe717efea9677644296bddade33ea15df..ca3450c307cf37db535f1aa39c9ab6a48b7c64ed 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/species/GeneTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/species/GeneTest.java @@ -1,23 +1,20 @@ package lcsb.mapviewer.model.map.species; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import java.util.ArrayList; import java.util.List; import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.mockito.Mockito; +import lcsb.mapviewer.ModelTestFunctions; import lcsb.mapviewer.common.exception.NotImplementedException; import lcsb.mapviewer.model.map.species.field.ModificationResidue; import lcsb.mapviewer.model.map.species.field.ModificationSite; -public class GeneTest { +public class GeneTest extends ModelTestFunctions { @Before public void setUp() throws Exception { @@ -29,63 +26,36 @@ public class GeneTest { @Test public void testSerialization() { - try { - SerializationUtils.serialize(new Gene()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + SerializationUtils.serialize(new Gene()); } @Test public void testConstructor1() { - try { - Gene original = new Gene(); - original.addModificationSite(new ModificationSite()); - Gene gene = new Gene(original); - assertNotNull(gene); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Gene original = new Gene(); + original.addModificationSite(new ModificationSite()); + Gene gene = new Gene(original); + assertNotNull(gene); } @Test public void testGetters() { - try { - List<ModificationResidue> modificationResidues = new ArrayList<>(); - Gene gene = new Gene("id"); - assertNotNull(gene.getStringType()); - gene.setModificationResidues(modificationResidues); - assertEquals(modificationResidues, gene.getModificationResidues()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + List<ModificationResidue> modificationResidues = new ArrayList<>(); + Gene gene = new Gene("id"); + assertNotNull(gene.getStringType()); + gene.setModificationResidues(modificationResidues); + assertEquals(modificationResidues, gene.getModificationResidues()); } @Test public void testCopy() { - try { - Gene degraded = new Gene().copy(); - assertNotNull(degraded); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Gene degraded = new Gene().copy(); + assertNotNull(degraded); } - @Test + @Test(expected = NotImplementedException.class) public void testInvalidCopy() { - try { - Gene gene = Mockito.spy(Gene.class); - gene.copy(); - fail("Exception expected"); - } catch (NotImplementedException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Gene gene = Mockito.spy(Gene.class); + gene.copy(); } } diff --git a/model/src/test/java/lcsb/mapviewer/model/map/species/GenericProteinComparatorTest.java b/model/src/test/java/lcsb/mapviewer/model/map/species/GenericProteinComparatorTest.java index aa378d8cddc47ce153fb34bf67acfa739c4eab0a..7f874e1c43b3a73b730a51b2c96ea10dbd78e14a 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/species/GenericProteinComparatorTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/species/GenericProteinComparatorTest.java @@ -1,84 +1,60 @@ package lcsb.mapviewer.model.map.species; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.mockito.Mockito; +import lcsb.mapviewer.ModelTestFunctions; import lcsb.mapviewer.common.exception.NotImplementedException; -public class GenericProteinComparatorTest { +public class GenericProteinComparatorTest extends ModelTestFunctions { - GenericProteinComparator comparator = new GenericProteinComparator(); + GenericProteinComparator comparator = new GenericProteinComparator(); - @Before - public void setUp() throws Exception { - } + @Before + public void setUp() throws Exception { + } - @After - public void tearDown() throws Exception { - } + @After + public void tearDown() throws Exception { + } - @Test - public void testEquals() { - try { - GenericProtein drug1 = createGenericProtein(); - GenericProtein drug2 = createGenericProtein(); + @Test + public void testEquals() { + GenericProtein drug1 = createGenericProtein(); + GenericProtein drug2 = createGenericProtein(); - assertEquals(0, comparator.compare(drug1, drug1)); + assertEquals(0, comparator.compare(drug1, drug1)); - assertEquals(0, comparator.compare(drug1, drug2)); - assertEquals(0, comparator.compare(drug2, drug1)); + assertEquals(0, comparator.compare(drug1, drug2)); + assertEquals(0, comparator.compare(drug2, drug1)); + } - } catch (Exception e) { - e.printStackTrace(); - fail("Unknowne exception occurred"); - } - } + @Test + public void testDifferent() { + GenericProtein drug2 = createGenericProtein(); + assertTrue(comparator.compare(null, drug2) != 0); + assertTrue(comparator.compare(drug2, null) != 0); + assertTrue(comparator.compare(null, null) == 0); - @Test - public void testDifferent() { - try { - GenericProtein drug2 = createGenericProtein(); - assertTrue(comparator.compare(null, drug2) != 0); - assertTrue(comparator.compare(drug2, null) != 0); - assertTrue(comparator.compare(null, null) == 0); + GenericProtein drug = createGenericProtein(); + drug.setName("n"); + assertTrue(comparator.compare(drug, drug2) != 0); - GenericProtein drug = createGenericProtein(); - drug.setName("n"); - assertTrue(comparator.compare(drug, drug2) != 0); + assertTrue(comparator.compare(drug, Mockito.mock(GenericProtein.class)) != 0); + } - assertTrue(comparator.compare(drug, Mockito.mock(GenericProtein.class)) != 0); + public GenericProtein createGenericProtein() { + GenericProtein result = new GenericProtein(); + return result; + } - } catch (Exception e) { - e.printStackTrace(); - fail("Unknowne exception occurred"); - } - } + @Test(expected = NotImplementedException.class) + public void testInvalid() { + GenericProtein object = Mockito.mock(GenericProtein.class); - public GenericProtein createGenericProtein() { - GenericProtein result = new GenericProtein(); - return result; - } - - @Test - public void testInvalid() { - try { - GenericProtein object = Mockito.mock(GenericProtein.class); - - comparator.compare(object, object); - - fail("Exception expected"); - } catch (NotImplementedException e) { - - } catch (Exception e) { - e.printStackTrace(); - fail("Unknowne exception occurred"); - } - } + comparator.compare(object, object); + } } diff --git a/model/src/test/java/lcsb/mapviewer/model/map/species/GenericProteinTest.java b/model/src/test/java/lcsb/mapviewer/model/map/species/GenericProteinTest.java index addbd76893e5c6405d30fb2482116dbc045b508b..aa6c24c5c12a7d61a3e24a2967170d9689243b01 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/species/GenericProteinTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/species/GenericProteinTest.java @@ -1,68 +1,44 @@ package lcsb.mapviewer.model.map.species; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.mockito.Mockito; +import lcsb.mapviewer.ModelTestFunctions; import lcsb.mapviewer.common.exception.NotImplementedException; -public class GenericProteinTest { - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testSerialization() { - try { - SerializationUtils.serialize(new GenericProtein()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testConstructor() { - try { - GenericProtein species = new GenericProtein(""); - assertNotNull(species); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testCopy1() { - try { - GenericProtein species = new GenericProtein(new GenericProtein()).copy(); - assertNotNull(species); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testCopy2() { - try { - GenericProtein protein = Mockito.spy(GenericProtein.class); - protein.copy(); - fail("Exception expected"); - } catch (NotImplementedException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } +public class GenericProteinTest extends ModelTestFunctions { + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testSerialization() { + SerializationUtils.serialize(new GenericProtein()); + } + + @Test + public void testConstructor() { + GenericProtein species = new GenericProtein(""); + assertNotNull(species); + } + + @Test + public void testCopy1() { + GenericProtein species = new GenericProtein(new GenericProtein()).copy(); + assertNotNull(species); + } + + @Test(expected = NotImplementedException.class) + public void testCopy2() { + GenericProtein protein = Mockito.spy(GenericProtein.class); + protein.copy(); + } } diff --git a/model/src/test/java/lcsb/mapviewer/model/map/species/IonChannelProteinComparatorTest.java b/model/src/test/java/lcsb/mapviewer/model/map/species/IonChannelProteinComparatorTest.java index 36795950cad8e00d4ee6d868779fe4eeb141e74a..0ad7b0f6d4d4032e57872c97ddb3366c1d72303f 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/species/IonChannelProteinComparatorTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/species/IonChannelProteinComparatorTest.java @@ -1,84 +1,60 @@ package lcsb.mapviewer.model.map.species; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.mockito.Mockito; +import lcsb.mapviewer.ModelTestFunctions; import lcsb.mapviewer.common.exception.NotImplementedException; -public class IonChannelProteinComparatorTest { +public class IonChannelProteinComparatorTest extends ModelTestFunctions { - IonChannelProteinComparator comparator = new IonChannelProteinComparator(); + IonChannelProteinComparator comparator = new IonChannelProteinComparator(); - @Before - public void setUp() throws Exception { - } + @Before + public void setUp() throws Exception { + } - @After - public void tearDown() throws Exception { - } + @After + public void tearDown() throws Exception { + } - @Test - public void testEquals() { - try { - IonChannelProtein drug1 = createIonChannelProtein(); - IonChannelProtein drug2 = createIonChannelProtein(); + @Test + public void testEquals() { + IonChannelProtein drug1 = createIonChannelProtein(); + IonChannelProtein drug2 = createIonChannelProtein(); - assertEquals(0, comparator.compare(drug1, drug1)); + assertEquals(0, comparator.compare(drug1, drug1)); - assertEquals(0, comparator.compare(drug1, drug2)); - assertEquals(0, comparator.compare(drug2, drug1)); + assertEquals(0, comparator.compare(drug1, drug2)); + assertEquals(0, comparator.compare(drug2, drug1)); + } - } catch (Exception e) { - e.printStackTrace(); - fail("Unknowne exception occurred"); - } - } + @Test + public void testDifferent() { + IonChannelProtein drug2 = createIonChannelProtein(); + assertTrue(comparator.compare(null, drug2) != 0); + assertTrue(comparator.compare(drug2, null) != 0); + assertTrue(comparator.compare(null, null) == 0); - @Test - public void testDifferent() { - try { - IonChannelProtein drug2 = createIonChannelProtein(); - assertTrue(comparator.compare(null, drug2) != 0); - assertTrue(comparator.compare(drug2, null) != 0); - assertTrue(comparator.compare(null, null) == 0); + IonChannelProtein drug = createIonChannelProtein(); + drug.setName("n"); + assertTrue(comparator.compare(drug, drug2) != 0); - IonChannelProtein drug = createIonChannelProtein(); - drug.setName("n"); - assertTrue(comparator.compare(drug, drug2) != 0); + assertTrue(comparator.compare(drug, Mockito.mock(IonChannelProtein.class)) != 0); + } - assertTrue(comparator.compare(drug, Mockito.mock(IonChannelProtein.class)) != 0); + public IonChannelProtein createIonChannelProtein() { + IonChannelProtein result = new IonChannelProtein(); + return result; + } - } catch (Exception e) { - e.printStackTrace(); - fail("Unknowne exception occurred"); - } - } + @Test(expected = NotImplementedException.class) + public void testInvalid() { + IonChannelProtein object = Mockito.mock(IonChannelProtein.class); - public IonChannelProtein createIonChannelProtein() { - IonChannelProtein result = new IonChannelProtein(); - return result; - } - - @Test - public void testInvalid() { - try { - IonChannelProtein object = Mockito.mock(IonChannelProtein.class); - - comparator.compare(object, object); - - fail("Exception expected"); - } catch (NotImplementedException e) { - - } catch (Exception e) { - e.printStackTrace(); - fail("Unknowne exception occurred"); - } - } + comparator.compare(object, object); + } } diff --git a/model/src/test/java/lcsb/mapviewer/model/map/species/IonChannelProteinTest.java b/model/src/test/java/lcsb/mapviewer/model/map/species/IonChannelProteinTest.java index 1008ea19e523fa0a37afeab6faf367869fed3966..871c361273bd095577b9986e1c8c3185eec92562 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/species/IonChannelProteinTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/species/IonChannelProteinTest.java @@ -1,69 +1,45 @@ package lcsb.mapviewer.model.map.species; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.mockito.Mockito; +import lcsb.mapviewer.ModelTestFunctions; import lcsb.mapviewer.common.exception.NotImplementedException; -public class IonChannelProteinTest { - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testSerialization() { - try { - SerializationUtils.serialize(new IonChannelProtein()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testConstructor() { - try { - IonChannelProtein species = new IonChannelProtein(new IonChannelProtein()); - assertNotNull(species); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testCopy1() { - try { - IonChannelProtein species = new IonChannelProtein("id").copy(); - assertNotNull(species); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testCopy2() { - try { - IonChannelProtein protein = Mockito.spy(IonChannelProtein.class); - protein.copy(); - fail("Exception expected"); - } catch (NotImplementedException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } +public class IonChannelProteinTest extends ModelTestFunctions { + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testSerialization() { + SerializationUtils.serialize(new IonChannelProtein()); + } + + @Test + public void testConstructor() { + IonChannelProtein species = new IonChannelProtein(new IonChannelProtein()); + assertNotNull(species); + } + + @Test + public void testCopy1() { + IonChannelProtein species = new IonChannelProtein("id").copy(); + assertNotNull(species); + } + + @Test(expected = NotImplementedException.class) + public void testCopy2() { + IonChannelProtein protein = Mockito.spy(IonChannelProtein.class); + protein.copy(); + } } diff --git a/model/src/test/java/lcsb/mapviewer/model/map/species/IonComparatorTest.java b/model/src/test/java/lcsb/mapviewer/model/map/species/IonComparatorTest.java index ede0274d62189d43fdb336fe11f7c10beb01a7ed..9cf4a3d73f2445a295747661eba93853a6b58c3f 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/species/IonComparatorTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/species/IonComparatorTest.java @@ -1,83 +1,60 @@ package lcsb.mapviewer.model.map.species; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.mockito.Mockito; +import lcsb.mapviewer.ModelTestFunctions; import lcsb.mapviewer.common.exception.NotImplementedException; -public class IonComparatorTest { - - IonComparator comparator = new IonComparator(); - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testEquals() { - try { - Ion ion1 = createIon(); - Ion ion2 = createIon(); - - assertEquals(0, comparator.compare(ion1, ion1)); - - assertEquals(0, comparator.compare(ion1, ion2)); - assertEquals(0, comparator.compare(ion2, ion1)); - - } catch (Exception e) { - e.printStackTrace(); - fail("Ione exception occurred"); - } - } - - @Test - public void testDifferent() { - try { - Ion ion2 = createIon(); - assertTrue(comparator.compare(null, ion2) != 0); - assertTrue(comparator.compare(ion2, null) != 0); - assertTrue(comparator.compare(null, null) == 0); - - Ion ion = createIon(); - ion.setName("n"); - assertTrue(comparator.compare(ion, ion2) != 0); - - assertTrue(comparator.compare(ion, Mockito.mock(Ion.class)) != 0); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - public Ion createIon() { - Ion result = new Ion(); - return result; - } - - @Test - public void testInvalid() { - try { - Ion object = Mockito.mock(Ion.class); - - comparator.compare(object, object); - - fail("Exception expected"); - } catch (NotImplementedException e) { - - } catch (Exception e) { - e.printStackTrace(); - fail("Unknowne exception occurred"); - } - } +public class IonComparatorTest extends ModelTestFunctions { + + IonComparator comparator = new IonComparator(); + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testEquals() { + Ion ion1 = createIon(); + Ion ion2 = createIon(); + + assertEquals(0, comparator.compare(ion1, ion1)); + + assertEquals(0, comparator.compare(ion1, ion2)); + assertEquals(0, comparator.compare(ion2, ion1)); + } + + @Test + public void testDifferent() { + Ion ion2 = createIon(); + assertTrue(comparator.compare(null, ion2) != 0); + assertTrue(comparator.compare(ion2, null) != 0); + assertTrue(comparator.compare(null, null) == 0); + + Ion ion = createIon(); + ion.setName("n"); + assertTrue(comparator.compare(ion, ion2) != 0); + + assertTrue(comparator.compare(ion, Mockito.mock(Ion.class)) != 0); + } + + public Ion createIon() { + Ion result = new Ion(); + return result; + } + + @Test(expected = NotImplementedException.class) + public void testInvalid() { + Ion object = Mockito.mock(Ion.class); + + comparator.compare(object, object); + } } diff --git a/model/src/test/java/lcsb/mapviewer/model/map/species/IonTest.java b/model/src/test/java/lcsb/mapviewer/model/map/species/IonTest.java index 50c4174cd6d45f47ab3123a55ca6c567b8413727..7cf6596007f235dc5371596d64055acb2a1df2eb 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/species/IonTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/species/IonTest.java @@ -1,80 +1,51 @@ package lcsb.mapviewer.model.map.species; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.mockito.Mockito; +import lcsb.mapviewer.ModelTestFunctions; import lcsb.mapviewer.common.exception.NotImplementedException; -public class IonTest { - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testSerialization() { - try { - SerializationUtils.serialize(new Ion()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testConstructor1() { - try { - Ion degraded = new Ion(new Ion()); - assertNotNull(degraded); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testGetters() { - try { - Ion degraded = new Ion("id"); - assertNotNull(degraded.getStringType()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testCopy() { - try { - Ion degraded = new Ion().copy(); - assertNotNull(degraded); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testInvalidCopy() { - try { - Ion ion = Mockito.spy(Ion.class); - ion.copy(); - fail("Exception expected"); - } catch (NotImplementedException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } +public class IonTest extends ModelTestFunctions { + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testSerialization() { + SerializationUtils.serialize(new Ion()); + } + + @Test + public void testConstructor1() { + Ion degraded = new Ion(new Ion()); + assertNotNull(degraded); + } + + @Test + public void testGetters() { + Ion degraded = new Ion("id"); + assertNotNull(degraded.getStringType()); + } + + @Test + public void testCopy() { + Ion degraded = new Ion().copy(); + assertNotNull(degraded); + } + + @Test(expected = NotImplementedException.class) + public void testInvalidCopy() { + Ion ion = Mockito.spy(Ion.class); + ion.copy(); + } } diff --git a/model/src/test/java/lcsb/mapviewer/model/map/species/PhenotypeComparatorTest.java b/model/src/test/java/lcsb/mapviewer/model/map/species/PhenotypeComparatorTest.java index b97c9062786319b95bd243b511ab43c02b6623d8..fe9d66fe14ee46d52a882d6819114ecfb6869164 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/species/PhenotypeComparatorTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/species/PhenotypeComparatorTest.java @@ -1,86 +1,62 @@ package lcsb.mapviewer.model.map.species; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.mockito.Mockito; +import lcsb.mapviewer.ModelTestFunctions; import lcsb.mapviewer.common.exception.NotImplementedException; -public class PhenotypeComparatorTest { +public class PhenotypeComparatorTest extends ModelTestFunctions { - PhenotypeComparator comparator = new PhenotypeComparator(); + PhenotypeComparator comparator = new PhenotypeComparator(); - @Before - public void setUp() throws Exception { - } + @Before + public void setUp() throws Exception { + } - @After - public void tearDown() throws Exception { - } + @After + public void tearDown() throws Exception { + } - @Test - public void testEquals() { - try { - Phenotype phenotype1 = createPhenotype(); - Phenotype phenotype2 = createPhenotype(); + @Test + public void testEquals() { + Phenotype phenotype1 = createPhenotype(); + Phenotype phenotype2 = createPhenotype(); - assertEquals(0, comparator.compare(phenotype1, phenotype1)); + assertEquals(0, comparator.compare(phenotype1, phenotype1)); - assertEquals(0, comparator.compare(phenotype1, phenotype2)); - assertEquals(0, comparator.compare(phenotype2, phenotype1)); + assertEquals(0, comparator.compare(phenotype1, phenotype2)); + assertEquals(0, comparator.compare(phenotype2, phenotype1)); + } - } catch (Exception e) { - e.printStackTrace(); - fail("Unknowne exception occurred"); - } - } + @Test(expected = NotImplementedException.class) + public void testInvalid() { + Phenotype phenotype1 = Mockito.mock(Phenotype.class); - @Test - public void testInvalid() { - try { - Phenotype phenotype1 = Mockito.mock(Phenotype.class); + comparator.compare(phenotype1, phenotype1); + } - comparator.compare(phenotype1, phenotype1); + @Test + public void testDifferent() { + Phenotype phenotype2 = createPhenotype(); + assertTrue(comparator.compare(null, phenotype2) != 0); + assertTrue(comparator.compare(phenotype2, null) != 0); + assertTrue(comparator.compare(null, null) == 0); - fail("Exception expected"); - } catch (NotImplementedException e) { + assertTrue(comparator.compare(phenotype2, Mockito.mock(Phenotype.class)) != 0); - } catch (Exception e) { - e.printStackTrace(); - fail("Unknowne exception occurred"); - } - } + Phenotype phenotype = createPhenotype(); + phenotype2 = createPhenotype(); + phenotype.setName("n"); + assertTrue(comparator.compare(phenotype, phenotype2) != 0); + } - @Test - public void testDifferent() { - try { - Phenotype phenotype2 = createPhenotype(); - assertTrue(comparator.compare(null, phenotype2) != 0); - assertTrue(comparator.compare(phenotype2, null) != 0); - assertTrue(comparator.compare(null, null) == 0); + public Phenotype createPhenotype() { + Phenotype result = new Phenotype(); - assertTrue(comparator.compare(phenotype2, Mockito.mock(Phenotype.class)) != 0); - - Phenotype phenotype = createPhenotype(); - phenotype2 = createPhenotype(); - phenotype.setName("n"); - assertTrue(comparator.compare(phenotype, phenotype2) != 0); - - } catch (Exception e) { - e.printStackTrace(); - fail("Unknowne exception occurred"); - } - } - - public Phenotype createPhenotype() { - Phenotype result = new Phenotype(); - - return result; - } + return result; + } } diff --git a/model/src/test/java/lcsb/mapviewer/model/map/species/PhenotypeTest.java b/model/src/test/java/lcsb/mapviewer/model/map/species/PhenotypeTest.java index acfd986657132ca43f536a98a83a2077d5460b58..5b8535329dca4592f8e17b7c00236f4fc2e8c497 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/species/PhenotypeTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/species/PhenotypeTest.java @@ -1,94 +1,59 @@ package lcsb.mapviewer.model.map.species; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.mockito.Mockito; +import lcsb.mapviewer.ModelTestFunctions; import lcsb.mapviewer.common.exception.NotImplementedException; -public class PhenotypeTest { - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testSerialization() { - try { - SerializationUtils.serialize(new Phenotype()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testConstructor1() { - try { - Phenotype original = new Phenotype(); - Phenotype copy = new Phenotype(original); - assertNotNull(copy); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testConstructor2() { - try { - String id = "idd"; - Phenotype copy = new Phenotype(id); - assertEquals(id, copy.getElementId()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testGetters() { - try { - Phenotype copy = new Phenotype("id"); - assertNotNull(copy.getStringType()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testCopy() { - try { - Phenotype degraded = new Phenotype().copy(); - assertNotNull(degraded); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testInvalidCopy() { - try { - Phenotype phenotype = Mockito.spy(Phenotype.class); - phenotype.copy(); - fail("Exception expected"); - } catch (NotImplementedException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } +public class PhenotypeTest extends ModelTestFunctions { + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testSerialization() { + SerializationUtils.serialize(new Phenotype()); + } + + @Test + public void testConstructor1() { + Phenotype original = new Phenotype(); + Phenotype copy = new Phenotype(original); + assertNotNull(copy); + } + + @Test + public void testConstructor2() { + String id = "idd"; + Phenotype copy = new Phenotype(id); + assertEquals(id, copy.getElementId()); + } + + @Test + public void testGetters() { + Phenotype copy = new Phenotype("id"); + assertNotNull(copy.getStringType()); + } + + @Test + public void testCopy() { + Phenotype degraded = new Phenotype().copy(); + assertNotNull(degraded); + } + + @Test(expected = NotImplementedException.class) + public void testInvalidCopy() { + Phenotype phenotype = Mockito.spy(Phenotype.class); + phenotype.copy(); + } } diff --git a/model/src/test/java/lcsb/mapviewer/model/map/species/ProteinComparatorTest.java b/model/src/test/java/lcsb/mapviewer/model/map/species/ProteinComparatorTest.java index 2e44d0cfaaa747767d0bca9054c3e8cad113ba53..2307b594ad92ac833bd04a26038e42f0d718646b 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/species/ProteinComparatorTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/species/ProteinComparatorTest.java @@ -1,23 +1,21 @@ package lcsb.mapviewer.model.map.species; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import java.awt.geom.Point2D; -import org.apache.logging.log4j.*; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.junit.*; import org.mockito.Mockito; +import lcsb.mapviewer.ModelTestFunctions; import lcsb.mapviewer.common.exception.NotImplementedException; import lcsb.mapviewer.model.map.species.field.ModificationState; import lcsb.mapviewer.model.map.species.field.Residue; -public class ProteinComparatorTest { - Logger logger= LogManager.getLogger(ProteinComparatorTest.class); +public class ProteinComparatorTest extends ModelTestFunctions { + Logger logger = LogManager.getLogger(ProteinComparatorTest.class); ProteinComparator comparator = new ProteinComparator(); @@ -31,92 +29,71 @@ public class ProteinComparatorTest { @Test public void testEquals() { - try { - GenericProtein protein1 = createProtein(); - GenericProtein protein2 = createProtein(); + GenericProtein protein1 = createProtein(); + GenericProtein protein2 = createProtein(); - assertEquals(0, comparator.compare(protein1, protein1)); + assertEquals(0, comparator.compare(protein1, protein1)); - assertEquals(0, comparator.compare(protein1, protein2)); - assertEquals(0, comparator.compare(protein2, protein1)); + assertEquals(0, comparator.compare(protein1, protein2)); + assertEquals(0, comparator.compare(protein2, protein1)); - assertEquals(0, comparator.compare(null, null)); + assertEquals(0, comparator.compare(null, null)); - assertEquals(0, comparator.compare(new TruncatedProtein(), new TruncatedProtein())); - assertEquals(0, comparator.compare(new ReceptorProtein(), new ReceptorProtein())); - assertEquals(0, comparator.compare(new IonChannelProtein(), new IonChannelProtein())); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, comparator.compare(new TruncatedProtein(), new TruncatedProtein())); + assertEquals(0, comparator.compare(new ReceptorProtein(), new ReceptorProtein())); + assertEquals(0, comparator.compare(new IonChannelProtein(), new IonChannelProtein())); } - @Test + @Test(expected = NotImplementedException.class) public void testUnknownProteinImplementations() { - try { - Protein protein1 = Mockito.mock(Protein.class); - assertEquals(0, comparator.compare(protein1, protein1)); - - fail("Exception expected"); - - } catch (NotImplementedException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Protein protein1 = Mockito.mock(Protein.class); + assertEquals(0, comparator.compare(protein1, protein1)); } @Test public void testDifferent() { - try { - GenericProtein protein1 = createProtein(); - GenericProtein protein2 = createProtein(); - assertTrue(comparator.compare(null, protein2) != 0); - assertTrue(comparator.compare(protein2, null) != 0); - - protein1.getModificationResidues().get(0).setName("bla"); - assertTrue(comparator.compare(protein1, protein2) != 0); - assertTrue(comparator.compare(protein2, protein1) != 0); - - protein1 = createProtein(); - protein2 = createProtein(); - protein1.getModificationResidues().clear(); - assertTrue(comparator.compare(protein1, protein2) != 0); - assertTrue(comparator.compare(protein2, protein1) != 0); - - protein1 = createProtein(); - protein2 = createProtein(); - assertTrue(comparator.compare(null, protein2) != 0); - assertTrue(comparator.compare(protein2, null) != 0); - assertTrue(comparator.compare(null, null) == 0); - - assertTrue(comparator.compare(protein2, new GenericProtein()) != 0); - - protein1 = createProtein(); - protein2 = createProtein(); - protein1.setName("a"); - assertTrue(comparator.compare(protein1, protein2) != 0); - assertTrue(comparator.compare(protein2, protein1) != 0); - - protein1 = createProtein(); - protein2 = createProtein(); - protein1.setStructuralState("a"); - assertTrue(comparator.compare(protein1, protein2) != 0); - assertTrue(comparator.compare(protein2, protein1) != 0); - - protein1 = createProtein(); - protein2 = createProtein(); - protein1.setHomodimer(1); - assertTrue(comparator.compare(protein1, protein2) != 0); - assertTrue(comparator.compare(protein2, protein1) != 0); - - assertTrue(comparator.compare(new GenericProtein(), new TruncatedProtein()) != 0); - - } catch (Exception e) { - e.printStackTrace(); - fail("Unknowne exception occurred"); - } + GenericProtein protein1 = createProtein(); + GenericProtein protein2 = createProtein(); + assertTrue(comparator.compare(null, protein2) != 0); + assertTrue(comparator.compare(protein2, null) != 0); + + protein1.getModificationResidues().get(0).setName("bla"); + assertTrue(comparator.compare(protein1, protein2) != 0); + assertTrue(comparator.compare(protein2, protein1) != 0); + + protein1 = createProtein(); + protein2 = createProtein(); + protein1.getModificationResidues().clear(); + assertTrue(comparator.compare(protein1, protein2) != 0); + assertTrue(comparator.compare(protein2, protein1) != 0); + + protein1 = createProtein(); + protein2 = createProtein(); + assertTrue(comparator.compare(null, protein2) != 0); + assertTrue(comparator.compare(protein2, null) != 0); + assertTrue(comparator.compare(null, null) == 0); + + assertTrue(comparator.compare(protein2, new GenericProtein()) != 0); + + protein1 = createProtein(); + protein2 = createProtein(); + protein1.setName("a"); + assertTrue(comparator.compare(protein1, protein2) != 0); + assertTrue(comparator.compare(protein2, protein1) != 0); + + protein1 = createProtein(); + protein2 = createProtein(); + protein1.setStructuralState("a"); + assertTrue(comparator.compare(protein1, protein2) != 0); + assertTrue(comparator.compare(protein2, protein1) != 0); + + protein1 = createProtein(); + protein2 = createProtein(); + protein1.setHomodimer(1); + assertTrue(comparator.compare(protein1, protein2) != 0); + assertTrue(comparator.compare(protein2, protein1) != 0); + + assertTrue(comparator.compare(new GenericProtein(), new TruncatedProtein()) != 0); } public GenericProtein createProtein() { diff --git a/model/src/test/java/lcsb/mapviewer/model/map/species/ProteinTest.java b/model/src/test/java/lcsb/mapviewer/model/map/species/ProteinTest.java index 6485005ac77f0f3eeab4762ca8ebaec10ad0096b..af692fc075f0650c7186e36cc4fb028c5ab93c00 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/species/ProteinTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/species/ProteinTest.java @@ -1,23 +1,20 @@ package lcsb.mapviewer.model.map.species; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import java.util.ArrayList; import java.util.List; import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.mockito.Mockito; +import lcsb.mapviewer.ModelTestFunctions; import lcsb.mapviewer.common.exception.NotImplementedException; import lcsb.mapviewer.model.map.species.field.ModificationResidue; import lcsb.mapviewer.model.map.species.field.Residue; -public class ProteinTest { +public class ProteinTest extends ModelTestFunctions { @Before public void setUp() throws Exception { @@ -29,78 +26,46 @@ public class ProteinTest { @Test public void testSerialization() { - try { - SerializationUtils.serialize(new GenericProtein()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + SerializationUtils.serialize(new GenericProtein()); } @Test public void testConstructor1() { - try { - GenericProtein protein = new GenericProtein(); - protein.setStructuralState("srt"); - List<ModificationResidue> residues = new ArrayList<>(); - residues.add(new Residue()); - - protein.setModificationResidues(residues); - Protein protein2 = new GenericProtein(protein); - assertNotNull(protein2); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + GenericProtein protein = new GenericProtein(); + protein.setStructuralState("srt"); + List<ModificationResidue> residues = new ArrayList<>(); + residues.add(new Residue()); + + protein.setModificationResidues(residues); + Protein protein2 = new GenericProtein(protein); + assertNotNull(protein2); } @Test public void testSetStructuralState() { - try { - GenericProtein protein = new GenericProtein(); - protein.setStructuralState("str"); - protein.setStructuralState("str1"); - - assertEquals("str1", protein.getStructuralState()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + GenericProtein protein = new GenericProtein(); + protein.setStructuralState("str"); + protein.setStructuralState("str1"); + + assertEquals("str1", protein.getStructuralState()); } @Test public void testGetters() { - try { - GenericProtein protein = new GenericProtein("id"); - assertNotNull(protein.getStringType()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + GenericProtein protein = new GenericProtein("id"); + assertNotNull(protein.getStringType()); } @Test public void testCopy() { - try { - GenericProtein protein = new GenericProtein().copy(); - assertNotNull(protein); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + GenericProtein protein = new GenericProtein().copy(); + assertNotNull(protein); } - @Test + @Test(expected = NotImplementedException.class) public void testInvalidCopy() { - try { - GenericProtein mock = Mockito.spy(GenericProtein.class); - mock.copy(); - fail("Exception expected"); - } catch (NotImplementedException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + GenericProtein mock = Mockito.spy(GenericProtein.class); + mock.copy(); } } diff --git a/model/src/test/java/lcsb/mapviewer/model/map/species/ReceptorProteinComparatorTest.java b/model/src/test/java/lcsb/mapviewer/model/map/species/ReceptorProteinComparatorTest.java index f5906304ec69c1f253b4aa27ab20d0ef1be1a2dc..74bc63f06c5c745c72130d0c66284982e464ad26 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/species/ReceptorProteinComparatorTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/species/ReceptorProteinComparatorTest.java @@ -1,84 +1,60 @@ package lcsb.mapviewer.model.map.species; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.mockito.Mockito; +import lcsb.mapviewer.ModelTestFunctions; import lcsb.mapviewer.common.exception.NotImplementedException; -public class ReceptorProteinComparatorTest { +public class ReceptorProteinComparatorTest extends ModelTestFunctions { - ReceptorProteinComparator comparator = new ReceptorProteinComparator(); + ReceptorProteinComparator comparator = new ReceptorProteinComparator(); - @Before - public void setUp() throws Exception { - } + @Before + public void setUp() throws Exception { + } - @After - public void tearDown() throws Exception { - } + @After + public void tearDown() throws Exception { + } - @Test - public void testEquals() { - try { - ReceptorProtein drug1 = createReceptorProtein(); - ReceptorProtein drug2 = createReceptorProtein(); + @Test + public void testEquals() { + ReceptorProtein drug1 = createReceptorProtein(); + ReceptorProtein drug2 = createReceptorProtein(); - assertEquals(0, comparator.compare(drug1, drug1)); + assertEquals(0, comparator.compare(drug1, drug1)); - assertEquals(0, comparator.compare(drug1, drug2)); - assertEquals(0, comparator.compare(drug2, drug1)); + assertEquals(0, comparator.compare(drug1, drug2)); + assertEquals(0, comparator.compare(drug2, drug1)); + } - } catch (Exception e) { - e.printStackTrace(); - fail("Unknowne exception occurred"); - } - } + @Test + public void testDifferent() { + ReceptorProtein drug2 = createReceptorProtein(); + assertTrue(comparator.compare(null, drug2) != 0); + assertTrue(comparator.compare(drug2, null) != 0); + assertTrue(comparator.compare(null, null) == 0); - @Test - public void testDifferent() { - try { - ReceptorProtein drug2 = createReceptorProtein(); - assertTrue(comparator.compare(null, drug2) != 0); - assertTrue(comparator.compare(drug2, null) != 0); - assertTrue(comparator.compare(null, null) == 0); + ReceptorProtein drug = createReceptorProtein(); + drug.setName("n"); + assertTrue(comparator.compare(drug, drug2) != 0); - ReceptorProtein drug = createReceptorProtein(); - drug.setName("n"); - assertTrue(comparator.compare(drug, drug2) != 0); + assertTrue(comparator.compare(drug, Mockito.mock(ReceptorProtein.class)) != 0); + } - assertTrue(comparator.compare(drug, Mockito.mock(ReceptorProtein.class)) != 0); + public ReceptorProtein createReceptorProtein() { + ReceptorProtein result = new ReceptorProtein(); + return result; + } - } catch (Exception e) { - e.printStackTrace(); - fail("Unknowne exception occurred"); - } - } + @Test(expected = NotImplementedException.class) + public void testInvalid() { + ReceptorProtein object = Mockito.mock(ReceptorProtein.class); - public ReceptorProtein createReceptorProtein() { - ReceptorProtein result = new ReceptorProtein(); - return result; - } - - @Test - public void testInvalid() { - try { - ReceptorProtein object = Mockito.mock(ReceptorProtein.class); - - comparator.compare(object, object); - - fail("Exception expected"); - } catch (NotImplementedException e) { - - } catch (Exception e) { - e.printStackTrace(); - fail("Unknowne exception occurred"); - } - } + comparator.compare(object, object); + } } diff --git a/model/src/test/java/lcsb/mapviewer/model/map/species/ReceptorProteinTest.java b/model/src/test/java/lcsb/mapviewer/model/map/species/ReceptorProteinTest.java index a220ae88ca3c7ceac5991431fcb457f2ffede338..52977e3d1b5bb9b7adb726367bfa51618e39bf6a 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/species/ReceptorProteinTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/species/ReceptorProteinTest.java @@ -1,69 +1,45 @@ package lcsb.mapviewer.model.map.species; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.mockito.Mockito; +import lcsb.mapviewer.ModelTestFunctions; import lcsb.mapviewer.common.exception.NotImplementedException; -public class ReceptorProteinTest { - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testSerialization() { - try { - SerializationUtils.serialize(new ReceptorProtein()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testConstructor() { - try { - ReceptorProtein species = new ReceptorProtein(new ReceptorProtein()); - assertNotNull(species); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testCopy1() { - try { - ReceptorProtein species = new ReceptorProtein("id").copy(); - assertNotNull(species); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testCopy2() { - try { - ReceptorProtein protein = Mockito.spy(ReceptorProtein.class); - protein.copy(); - fail("Exception expected"); - } catch (NotImplementedException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } +public class ReceptorProteinTest extends ModelTestFunctions { + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testSerialization() { + SerializationUtils.serialize(new ReceptorProtein()); + } + + @Test + public void testConstructor() { + ReceptorProtein species = new ReceptorProtein(new ReceptorProtein()); + assertNotNull(species); + } + + @Test + public void testCopy1() { + ReceptorProtein species = new ReceptorProtein("id").copy(); + assertNotNull(species); + } + + @Test(expected = NotImplementedException.class) + public void testCopy2() { + ReceptorProtein protein = Mockito.spy(ReceptorProtein.class); + protein.copy(); + } } diff --git a/model/src/test/java/lcsb/mapviewer/model/map/species/RnaComparatorTest.java b/model/src/test/java/lcsb/mapviewer/model/map/species/RnaComparatorTest.java index f99156d913a2a5756672c1812cfb4505457773c2..7d5209461f70ccbda658e47ec9649bb214ca2a1b 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/species/RnaComparatorTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/species/RnaComparatorTest.java @@ -1,20 +1,17 @@ package lcsb.mapviewer.model.map.species; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import java.awt.geom.Point2D; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.mockito.Mockito; +import lcsb.mapviewer.ModelTestFunctions; import lcsb.mapviewer.common.exception.NotImplementedException; import lcsb.mapviewer.model.map.species.field.CodingRegion; -public class RnaComparatorTest { +public class RnaComparatorTest extends ModelTestFunctions { RnaComparator comparator = new RnaComparator(); @@ -28,52 +25,40 @@ public class RnaComparatorTest { @Test public void testEquals() { - try { - Rna aRna1 = createRna(); - Rna aRna2 = createRna(); + Rna aRna1 = createRna(); + Rna aRna2 = createRna(); - assertEquals(0, comparator.compare(aRna1, aRna1)); + assertEquals(0, comparator.compare(aRna1, aRna1)); - assertEquals(0, comparator.compare(aRna1, aRna2)); - assertEquals(0, comparator.compare(aRna2, aRna1)); - - } catch (Exception e) { - e.printStackTrace(); - fail("Unknowne exception occurred"); - } + assertEquals(0, comparator.compare(aRna1, aRna2)); + assertEquals(0, comparator.compare(aRna2, aRna1)); } @Test public void testDifferent() { - try { - Rna aRna1 = createRna(); - Rna aRna2 = createRna(); - aRna1.getRegions().get(0).setName("X"); - assertTrue(comparator.compare(aRna1, aRna2) != 0); - assertTrue(comparator.compare(aRna2, aRna1) != 0); - - aRna1 = createRna(); - aRna2 = createRna(); - aRna1.getRegions().clear(); - assertTrue(comparator.compare(aRna1, aRna2) != 0); - assertTrue(comparator.compare(aRna2, aRna1) != 0); - - aRna1 = createRna(); - aRna2 = createRna(); - assertTrue(comparator.compare(null, aRna2) != 0); - assertTrue(comparator.compare(aRna2, null) != 0); - assertTrue(comparator.compare(null, null) == 0); - - Rna rna = createRna(); - rna.setName("n"); - assertTrue(comparator.compare(rna, aRna2) != 0); - - assertTrue(comparator.compare(rna, Mockito.mock(Rna.class)) != 0); - - } catch (Exception e) { - e.printStackTrace(); - fail("Unknowne exception occurred"); - } + Rna aRna1 = createRna(); + Rna aRna2 = createRna(); + aRna1.getRegions().get(0).setName("X"); + assertTrue(comparator.compare(aRna1, aRna2) != 0); + assertTrue(comparator.compare(aRna2, aRna1) != 0); + + aRna1 = createRna(); + aRna2 = createRna(); + aRna1.getRegions().clear(); + assertTrue(comparator.compare(aRna1, aRna2) != 0); + assertTrue(comparator.compare(aRna2, aRna1) != 0); + + aRna1 = createRna(); + aRna2 = createRna(); + assertTrue(comparator.compare(null, aRna2) != 0); + assertTrue(comparator.compare(aRna2, null) != 0); + assertTrue(comparator.compare(null, null) == 0); + + Rna rna = createRna(); + rna.setName("n"); + assertTrue(comparator.compare(rna, aRna2) != 0); + + assertTrue(comparator.compare(rna, Mockito.mock(Rna.class)) != 0); } public Rna createRna() { @@ -88,20 +73,11 @@ public class RnaComparatorTest { return result; } - @Test + @Test(expected=NotImplementedException.class) public void testInvalid() { - try { - Rna object = Mockito.mock(Rna.class); - - comparator.compare(object, object); - - fail("Exception expected"); - } catch (NotImplementedException e) { + Rna object = Mockito.mock(Rna.class); - } catch (Exception e) { - e.printStackTrace(); - fail("Unknowne exception occurred"); - } + comparator.compare(object, object); } } diff --git a/model/src/test/java/lcsb/mapviewer/model/map/species/RnaTest.java b/model/src/test/java/lcsb/mapviewer/model/map/species/RnaTest.java index 88cb9f2ce62276c24f4c5b70b792e8d90496ad8a..2d742662d265b480eb90c2712630550391261d00 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/species/RnaTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/species/RnaTest.java @@ -1,17 +1,14 @@ package lcsb.mapviewer.model.map.species; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import java.util.ArrayList; import java.util.List; import org.apache.commons.lang3.SerializationUtils; -import org.apache.logging.log4j.*; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.junit.*; import org.mockito.Mockito; import lcsb.mapviewer.common.exception.NotImplementedException; @@ -31,76 +28,44 @@ public class RnaTest { @Test public void testSerialization() { - try { - SerializationUtils.serialize(new Rna()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + SerializationUtils.serialize(new Rna()); } @Test public void testConstructor1() { - try { - Rna rna = new Rna("d"); - assertNotNull(rna); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Rna rna = new Rna("d"); + assertNotNull(rna); } @Test public void testConstructor() { - try { - Rna rna = new Rna("d"); - rna.addCodingRegion(new CodingRegion()); - Rna rna2 = new Rna(rna); - assertEquals(rna.getRegions().size(), rna2.getRegions().size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Rna rna = new Rna("d"); + rna.addCodingRegion(new CodingRegion()); + Rna rna2 = new Rna(rna); + assertEquals(rna.getRegions().size(), rna2.getRegions().size()); } @Test public void testGetters() { - try { - Rna rna = new Rna(new Rna()); - assertNotNull(rna.getStringType()); - List<ModificationResidue> regions = new ArrayList<>(); - - rna.setRegions(regions); - - assertEquals(regions, rna.getRegions()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Rna rna = new Rna(new Rna()); + assertNotNull(rna.getStringType()); + List<ModificationResidue> regions = new ArrayList<>(); + + rna.setRegions(regions); + + assertEquals(regions, rna.getRegions()); } @Test public void testCopy() { - try { - Rna rna = new Rna().copy(); - assertNotNull(rna); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Rna rna = new Rna().copy(); + assertNotNull(rna); } - @Test + @Test(expected = NotImplementedException.class) public void testInvalidCopy() { - try { - Rna object = Mockito.spy(Rna.class); - object.copy(); - fail("Exception expected"); - } catch (NotImplementedException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Rna object = Mockito.spy(Rna.class); + object.copy(); } } diff --git a/model/src/test/java/lcsb/mapviewer/model/map/species/SimpleMoleculeComparatorTest.java b/model/src/test/java/lcsb/mapviewer/model/map/species/SimpleMoleculeComparatorTest.java index 12f76121917c5d23bf64e09991bb0380df6e9633..06b77a459a0066b6b6d0a99db963c99cb44e3b54 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/species/SimpleMoleculeComparatorTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/species/SimpleMoleculeComparatorTest.java @@ -1,121 +1,93 @@ package lcsb.mapviewer.model.map.species; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.mockito.Mockito; +import lcsb.mapviewer.ModelTestFunctions; import lcsb.mapviewer.common.exception.NotImplementedException; -public class SimpleMoleculeComparatorTest { - - SimpleMoleculeComparator comparator = new SimpleMoleculeComparator(); - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testEquals() { - try { - SimpleMolecule simpleMolecule1 = createSimpleMolecule(); - SimpleMolecule simpleMolecule2 = createSimpleMolecule(); - - assertEquals(0, comparator.compare(simpleMolecule1, simpleMolecule1)); - - assertEquals(0, comparator.compare(simpleMolecule1, simpleMolecule2)); - assertEquals(0, comparator.compare(simpleMolecule2, simpleMolecule1)); - - } catch (Exception e) { - e.printStackTrace(); - fail("Unknowne exception occurred"); - } - } - - @Test - public void testDifferent() { - try { - SimpleMolecule simpleMolecule1 = createSimpleMolecule(); - SimpleMolecule simpleMolecule2 = createSimpleMolecule(); - simpleMolecule1.setHomodimer(3); - assertTrue(comparator.compare(simpleMolecule1, simpleMolecule2) != 0); - assertTrue(comparator.compare(simpleMolecule2, simpleMolecule1) != 0); - - simpleMolecule1 = createSimpleMolecule(); - simpleMolecule2 = createSimpleMolecule(); - simpleMolecule1.setName("as"); - assertTrue(comparator.compare(simpleMolecule1, simpleMolecule2) != 0); - assertTrue(comparator.compare(simpleMolecule2, simpleMolecule1) != 0); - - simpleMolecule1 = createSimpleMolecule(); - simpleMolecule2 = createSimpleMolecule(); - simpleMolecule1.setInChIKey("as"); - assertTrue(comparator.compare(simpleMolecule1, simpleMolecule2) != 0); - assertTrue(comparator.compare(simpleMolecule2, simpleMolecule1) != 0); - - simpleMolecule1 = createSimpleMolecule(); - simpleMolecule2 = createSimpleMolecule(); - assertTrue(comparator.compare(null, simpleMolecule2) != 0); - assertTrue(comparator.compare(simpleMolecule2, null) != 0); - assertTrue(comparator.compare(null, null) == 0); - - assertTrue(comparator.compare(simpleMolecule1, Mockito.mock(SimpleMolecule.class)) != 0); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testInvalid() { - try { - SimpleMolecule simpleMolecule1 = Mockito.mock(SimpleMolecule.class); - comparator.compare(simpleMolecule1, simpleMolecule1); - fail("Exception expected"); - } catch (NotImplementedException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testDifferentNewFields() throws Exception { - try { - SimpleMolecule species1 = createSimpleMolecule(); - SimpleMolecule species2 = createSimpleMolecule(); - - species1.setSmiles("some symbol"); - assertTrue(comparator.compare(species1, species2) != 0); - assertTrue(comparator.compare(species2, species1) != 0); - - species1 = createSimpleMolecule(); - species2 = createSimpleMolecule(); - - species1.setInChI("some inchi"); - assertTrue(comparator.compare(species1, species2) != 0); - assertTrue(comparator.compare(species2, species1) != 0); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - public SimpleMolecule createSimpleMolecule() { - SimpleMolecule result = new SimpleMolecule(); - result.setHomodimer(12); - - return result; - } +public class SimpleMoleculeComparatorTest extends ModelTestFunctions { + + SimpleMoleculeComparator comparator = new SimpleMoleculeComparator(); + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testEquals() { + SimpleMolecule simpleMolecule1 = createSimpleMolecule(); + SimpleMolecule simpleMolecule2 = createSimpleMolecule(); + + assertEquals(0, comparator.compare(simpleMolecule1, simpleMolecule1)); + + assertEquals(0, comparator.compare(simpleMolecule1, simpleMolecule2)); + assertEquals(0, comparator.compare(simpleMolecule2, simpleMolecule1)); + } + + @Test + public void testDifferent() { + SimpleMolecule simpleMolecule1 = createSimpleMolecule(); + SimpleMolecule simpleMolecule2 = createSimpleMolecule(); + simpleMolecule1.setHomodimer(3); + assertTrue(comparator.compare(simpleMolecule1, simpleMolecule2) != 0); + assertTrue(comparator.compare(simpleMolecule2, simpleMolecule1) != 0); + + simpleMolecule1 = createSimpleMolecule(); + simpleMolecule2 = createSimpleMolecule(); + simpleMolecule1.setName("as"); + assertTrue(comparator.compare(simpleMolecule1, simpleMolecule2) != 0); + assertTrue(comparator.compare(simpleMolecule2, simpleMolecule1) != 0); + + simpleMolecule1 = createSimpleMolecule(); + simpleMolecule2 = createSimpleMolecule(); + simpleMolecule1.setInChIKey("as"); + assertTrue(comparator.compare(simpleMolecule1, simpleMolecule2) != 0); + assertTrue(comparator.compare(simpleMolecule2, simpleMolecule1) != 0); + + simpleMolecule1 = createSimpleMolecule(); + simpleMolecule2 = createSimpleMolecule(); + assertTrue(comparator.compare(null, simpleMolecule2) != 0); + assertTrue(comparator.compare(simpleMolecule2, null) != 0); + assertTrue(comparator.compare(null, null) == 0); + + assertTrue(comparator.compare(simpleMolecule1, Mockito.mock(SimpleMolecule.class)) != 0); + } + + @Test(expected = NotImplementedException.class) + public void testInvalid() { + SimpleMolecule simpleMolecule1 = Mockito.mock(SimpleMolecule.class); + comparator.compare(simpleMolecule1, simpleMolecule1); + } + + @Test + public void testDifferentNewFields() throws Exception { + SimpleMolecule species1 = createSimpleMolecule(); + SimpleMolecule species2 = createSimpleMolecule(); + + species1.setSmiles("some symbol"); + assertTrue(comparator.compare(species1, species2) != 0); + assertTrue(comparator.compare(species2, species1) != 0); + + species1 = createSimpleMolecule(); + species2 = createSimpleMolecule(); + + species1.setInChI("some inchi"); + assertTrue(comparator.compare(species1, species2) != 0); + assertTrue(comparator.compare(species2, species1) != 0); + } + + public SimpleMolecule createSimpleMolecule() { + SimpleMolecule result = new SimpleMolecule(); + result.setHomodimer(12); + + return result; + } } diff --git a/model/src/test/java/lcsb/mapviewer/model/map/species/SimpleMoleculeTest.java b/model/src/test/java/lcsb/mapviewer/model/map/species/SimpleMoleculeTest.java index e238e10b506674b50d11a0050c0e90b94aa655bf..6d88a38983633bea2e6b831b3eafe9b39617fb37 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/species/SimpleMoleculeTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/species/SimpleMoleculeTest.java @@ -1,80 +1,51 @@ package lcsb.mapviewer.model.map.species; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.mockito.Mockito; +import lcsb.mapviewer.ModelTestFunctions; import lcsb.mapviewer.common.exception.NotImplementedException; -public class SimpleMoleculeTest { - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testSerialization() { - try { - SerializationUtils.serialize(new SimpleMolecule()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testConstructor1() { - try { - SimpleMolecule degraded = new SimpleMolecule("id"); - assertNotNull(degraded); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testGetters() { - try { - SimpleMolecule degraded = new SimpleMolecule(new SimpleMolecule()); - assertNotNull(degraded.getStringType()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testCopy() { - try { - SimpleMolecule degraded = new SimpleMolecule().copy(); - assertNotNull(degraded); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testInvalidCopy() { - try { - SimpleMolecule simpleMolecule = Mockito.spy(SimpleMolecule.class); - simpleMolecule.copy(); - fail("Exception expected"); - } catch (NotImplementedException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } +public class SimpleMoleculeTest extends ModelTestFunctions { + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testSerialization() { + SerializationUtils.serialize(new SimpleMolecule()); + } + + @Test + public void testConstructor1() { + SimpleMolecule degraded = new SimpleMolecule("id"); + assertNotNull(degraded); + } + + @Test + public void testGetters() { + SimpleMolecule degraded = new SimpleMolecule(new SimpleMolecule()); + assertNotNull(degraded.getStringType()); + } + + @Test + public void testCopy() { + SimpleMolecule degraded = new SimpleMolecule().copy(); + assertNotNull(degraded); + } + + @Test(expected = NotImplementedException.class) + public void testInvalidCopy() { + SimpleMolecule simpleMolecule = Mockito.spy(SimpleMolecule.class); + simpleMolecule.copy(); + } } diff --git a/model/src/test/java/lcsb/mapviewer/model/map/species/SpeciesComparatorTest.java b/model/src/test/java/lcsb/mapviewer/model/map/species/SpeciesComparatorTest.java index 898e00b37ad865e6cf91bc728ef34f661de8a79a..7751e2b5fdf86db791f4266d6721da6d2951b5b2 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/species/SpeciesComparatorTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/species/SpeciesComparatorTest.java @@ -1,24 +1,19 @@ package lcsb.mapviewer.model.map.species; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import java.awt.Color; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.mockito.Mockito; +import lcsb.mapviewer.ModelTestFunctions; import lcsb.mapviewer.common.exception.NotImplementedException; -import lcsb.mapviewer.model.map.MiriamData; -import lcsb.mapviewer.model.map.MiriamRelationType; -import lcsb.mapviewer.model.map.MiriamType; +import lcsb.mapviewer.model.map.*; import lcsb.mapviewer.model.map.kinetics.SbmlUnitType; import lcsb.mapviewer.model.map.species.field.PositionToCompartment; -public class SpeciesComparatorTest { +public class SpeciesComparatorTest extends ModelTestFunctions { SpeciesComparator comparator = new SpeciesComparator(); @@ -32,35 +27,20 @@ public class SpeciesComparatorTest { @Test public void testEquals() { - try { - Species species1 = createSpecies(); - Species species2 = createSpecies(); + Species species1 = createSpecies(); + Species species2 = createSpecies(); - assertEquals(0, comparator.compare(species1, species2)); + assertEquals(0, comparator.compare(species1, species2)); - assertEquals(0, comparator.compare(null, null)); + assertEquals(0, comparator.compare(null, null)); - assertEquals(0, comparator.compare(new Complex(), new Complex())); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, comparator.compare(new Complex(), new Complex())); } - @Test + @Test(expected = NotImplementedException.class) public void testCompareInvalid() { - try { - - Species speciesMock = Mockito.mock(Species.class); - comparator.compare(speciesMock, speciesMock); - fail("Exception expected"); - - } catch (NotImplementedException e) { - } catch (Exception e) { - e.printStackTrace(); - fail("Unkowne exception"); - } + Species speciesMock = Mockito.mock(Species.class); + comparator.compare(speciesMock, speciesMock); } private Species createSpecies() { @@ -83,191 +63,164 @@ public class SpeciesComparatorTest { @Test public void testDifferent() throws Exception { - try { - Species species1 = createSpecies(); - Species species2 = createSpecies(); + Species species1 = createSpecies(); + Species species2 = createSpecies(); - assertTrue(comparator.compare(species1, null) != 0); - assertTrue(comparator.compare(null, species1) != 0); + assertTrue(comparator.compare(species1, null) != 0); + assertTrue(comparator.compare(null, species1) != 0); - assertTrue(comparator.compare(new Complex(), species1) != 0); + assertTrue(comparator.compare(new Complex(), species1) != 0); - species1 = createSpecies(); - species2 = createSpecies(); + species1 = createSpecies(); + species2 = createSpecies(); - species1.setElementId("tmp"); + species1.setElementId("tmp"); - assertTrue(comparator.compare(species1, species2) != 0); - assertTrue(comparator.compare(species2, species1) != 0); + assertTrue(comparator.compare(species1, species2) != 0); + assertTrue(comparator.compare(species2, species1) != 0); - species1 = createSpecies(); - species2 = createSpecies(); + species1 = createSpecies(); + species2 = createSpecies(); - species1.setStateLabel("tmp"); + species1.setStateLabel("tmp"); - assertTrue(comparator.compare(species1, species2) != 0); - assertTrue(comparator.compare(species2, species1) != 0); + assertTrue(comparator.compare(species1, species2) != 0); + assertTrue(comparator.compare(species2, species1) != 0); - species1 = createSpecies(); - species2 = createSpecies(); + species1 = createSpecies(); + species2 = createSpecies(); - species1.setStatePrefix("tmp"); + species1.setStatePrefix("tmp"); - assertTrue(comparator.compare(species1, species2) != 0); - assertTrue(comparator.compare(species2, species1) != 0); + assertTrue(comparator.compare(species1, species2) != 0); + assertTrue(comparator.compare(species2, species1) != 0); - species1 = createSpecies(); - species2 = createSpecies(); + species1 = createSpecies(); + species2 = createSpecies(); - species1.setName("new namne"); + species1.setName("new namne"); - assertTrue(comparator.compare(species1, species2) != 0); - assertTrue(comparator.compare(species2, species1) != 0); + assertTrue(comparator.compare(species1, species2) != 0); + assertTrue(comparator.compare(species2, species1) != 0); - species1 = createSpecies(); - species2 = createSpecies(); + species1 = createSpecies(); + species2 = createSpecies(); - species1.setActivity(true); + species1.setActivity(true); - assertTrue(comparator.compare(species1, species2) != 0); - assertTrue(comparator.compare(species2, species1) != 0); + assertTrue(comparator.compare(species1, species2) != 0); + assertTrue(comparator.compare(species2, species1) != 0); - species1 = createSpecies(); - species2 = createSpecies(); + species1 = createSpecies(); + species2 = createSpecies(); - species1.setLineWidth(453.75); + species1.setLineWidth(453.75); - assertTrue(comparator.compare(species1, species2) != 0); - assertTrue(comparator.compare(species2, species1) != 0); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertTrue(comparator.compare(species1, species2) != 0); + assertTrue(comparator.compare(species2, species1) != 0); } - @Test + @Test(expected=NotImplementedException.class) public void testException() { - try { - Species mock = Mockito.mock(Species.class); - comparator.compare(mock, mock); - - fail("Exception expected"); - } catch (NotImplementedException e) { - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Species mock = Mockito.mock(Species.class); + comparator.compare(mock, mock); } @Test public void testEquals2() { - try { - SimpleMolecule species1 = createSimpleMolecule(); - SimpleMolecule species2 = createSimpleMolecule(); - assertEquals(0, comparator.compare(species1, species2)); - - assertEquals(0, comparator.compare(null, null)); - - assertEquals(0, comparator.compare(new AntisenseRna(), new AntisenseRna())); - assertEquals(0, comparator.compare(new Degraded(), new Degraded())); - assertEquals(0, comparator.compare(new Drug(), new Drug())); - assertEquals(0, comparator.compare(new Ion(), new Ion())); - assertEquals(0, comparator.compare(new Phenotype(), new Phenotype())); - assertEquals(0, comparator.compare(new Rna(), new Rna())); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + SimpleMolecule species1 = createSimpleMolecule(); + SimpleMolecule species2 = createSimpleMolecule(); + assertEquals(0, comparator.compare(species1, species2)); + + assertEquals(0, comparator.compare(null, null)); + + assertEquals(0, comparator.compare(new AntisenseRna(), new AntisenseRna())); + assertEquals(0, comparator.compare(new Degraded(), new Degraded())); + assertEquals(0, comparator.compare(new Drug(), new Drug())); + assertEquals(0, comparator.compare(new Ion(), new Ion())); + assertEquals(0, comparator.compare(new Phenotype(), new Phenotype())); + assertEquals(0, comparator.compare(new Rna(), new Rna())); } @Test public void testDifferent2() { - try { - SimpleMolecule species1 = createSimpleMolecule(); - SimpleMolecule species2 = createSimpleMolecule(); - - species1.setCharge(99); - assertTrue(comparator.compare(species1, species2) != 0); - assertTrue(comparator.compare(species2, species1) != 0); - assertTrue(comparator.compare(null, species1) != 0); - assertTrue(comparator.compare(species1, null) != 0); - - species1 = createSimpleMolecule(); - species2 = createSimpleMolecule(); - species1.setHomodimer(1233); - assertTrue(comparator.compare(species1, species2) != 0); - assertTrue(comparator.compare(species2, species1) != 0); - - species1 = createSimpleMolecule(); - species2 = createSimpleMolecule(); - species1.setElementId(""); - species1.setElementId("ASD"); - assertTrue(comparator.compare(species1, species2) != 0); - assertTrue(comparator.compare(species2, species1) != 0); - - species1 = createSimpleMolecule(); - species2 = createSimpleMolecule(); - species1.setNotes("ASD"); - assertTrue(comparator.compare(species1, species2) != 0); - assertTrue(comparator.compare(species2, species1) != 0); - - species1 = createSimpleMolecule(); - species2 = createSimpleMolecule(); - species1.setPositionToCompartment(PositionToCompartment.TRANSMEMBRANE); - assertTrue(comparator.compare(species1, species2) != 0); - assertTrue(comparator.compare(species2, species1) != 0); - - species1 = createSimpleMolecule(); - species2 = createSimpleMolecule(); - species1.getMiriamData().clear(); - assertTrue(comparator.compare(species1, species2) != 0); - assertTrue(comparator.compare(species2, species1) != 0); - - species1 = createSimpleMolecule(); - species2 = createSimpleMolecule(); - species1.setInitialAmount(4.0); - assertTrue(comparator.compare(species1, species2) != 0); - assertTrue(comparator.compare(species2, species1) != 0); - - species1 = createSimpleMolecule(); - species2 = createSimpleMolecule(); - species1.setInitialConcentration(4.0); - assertTrue(comparator.compare(species1, species2) != 0); - assertTrue(comparator.compare(species2, species1) != 0); - - species1 = createSimpleMolecule(); - species2 = createSimpleMolecule(); - species1.setOnlySubstanceUnits(false); - assertTrue(comparator.compare(species1, species2) != 0); - assertTrue(comparator.compare(species2, species1) != 0); - - species1 = createSimpleMolecule(); - species2 = createSimpleMolecule(); - species1.setHypothetical(true); - assertTrue(comparator.compare(species1, species2) != 0); - assertTrue(comparator.compare(species2, species1) != 0); - - species1 = createSimpleMolecule(); - species2 = createSimpleMolecule(); - species1.getMiriamData().iterator().next().setRelationType(MiriamRelationType.BQ_BIOL_IS); - assertTrue(comparator.compare(species1, species2) != 0); - assertTrue(comparator.compare(species2, species1) != 0); - - species1 = createSimpleMolecule(); - species2 = createSimpleMolecule(); - species1.addMiriamData(new MiriamData()); - assertTrue(comparator.compare(species1, species2) != 0); - assertTrue(comparator.compare(species2, species1) != 0); - - assertTrue(comparator.compare(new Rna(), new Drug()) != 0); - - } catch (Exception e) { - e.printStackTrace(); - fail("Unkowne exception"); - } + SimpleMolecule species1 = createSimpleMolecule(); + SimpleMolecule species2 = createSimpleMolecule(); + + species1.setCharge(99); + assertTrue(comparator.compare(species1, species2) != 0); + assertTrue(comparator.compare(species2, species1) != 0); + assertTrue(comparator.compare(null, species1) != 0); + assertTrue(comparator.compare(species1, null) != 0); + + species1 = createSimpleMolecule(); + species2 = createSimpleMolecule(); + species1.setHomodimer(1233); + assertTrue(comparator.compare(species1, species2) != 0); + assertTrue(comparator.compare(species2, species1) != 0); + + species1 = createSimpleMolecule(); + species2 = createSimpleMolecule(); + species1.setElementId(""); + species1.setElementId("ASD"); + assertTrue(comparator.compare(species1, species2) != 0); + assertTrue(comparator.compare(species2, species1) != 0); + + species1 = createSimpleMolecule(); + species2 = createSimpleMolecule(); + species1.setNotes("ASD"); + assertTrue(comparator.compare(species1, species2) != 0); + assertTrue(comparator.compare(species2, species1) != 0); + + species1 = createSimpleMolecule(); + species2 = createSimpleMolecule(); + species1.setPositionToCompartment(PositionToCompartment.TRANSMEMBRANE); + assertTrue(comparator.compare(species1, species2) != 0); + assertTrue(comparator.compare(species2, species1) != 0); + + species1 = createSimpleMolecule(); + species2 = createSimpleMolecule(); + species1.getMiriamData().clear(); + assertTrue(comparator.compare(species1, species2) != 0); + assertTrue(comparator.compare(species2, species1) != 0); + + species1 = createSimpleMolecule(); + species2 = createSimpleMolecule(); + species1.setInitialAmount(4.0); + assertTrue(comparator.compare(species1, species2) != 0); + assertTrue(comparator.compare(species2, species1) != 0); + + species1 = createSimpleMolecule(); + species2 = createSimpleMolecule(); + species1.setInitialConcentration(4.0); + assertTrue(comparator.compare(species1, species2) != 0); + assertTrue(comparator.compare(species2, species1) != 0); + + species1 = createSimpleMolecule(); + species2 = createSimpleMolecule(); + species1.setOnlySubstanceUnits(false); + assertTrue(comparator.compare(species1, species2) != 0); + assertTrue(comparator.compare(species2, species1) != 0); + + species1 = createSimpleMolecule(); + species2 = createSimpleMolecule(); + species1.setHypothetical(true); + assertTrue(comparator.compare(species1, species2) != 0); + assertTrue(comparator.compare(species2, species1) != 0); + + species1 = createSimpleMolecule(); + species2 = createSimpleMolecule(); + species1.getMiriamData().iterator().next().setRelationType(MiriamRelationType.BQ_BIOL_IS); + assertTrue(comparator.compare(species1, species2) != 0); + assertTrue(comparator.compare(species2, species1) != 0); + + species1 = createSimpleMolecule(); + species2 = createSimpleMolecule(); + species1.addMiriamData(new MiriamData()); + assertTrue(comparator.compare(species1, species2) != 0); + assertTrue(comparator.compare(species2, species1) != 0); + + assertTrue(comparator.compare(new Rna(), new Drug()) != 0); } public SimpleMolecule createSimpleMolecule() { diff --git a/model/src/test/java/lcsb/mapviewer/model/map/species/SpeciesTest.java b/model/src/test/java/lcsb/mapviewer/model/map/species/SpeciesTest.java index a492d7aa9ac7b430fb7b04d2b60e6087ce8bef73..2dff3ef1f20f94139a9d9b5befff2123fba6f414 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/species/SpeciesTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/species/SpeciesTest.java @@ -1,12 +1,12 @@ package lcsb.mapviewer.model.map.species; -import static org.junit.Assert.assertEquals; +import static org.junit.Assert.*; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; -public class SpeciesTest { +import lcsb.mapviewer.ModelTestFunctions; + +public class SpeciesTest extends ModelTestFunctions { @Before public void setUp() throws Exception { @@ -18,17 +18,11 @@ public class SpeciesTest { @Test public void testGetter() { - try { - Species species = new GenericProtein("id"); - String state = "as"; - species.setState(state); - - assertEquals(state, species.getState()); + Species species = new GenericProtein("id"); + String state = "as"; + species.setState(state); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(state, species.getState()); } } diff --git a/model/src/test/java/lcsb/mapviewer/model/map/species/TruncatedProteinComparatorTest.java b/model/src/test/java/lcsb/mapviewer/model/map/species/TruncatedProteinComparatorTest.java index 8495fd04c2c3976e49699e5d8c449ebcf3eab4b8..feea3071a8fdcea24b8be4fb095c1ed72870bf60 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/species/TruncatedProteinComparatorTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/species/TruncatedProteinComparatorTest.java @@ -1,84 +1,60 @@ package lcsb.mapviewer.model.map.species; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.mockito.Mockito; +import lcsb.mapviewer.ModelTestFunctions; import lcsb.mapviewer.common.exception.NotImplementedException; -public class TruncatedProteinComparatorTest { +public class TruncatedProteinComparatorTest extends ModelTestFunctions { - TruncatedProteinComparator comparator = new TruncatedProteinComparator(); + TruncatedProteinComparator comparator = new TruncatedProteinComparator(); - @Before - public void setUp() throws Exception { - } + @Before + public void setUp() throws Exception { + } - @After - public void tearDown() throws Exception { - } + @After + public void tearDown() throws Exception { + } - @Test - public void testEquals() { - try { - TruncatedProtein drug1 = createTruncatedProtein(); - TruncatedProtein drug2 = createTruncatedProtein(); + @Test + public void testEquals() { + TruncatedProtein drug1 = createTruncatedProtein(); + TruncatedProtein drug2 = createTruncatedProtein(); - assertEquals(0, comparator.compare(drug1, drug1)); + assertEquals(0, comparator.compare(drug1, drug1)); - assertEquals(0, comparator.compare(drug1, drug2)); - assertEquals(0, comparator.compare(drug2, drug1)); + assertEquals(0, comparator.compare(drug1, drug2)); + assertEquals(0, comparator.compare(drug2, drug1)); + } - } catch (Exception e) { - e.printStackTrace(); - fail("Unknowne exception occurred"); - } - } + @Test + public void testDifferent() { + TruncatedProtein drug2 = createTruncatedProtein(); + assertTrue(comparator.compare(null, drug2) != 0); + assertTrue(comparator.compare(drug2, null) != 0); + assertTrue(comparator.compare(null, null) == 0); - @Test - public void testDifferent() { - try { - TruncatedProtein drug2 = createTruncatedProtein(); - assertTrue(comparator.compare(null, drug2) != 0); - assertTrue(comparator.compare(drug2, null) != 0); - assertTrue(comparator.compare(null, null) == 0); + TruncatedProtein drug = createTruncatedProtein(); + drug.setName("n"); + assertTrue(comparator.compare(drug, drug2) != 0); - TruncatedProtein drug = createTruncatedProtein(); - drug.setName("n"); - assertTrue(comparator.compare(drug, drug2) != 0); + assertTrue(comparator.compare(drug, Mockito.mock(TruncatedProtein.class)) != 0); + } - assertTrue(comparator.compare(drug, Mockito.mock(TruncatedProtein.class)) != 0); + public TruncatedProtein createTruncatedProtein() { + TruncatedProtein result = new TruncatedProtein(); + return result; + } - } catch (Exception e) { - e.printStackTrace(); - fail("Unknowne exception occurred"); - } - } + @Test(expected = NotImplementedException.class) + public void testInvalid() { + TruncatedProtein object = Mockito.mock(TruncatedProtein.class); - public TruncatedProtein createTruncatedProtein() { - TruncatedProtein result = new TruncatedProtein(); - return result; - } - - @Test - public void testInvalid() { - try { - TruncatedProtein object = Mockito.mock(TruncatedProtein.class); - - comparator.compare(object, object); - - fail("Exception expected"); - } catch (NotImplementedException e) { - - } catch (Exception e) { - e.printStackTrace(); - fail("Unknowne exception occurred"); - } - } + comparator.compare(object, object); + } } diff --git a/model/src/test/java/lcsb/mapviewer/model/map/species/TruncatedProteinTest.java b/model/src/test/java/lcsb/mapviewer/model/map/species/TruncatedProteinTest.java index c67c4db57ec6bbc8e20c78c9038966a950f2d0ad..fbaad1d3c14d944a04f4eb3825f91264d9fcd287 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/species/TruncatedProteinTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/species/TruncatedProteinTest.java @@ -1,69 +1,45 @@ package lcsb.mapviewer.model.map.species; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.mockito.Mockito; +import lcsb.mapviewer.ModelTestFunctions; import lcsb.mapviewer.common.exception.NotImplementedException; -public class TruncatedProteinTest { - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testSerialization() { - try { - SerializationUtils.serialize(new TruncatedProtein()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testConstructor() { - try { - TruncatedProtein species = new TruncatedProtein(new TruncatedProtein()); - assertNotNull(species); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testCopy1() { - try { - TruncatedProtein species = new TruncatedProtein("id").copy(); - assertNotNull(species); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testCopy2() { - try { - TruncatedProtein protein = Mockito.spy(TruncatedProtein.class); - protein.copy(); - fail("Exception expected"); - } catch (NotImplementedException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } +public class TruncatedProteinTest extends ModelTestFunctions { + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testSerialization() { + SerializationUtils.serialize(new TruncatedProtein()); + } + + @Test + public void testConstructor() { + TruncatedProtein species = new TruncatedProtein(new TruncatedProtein()); + assertNotNull(species); + } + + @Test + public void testCopy1() { + TruncatedProtein species = new TruncatedProtein("id").copy(); + assertNotNull(species); + } + + @Test(expected = NotImplementedException.class) + public void testCopy2() { + TruncatedProtein protein = Mockito.spy(TruncatedProtein.class); + protein.copy(); + } } diff --git a/model/src/test/java/lcsb/mapviewer/model/map/species/UnknownComparatorTest.java b/model/src/test/java/lcsb/mapviewer/model/map/species/UnknownComparatorTest.java index e0fe9a859ddf7dbce46f03725a7a700ced3e38d4..324249ff106b1a111d81224350b5c3793da56a3b 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/species/UnknownComparatorTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/species/UnknownComparatorTest.java @@ -1,84 +1,60 @@ package lcsb.mapviewer.model.map.species; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.mockito.Mockito; +import lcsb.mapviewer.ModelTestFunctions; import lcsb.mapviewer.common.exception.NotImplementedException; -public class UnknownComparatorTest { +public class UnknownComparatorTest extends ModelTestFunctions { - UnknownComparator comparator = new UnknownComparator(); + UnknownComparator comparator = new UnknownComparator(); - @Before - public void setUp() throws Exception { - } + @Before + public void setUp() throws Exception { + } - @After - public void tearDown() throws Exception { - } + @After + public void tearDown() throws Exception { + } - @Test - public void testEquals() { - try { - Unknown aRna1 = createUnknown(); - Unknown aRna2 = createUnknown(); + @Test + public void testEquals() { + Unknown aRna1 = createUnknown(); + Unknown aRna2 = createUnknown(); - assertEquals(0, comparator.compare(aRna1, aRna1)); + assertEquals(0, comparator.compare(aRna1, aRna1)); - assertEquals(0, comparator.compare(aRna1, aRna2)); - assertEquals(0, comparator.compare(aRna2, aRna1)); + assertEquals(0, comparator.compare(aRna1, aRna2)); + assertEquals(0, comparator.compare(aRna2, aRna1)); + } - } catch (Exception e) { - e.printStackTrace(); - fail("Unknowne exception occurred"); - } - } + @Test + public void testDifferent() { + Unknown unknown2 = createUnknown(); + assertTrue(comparator.compare(null, unknown2) != 0); + assertTrue(comparator.compare(unknown2, null) != 0); + assertTrue(comparator.compare(null, null) == 0); - @Test - public void testDifferent() { - try { - Unknown unknown2 = createUnknown(); - assertTrue(comparator.compare(null, unknown2) != 0); - assertTrue(comparator.compare(unknown2, null) != 0); - assertTrue(comparator.compare(null, null) == 0); + Unknown unknown = createUnknown(); + unknown.setName("n"); + assertTrue(comparator.compare(unknown, unknown2) != 0); - Unknown unknown = createUnknown(); - unknown.setName("n"); - assertTrue(comparator.compare(unknown, unknown2) != 0); + assertTrue(comparator.compare(unknown, Mockito.mock(Unknown.class)) != 0); + } - assertTrue(comparator.compare(unknown, Mockito.mock(Unknown.class)) != 0); + public Unknown createUnknown() { + Unknown result = new Unknown(); + return result; + } - } catch (Exception e) { - e.printStackTrace(); - fail("Unknowne exception occurred"); - } - } + @Test(expected = NotImplementedException.class) + public void testInvalid() { + Unknown object = Mockito.mock(Unknown.class); - public Unknown createUnknown() { - Unknown result = new Unknown(); - return result; - } - - @Test - public void testInvalid() { - try { - Unknown object = Mockito.mock(Unknown.class); - - comparator.compare(object, object); - - fail("Exception expected"); - } catch (NotImplementedException e) { - - } catch (Exception e) { - e.printStackTrace(); - fail("Unknowne exception occurred"); - } - } + comparator.compare(object, object); + } } diff --git a/model/src/test/java/lcsb/mapviewer/model/map/species/UnknownTest.java b/model/src/test/java/lcsb/mapviewer/model/map/species/UnknownTest.java index 591ac886f1195f83c247cc948a44727e850865ea..ed3e6cf75baaf884f92e10c716594b510d498270 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/species/UnknownTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/species/UnknownTest.java @@ -1,80 +1,51 @@ package lcsb.mapviewer.model.map.species; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.mockito.Mockito; +import lcsb.mapviewer.ModelTestFunctions; import lcsb.mapviewer.common.exception.NotImplementedException; -public class UnknownTest { - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testSerialization() { - try { - SerializationUtils.serialize(new Unknown()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testConstructor1() { - try { - Unknown degraded = new Unknown(new Unknown()); - assertNotNull(degraded); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testGetters() { - try { - Unknown degraded = new Unknown("id"); - assertNotNull(degraded.getStringType()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testCopy() { - try { - Unknown degraded = new Unknown().copy(); - assertNotNull(degraded); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testInvalidCopy() { - try { - Unknown object = Mockito.spy(Unknown.class); - object.copy(); - fail("Exception expected"); - } catch (NotImplementedException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } +public class UnknownTest extends ModelTestFunctions { + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testSerialization() { + SerializationUtils.serialize(new Unknown()); + } + + @Test + public void testConstructor1() { + Unknown degraded = new Unknown(new Unknown()); + assertNotNull(degraded); + } + + @Test + public void testGetters() { + Unknown degraded = new Unknown("id"); + assertNotNull(degraded.getStringType()); + } + + @Test + public void testCopy() { + Unknown degraded = new Unknown().copy(); + assertNotNull(degraded); + } + + @Test(expected = NotImplementedException.class) + public void testInvalidCopy() { + Unknown object = Mockito.spy(Unknown.class); + object.copy(); + } } diff --git a/model/src/test/java/lcsb/mapviewer/model/map/species/field/CodingRegionTest.java b/model/src/test/java/lcsb/mapviewer/model/map/species/field/CodingRegionTest.java index 42287fa3fe2efa098a2260a751252904b9557c66..cff6502b203f2af6f8819d09c9ce47735f0673ff 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/species/field/CodingRegionTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/species/field/CodingRegionTest.java @@ -1,23 +1,20 @@ package lcsb.mapviewer.model.map.species.field; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import java.awt.geom.Point2D; import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.mockito.Mockito; +import lcsb.mapviewer.ModelTestFunctions; import lcsb.mapviewer.common.Configuration; import lcsb.mapviewer.common.exception.InvalidArgumentException; import lcsb.mapviewer.common.exception.NotImplementedException; import lcsb.mapviewer.model.map.species.AntisenseRna; -public class CodingRegionTest { +public class CodingRegionTest extends ModelTestFunctions { @Before public void setUp() throws Exception { @@ -29,119 +26,74 @@ public class CodingRegionTest { @Test public void testSerialization() { - try { - SerializationUtils.serialize(new CodingRegion()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + SerializationUtils.serialize(new CodingRegion()); } @Test public void testConstructor1() { - try { - CodingRegion antisenseRna = new CodingRegion(); - CodingRegion antisenseRna2 = new CodingRegion(antisenseRna); - assertNotNull(antisenseRna2); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + CodingRegion antisenseRna = new CodingRegion(); + CodingRegion antisenseRna2 = new CodingRegion(antisenseRna); + assertNotNull(antisenseRna2); } @Test public void testUpdate() { - try { - CodingRegion antisenseRna = new CodingRegion(); - antisenseRna.setName("as"); - antisenseRna.setPosition(new Point2D.Double(10, 0)); - CodingRegion antisenseRna2 = new CodingRegion(); - antisenseRna2.update(antisenseRna); - assertEquals(antisenseRna.getName(), antisenseRna2.getName()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + CodingRegion antisenseRna = new CodingRegion(); + antisenseRna.setName("as"); + antisenseRna.setPosition(new Point2D.Double(10, 0)); + CodingRegion antisenseRna2 = new CodingRegion(); + antisenseRna2.update(antisenseRna); + assertEquals(antisenseRna.getName(), antisenseRna2.getName()); } - @Test + @Test(expected = InvalidArgumentException.class) public void testInvalidUpdate() { - try { - CodingRegion antisenseRna = new CodingRegion(); - CodingRegion antisenseRna2 = new CodingRegion(); - antisenseRna.setIdModificationResidue("@1"); - antisenseRna2.setIdModificationResidue("@"); - antisenseRna2.update(antisenseRna); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + CodingRegion antisenseRna = new CodingRegion(); + CodingRegion antisenseRna2 = new CodingRegion(); + antisenseRna.setIdModificationResidue("@1"); + antisenseRna2.setIdModificationResidue("@"); + antisenseRna2.update(antisenseRna); } @Test public void testGetters() { - try { - CodingRegion region = new CodingRegion(new CodingRegion()); - int id = 91; - AntisenseRna species = new AntisenseRna("id"); - Point2D position = new Point2D.Double(10, 20); - double width = 5.3; - String name = "nam"; - String idCodingRegion = "iddd"; - - region.setId(id); - region.setSpecies(species); - region.setPosition(position); - region.setWidth(width); - region.setName(name); - region.setIdModificationResidue(idCodingRegion); - - assertEquals(id, region.getId()); - assertEquals(species, region.getSpecies()); - assertEquals(position.distance(region.getPosition()), 0, Configuration.EPSILON); - assertEquals(width, region.getWidth(), Configuration.EPSILON); - assertEquals(name, region.getName()); - assertEquals(idCodingRegion, region.getIdModificationResidue()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + CodingRegion region = new CodingRegion(new CodingRegion()); + int id = 91; + AntisenseRna species = new AntisenseRna("id"); + Point2D position = new Point2D.Double(10, 20); + double width = 5.3; + String name = "nam"; + String idCodingRegion = "iddd"; + + region.setId(id); + region.setSpecies(species); + region.setPosition(position); + region.setWidth(width); + region.setName(name); + region.setIdModificationResidue(idCodingRegion); + + assertEquals(id, region.getId()); + assertEquals(species, region.getSpecies()); + assertEquals(position.distance(region.getPosition()), 0, Configuration.EPSILON); + assertEquals(width, region.getWidth(), Configuration.EPSILON); + assertEquals(name, region.getName()); + assertEquals(idCodingRegion, region.getIdModificationResidue()); } @Test public void testToString() { - try { - assertNotNull(new CodingRegion().toString()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertNotNull(new CodingRegion().toString()); } @Test public void testCopy() { - try { - CodingRegion degraded = new CodingRegion().copy(); - assertNotNull(degraded); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + CodingRegion degraded = new CodingRegion().copy(); + assertNotNull(degraded); } - @Test + @Test(expected = NotImplementedException.class) public void testInvalidCopy() { - try { - Mockito.mock(CodingRegion.class, Mockito.CALLS_REAL_METHODS).copy(); - fail("Exception expected"); - } catch (NotImplementedException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Mockito.mock(CodingRegion.class, Mockito.CALLS_REAL_METHODS).copy(); } } diff --git a/model/src/test/java/lcsb/mapviewer/model/map/species/field/ProteinBindingDomainTest.java b/model/src/test/java/lcsb/mapviewer/model/map/species/field/ProteinBindingDomainTest.java index 1211018e2de52140c3f0979573c6e3b780a43ffb..4ad27f53a33c581f21d717384b879bd03501f2b1 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/species/field/ProteinBindingDomainTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/species/field/ProteinBindingDomainTest.java @@ -1,22 +1,18 @@ package lcsb.mapviewer.model.map.species.field; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import java.awt.geom.Point2D; import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; +import lcsb.mapviewer.ModelTestFunctions; import lcsb.mapviewer.common.Configuration; import lcsb.mapviewer.common.exception.InvalidArgumentException; import lcsb.mapviewer.model.map.species.Rna; -public class ProteinBindingDomainTest { +public class ProteinBindingDomainTest extends ModelTestFunctions { @Before public void setUp() throws Exception { @@ -28,73 +24,46 @@ public class ProteinBindingDomainTest { @Test public void testSerialization() { - try { - SerializationUtils.serialize(new ProteinBindingDomain()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + SerializationUtils.serialize(new ProteinBindingDomain()); } @Test public void testConstructor() { - try { - ProteinBindingDomain region = new ProteinBindingDomain(new ProteinBindingDomain()); - assertNotNull(region); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + ProteinBindingDomain region = new ProteinBindingDomain(new ProteinBindingDomain()); + assertNotNull(region); } @Test public void testUpdate() { - try { - ProteinBindingDomain region = new ProteinBindingDomain(); - ProteinBindingDomain region2 = new ProteinBindingDomain(); - region2.setName("asd"); - region2.setPosition(new Point2D.Double(0, 10)); - region.update(region2); - assertEquals(region2.getName(), region.getName()); - assertTrue(region2.getPosition().distance(region.getPosition()) <= Configuration.EPSILON); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + ProteinBindingDomain region = new ProteinBindingDomain(); + ProteinBindingDomain region2 = new ProteinBindingDomain(); + region2.setName("asd"); + region2.setPosition(new Point2D.Double(0, 10)); + region.update(region2); + assertEquals(region2.getName(), region.getName()); + assertTrue(region2.getPosition().distance(region.getPosition()) <= Configuration.EPSILON); } - @Test + @Test(expected = InvalidArgumentException.class) public void testUpdate2() { - try { - ProteinBindingDomain region = new ProteinBindingDomain(); - region.setIdModificationResidue("1"); - ProteinBindingDomain region2 = new ProteinBindingDomain(); - region2.setIdModificationResidue("2"); - region.update(region2); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + ProteinBindingDomain region = new ProteinBindingDomain(); + region.setIdModificationResidue("1"); + ProteinBindingDomain region2 = new ProteinBindingDomain(); + region2.setIdModificationResidue("2"); + region.update(region2); } @Test public void testGetters() { - try { - ProteinBindingDomain region = new ProteinBindingDomain(); - double size = 2.5; - int id = 58; - Rna species = new Rna("id"); - region.setWidth(size); - region.setSpecies(species); - region.setId(id); - assertEquals(id, region.getId()); - assertEquals(size, region.getWidth(), Configuration.EPSILON); - assertEquals(species, region.getSpecies()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + ProteinBindingDomain region = new ProteinBindingDomain(); + double size = 2.5; + int id = 58; + Rna species = new Rna("id"); + region.setWidth(size); + region.setSpecies(species); + region.setId(id); + assertEquals(id, region.getId()); + assertEquals(size, region.getWidth(), Configuration.EPSILON); + assertEquals(species, region.getSpecies()); } } diff --git a/model/src/test/java/lcsb/mapviewer/model/map/species/field/StructureTest.java b/model/src/test/java/lcsb/mapviewer/model/map/species/field/StructureTest.java index 4e40ae40b28c4069a3f88697afc18f3aa26d2c7c..2014473d37d668eac4dd810df574b5a29b161b71 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/species/field/StructureTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/species/field/StructureTest.java @@ -1,66 +1,61 @@ package lcsb.mapviewer.model.map.species.field; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import java.util.HashSet; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.mockito.Mockito; import lcsb.mapviewer.common.exception.NotImplementedException; public class StructureTest { - @AfterClass - public static void tearDownAfterClass() throws Exception { - } - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testGetters() { - Structure s = new Structure(); - UniprotRecord ur = new UniprotRecord(); - ur.setId(100); - ur.setUniprotId("P29373"); - - int id = 101; - s.setUniprot(ur); - s.setId(id); - - ur.setStructures(new HashSet<Structure>() {private static final long serialVersionUID = 1L; {add(s);} }); - - assertEquals(ur, s.getUniprot()); - assertEquals(id, s.getId()); - assertEquals(s, ur.getStructures().iterator().next()); - } - - @Test - public void testCopy() { - Structure s = new Structure().copy(); - assertNotNull(s); - } - - @Test - public void testInvalidCopy() { - Structure s = Mockito.spy(Structure.class); - try { - s.copy(); - fail("Exception expected"); - } catch (NotImplementedException e) { - - } - } + @AfterClass + public static void tearDownAfterClass() throws Exception { + } + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testGetters() { + Structure s = new Structure(); + UniprotRecord ur = new UniprotRecord(); + ur.setId(100); + ur.setUniprotId("P29373"); + + int id = 101; + s.setUniprot(ur); + s.setId(id); + + ur.setStructures(new HashSet<Structure>() { + private static final long serialVersionUID = 1L; + { + add(s); + } + }); + + assertEquals(ur, s.getUniprot()); + assertEquals(id, s.getId()); + assertEquals(s, ur.getStructures().iterator().next()); + } + + @Test + public void testCopy() { + Structure s = new Structure().copy(); + assertNotNull(s); + } + + @Test(expected = NotImplementedException.class) + public void testInvalidCopy() { + Structure s = Mockito.spy(Structure.class); + s.copy(); + } } diff --git a/model/src/test/java/lcsb/mapviewer/model/map/species/field/UniprotRecordTest.java b/model/src/test/java/lcsb/mapviewer/model/map/species/field/UniprotRecordTest.java index 38460ffb23cccac9c2be4fa8c5d2d995e020e353..26e3aa41a8eef0477a332ee19696d4bf72df1cd9 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/species/field/UniprotRecordTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/species/field/UniprotRecordTest.java @@ -1,13 +1,8 @@ package lcsb.mapviewer.model.map.species.field; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; - -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.Test; +import static org.junit.Assert.*; + +import org.junit.*; import org.mockito.Mockito; import lcsb.mapviewer.common.exception.NotImplementedException; @@ -16,46 +11,41 @@ import lcsb.mapviewer.model.map.species.Species; public class UniprotRecordTest { - @AfterClass - public static void tearDownAfterClass() throws Exception { - } - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testGetters() { - UniprotRecord ur = new UniprotRecord(); - Species species = new GenericProtein("id"); - int id = 94; - - ur.setSpecies(species); - ur.setId(id); - - assertEquals(species, ur.getSpecies()); - assertEquals(id, ur.getId()); - } - - @Test - public void testCopy() { - UniprotRecord ur = new UniprotRecord().copy(); - assertNotNull(ur); - } - - @Test - public void testInvalidCopy() { - UniprotRecord ur = Mockito.spy(UniprotRecord.class); - try { - ur.copy(); - fail("Exception expected"); - } catch (NotImplementedException e) { - - } - } + @AfterClass + public static void tearDownAfterClass() throws Exception { + } + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testGetters() { + UniprotRecord ur = new UniprotRecord(); + Species species = new GenericProtein("id"); + int id = 94; + + ur.setSpecies(species); + ur.setId(id); + + assertEquals(species, ur.getSpecies()); + assertEquals(id, ur.getId()); + } + + @Test + public void testCopy() { + UniprotRecord ur = new UniprotRecord().copy(); + assertNotNull(ur); + } + + @Test(expected = NotImplementedException.class) + public void testInvalidCopy() { + UniprotRecord ur = Mockito.spy(UniprotRecord.class); + ur.copy(); + } } diff --git a/model/src/test/java/lcsb/mapviewer/model/map/statistics/SearchHistoryTest.java b/model/src/test/java/lcsb/mapviewer/model/map/statistics/SearchHistoryTest.java index bbbda64dde21df668b66b2a9b53e3e1832f304c8..08b7e0ee0acad095fa6e2df08951253052a275c8 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/statistics/SearchHistoryTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/statistics/SearchHistoryTest.java @@ -1,63 +1,52 @@ package lcsb.mapviewer.model.map.statistics; -import static org.junit.Assert.assertEquals; +import static org.junit.Assert.*; import java.util.Calendar; import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -public class SearchHistoryTest { - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testSerialization() { - try { - SerializationUtils.serialize(new SearchHistory()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testGetters() { - try { - SearchHistory sh = new SearchHistory(); - - int id = 60; - String query = "q"; - String map = "e"; - Calendar timestamp = Calendar.getInstance(); - SearchType type = SearchType.DRUG; - String ipAddress = "3.4"; - - sh.setId(id); - sh.setQuery(query); - sh.setMap(map); - sh.setTimestamp(timestamp); - sh.setType(type); - sh.setIpAddress(ipAddress); - - assertEquals(id, sh.getId()); - assertEquals(query, sh.getQuery()); - assertEquals(map, sh.getMap()); - assertEquals(timestamp, sh.getTimestamp()); - assertEquals(type, sh.getType()); - assertEquals(ipAddress, sh.getIpAddress()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } +import org.junit.*; + +import lcsb.mapviewer.ModelTestFunctions; + +public class SearchHistoryTest extends ModelTestFunctions { + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testSerialization() { + SerializationUtils.serialize(new SearchHistory()); + } + + @Test + public void testGetters() { + SearchHistory sh = new SearchHistory(); + + int id = 60; + String query = "q"; + String map = "e"; + Calendar timestamp = Calendar.getInstance(); + SearchType type = SearchType.DRUG; + String ipAddress = "3.4"; + + sh.setId(id); + sh.setQuery(query); + sh.setMap(map); + sh.setTimestamp(timestamp); + sh.setType(type); + sh.setIpAddress(ipAddress); + + assertEquals(id, sh.getId()); + assertEquals(query, sh.getQuery()); + assertEquals(map, sh.getMap()); + assertEquals(timestamp, sh.getTimestamp()); + assertEquals(type, sh.getType()); + assertEquals(ipAddress, sh.getIpAddress()); + } } diff --git a/model/src/test/java/lcsb/mapviewer/model/security/PrivilegeTest.java b/model/src/test/java/lcsb/mapviewer/model/security/PrivilegeTest.java index 68b38bc88cc0efe207f5609f5f713030d95dc32e..60c29ccdc87a3d0697abce8e4f36918ea4a635f0 100644 --- a/model/src/test/java/lcsb/mapviewer/model/security/PrivilegeTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/security/PrivilegeTest.java @@ -1,31 +1,23 @@ package lcsb.mapviewer.model.security; -import lcsb.mapviewer.model.security.Privilege; -import lcsb.mapviewer.model.security.PrivilegeType; - import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; + +import lcsb.mapviewer.ModelTestFunctions; -public class PrivilegeTest { +public class PrivilegeTest extends ModelTestFunctions { - @Before - public void setUp() throws Exception { - } + @Before + public void setUp() throws Exception { + } - @After - public void tearDown() throws Exception { - } + @After + public void tearDown() throws Exception { + } - @Test - public void testSerialization() { - try { - SerializationUtils.serialize(new Privilege(PrivilegeType.IS_ADMIN)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } + @Test + public void testSerialization() { + SerializationUtils.serialize(new Privilege(PrivilegeType.IS_ADMIN)); + } } diff --git a/model/src/test/java/lcsb/mapviewer/model/user/ConfigurationTest.java b/model/src/test/java/lcsb/mapviewer/model/user/ConfigurationTest.java index 554afa44cef20b3eb960a6b9ac403bc7f6c6aa2d..e9d088ff51628a08720a77d6a24e4e855aeeefd6 100644 --- a/model/src/test/java/lcsb/mapviewer/model/user/ConfigurationTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/user/ConfigurationTest.java @@ -1,49 +1,38 @@ package lcsb.mapviewer.model.user; -import static org.junit.Assert.assertEquals; +import static org.junit.Assert.*; import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -public class ConfigurationTest { - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testSerialization() { - try { - SerializationUtils.serialize(new ConfigurationOption()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testGetters() { - try { - ConfigurationOption conf = new ConfigurationOption(); - int id = 81; - ConfigurationElementType type = ConfigurationElementType.DEFAULT_MAP; - String value = "a.val"; - conf.setId(id); - assertEquals(id, conf.getId()); - conf.setType(type); - assertEquals(type, conf.getType()); - conf.setValue(value); - assertEquals(value, conf.getValue()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } +import org.junit.*; + +import lcsb.mapviewer.ModelTestFunctions; + +public class ConfigurationTest extends ModelTestFunctions { + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testSerialization() { + SerializationUtils.serialize(new ConfigurationOption()); + } + + @Test + public void testGetters() { + ConfigurationOption conf = new ConfigurationOption(); + int id = 81; + ConfigurationElementType type = ConfigurationElementType.DEFAULT_MAP; + String value = "a.val"; + conf.setId(id); + assertEquals(id, conf.getId()); + conf.setType(type); + assertEquals(type, conf.getType()); + conf.setValue(value); + assertEquals(value, conf.getValue()); + } } diff --git a/model/src/test/java/lcsb/mapviewer/model/user/UserAnnotationSchemaTest.java b/model/src/test/java/lcsb/mapviewer/model/user/UserAnnotationSchemaTest.java index d3039c5dca6f7ca1e0ec7f9c5bf1263f6e3f8db9..b5c9dba43898360db2a3e35b7c81e560d3289ca4 100644 --- a/model/src/test/java/lcsb/mapviewer/model/user/UserAnnotationSchemaTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/user/UserAnnotationSchemaTest.java @@ -1,20 +1,18 @@ package lcsb.mapviewer.model.user; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import java.util.ArrayList; import java.util.List; import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; +import lcsb.mapviewer.ModelTestFunctions; import lcsb.mapviewer.common.exception.InvalidArgumentException; import lcsb.mapviewer.model.map.MiriamType; -public class UserAnnotationSchemaTest { +public class UserAnnotationSchemaTest extends ModelTestFunctions { @Before public void setUp() throws Exception { @@ -26,207 +24,140 @@ public class UserAnnotationSchemaTest { @Test public void testAddClassAnnotator() throws Exception { - try { - UserAnnotationSchema annotationSchema = new UserAnnotationSchema(); - UserClassAnnotators ca = new UserClassAnnotators(String.class, new ArrayList<>()); - UserClassAnnotators ca2 = new UserClassAnnotators(String.class, new ArrayList<>()); - annotationSchema.addClassAnnotator(ca); - annotationSchema.addClassAnnotator(ca2); - assertEquals(1, annotationSchema.getClassAnnotators().size()); - assertEquals(ca2.getAnnotators(), annotationSchema.getAnnotatorsForClass(String.class)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + UserAnnotationSchema annotationSchema = new UserAnnotationSchema(); + UserClassAnnotators ca = new UserClassAnnotators(String.class, new ArrayList<>()); + UserClassAnnotators ca2 = new UserClassAnnotators(String.class, new ArrayList<>()); + annotationSchema.addClassAnnotator(ca); + annotationSchema.addClassAnnotator(ca2); + assertEquals(1, annotationSchema.getClassAnnotators().size()); + assertEquals(ca2.getAnnotators(), annotationSchema.getAnnotatorsForClass(String.class)); } - @Test + @Test(expected = InvalidArgumentException.class) public void testInvalidAddClassAnnotator() throws Exception { - try { - UserAnnotationSchema annotationSchema = new UserAnnotationSchema(); - UserClassAnnotators ca = new UserClassAnnotators(String.class, new ArrayList<>()); - ca.setClassName((String) null); - annotationSchema.addClassAnnotator(ca); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + UserAnnotationSchema annotationSchema = new UserAnnotationSchema(); + UserClassAnnotators ca = new UserClassAnnotators(String.class, new ArrayList<>()); + ca.setClassName((String) null); + annotationSchema.addClassAnnotator(ca); } @Test public void testAddClassRequiredAnnotations() throws Exception { - try { - UserAnnotationSchema annotationSchema = new UserAnnotationSchema(); - UserClassRequiredAnnotations cra = new UserClassRequiredAnnotations(String.class, new ArrayList<MiriamType>()); - UserClassRequiredAnnotations cra2 = new UserClassRequiredAnnotations(String.class, new ArrayList<MiriamType>()); - annotationSchema.addClassRequiredAnnotations(cra); - annotationSchema.addClassRequiredAnnotations(cra2); - assertEquals(1, annotationSchema.getClassRequiredAnnotators().size()); - assertEquals(cra2, annotationSchema.getClassRequiredAnnotators().get(0)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + UserAnnotationSchema annotationSchema = new UserAnnotationSchema(); + UserClassRequiredAnnotations cra = new UserClassRequiredAnnotations(String.class, new ArrayList<MiriamType>()); + UserClassRequiredAnnotations cra2 = new UserClassRequiredAnnotations(String.class, new ArrayList<MiriamType>()); + annotationSchema.addClassRequiredAnnotations(cra); + annotationSchema.addClassRequiredAnnotations(cra2); + assertEquals(1, annotationSchema.getClassRequiredAnnotators().size()); + assertEquals(cra2, annotationSchema.getClassRequiredAnnotators().get(0)); } - @Test + @Test(expected = InvalidArgumentException.class) public void testAddInvalidClassRequiredAnnotations() throws Exception { - try { - UserAnnotationSchema annotationSchema = new UserAnnotationSchema(); - UserClassRequiredAnnotations cra = new UserClassRequiredAnnotations(String.class, new ArrayList<MiriamType>()); - cra.setClassName((String) null); - - annotationSchema.addClassRequiredAnnotations(cra); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + UserAnnotationSchema annotationSchema = new UserAnnotationSchema(); + UserClassRequiredAnnotations cra = new UserClassRequiredAnnotations(String.class, new ArrayList<MiriamType>()); + cra.setClassName((String) null); + + annotationSchema.addClassRequiredAnnotations(cra); } @Test public void testAddClassValidAnnotations() throws Exception { - try { - UserAnnotationSchema annotationSchema = new UserAnnotationSchema(); - UserClassValidAnnotations cva = new UserClassValidAnnotations(String.class, new ArrayList<MiriamType>()); - UserClassValidAnnotations cva2 = new UserClassValidAnnotations(String.class, new ArrayList<MiriamType>()); - annotationSchema.addClassValidAnnotations(cva); - annotationSchema.addClassValidAnnotations(cva2); - assertEquals(1, annotationSchema.getClassValidAnnotators().size()); - assertEquals(cva2, annotationSchema.getClassValidAnnotators().get(0)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + UserAnnotationSchema annotationSchema = new UserAnnotationSchema(); + UserClassValidAnnotations cva = new UserClassValidAnnotations(String.class, new ArrayList<MiriamType>()); + UserClassValidAnnotations cva2 = new UserClassValidAnnotations(String.class, new ArrayList<MiriamType>()); + annotationSchema.addClassValidAnnotations(cva); + annotationSchema.addClassValidAnnotations(cva2); + assertEquals(1, annotationSchema.getClassValidAnnotators().size()); + assertEquals(cva2, annotationSchema.getClassValidAnnotators().get(0)); } @Test public void testGetValidAnnotations() throws Exception { - try { - UserAnnotationSchema annotationSchema = new UserAnnotationSchema(); - List<MiriamType> list = new ArrayList<>(); - list.add(MiriamType.CAS); - UserClassValidAnnotations cva = new UserClassValidAnnotations(String.class, list); - annotationSchema.addClassValidAnnotations(cva); - assertEquals(1, annotationSchema.getValidAnnotations(String.class).size()); - assertEquals(0, annotationSchema.getValidAnnotations(Integer.class).size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + UserAnnotationSchema annotationSchema = new UserAnnotationSchema(); + List<MiriamType> list = new ArrayList<>(); + list.add(MiriamType.CAS); + UserClassValidAnnotations cva = new UserClassValidAnnotations(String.class, list); + annotationSchema.addClassValidAnnotations(cva); + assertEquals(1, annotationSchema.getValidAnnotations(String.class).size()); + assertEquals(0, annotationSchema.getValidAnnotations(Integer.class).size()); } @Test public void testGetRequiredAnnotations() throws Exception { - try { - UserAnnotationSchema annotationSchema = new UserAnnotationSchema(); - List<MiriamType> list = new ArrayList<>(); - list.add(MiriamType.CAS); - UserClassRequiredAnnotations cva = new UserClassRequiredAnnotations(String.class, list); - annotationSchema.addClassRequiredAnnotations(cva); - assertEquals(1, annotationSchema.getRequiredAnnotations(String.class).size()); - assertEquals(0, annotationSchema.getRequiredAnnotations(Integer.class).size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + UserAnnotationSchema annotationSchema = new UserAnnotationSchema(); + List<MiriamType> list = new ArrayList<>(); + list.add(MiriamType.CAS); + UserClassRequiredAnnotations cva = new UserClassRequiredAnnotations(String.class, list); + annotationSchema.addClassRequiredAnnotations(cva); + assertEquals(1, annotationSchema.getRequiredAnnotations(String.class).size()); + assertEquals(0, annotationSchema.getRequiredAnnotations(Integer.class).size()); } - @Test + @Test(expected = InvalidArgumentException.class) public void testAddInvalidClassValidAnnotations() throws Exception { - try { - UserAnnotationSchema annotationSchema = new UserAnnotationSchema(); - UserClassValidAnnotations cva = new UserClassValidAnnotations(String.class, new ArrayList<MiriamType>()); - cva.setClassName((String) null); - - annotationSchema.addClassValidAnnotations(cva); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + UserAnnotationSchema annotationSchema = new UserAnnotationSchema(); + UserClassValidAnnotations cva = new UserClassValidAnnotations(String.class, new ArrayList<MiriamType>()); + cva.setClassName((String) null); + + annotationSchema.addClassValidAnnotations(cva); } @Test public void testAddGuiPreference() throws Exception { - try { - UserAnnotationSchema annotationSchema = new UserAnnotationSchema(); - - annotationSchema.addGuiPreference(new UserGuiPreference()); - assertEquals(1, annotationSchema.getGuiPreferences().size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + UserAnnotationSchema annotationSchema = new UserAnnotationSchema(); + + annotationSchema.addGuiPreference(new UserGuiPreference()); + assertEquals(1, annotationSchema.getGuiPreferences().size()); } @Test public void testAddGuiPreferenceWithDuplicateKey() throws Exception { - try { - UserAnnotationSchema annotationSchema = new UserAnnotationSchema(); - UserGuiPreference preference1 = new UserGuiPreference(); - preference1.setKey("test"); - preference1.setValue("value"); - annotationSchema.addGuiPreference(preference1); - UserGuiPreference preference2 = new UserGuiPreference(); - preference2.setKey("test"); - preference2.setValue("new value"); - annotationSchema.addGuiPreference(preference2); - assertEquals(1, annotationSchema.getGuiPreferences().size()); - assertEquals("new value", annotationSchema.getGuiPreferences().iterator().next().getValue()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + UserAnnotationSchema annotationSchema = new UserAnnotationSchema(); + UserGuiPreference preference1 = new UserGuiPreference(); + preference1.setKey("test"); + preference1.setValue("value"); + annotationSchema.addGuiPreference(preference1); + UserGuiPreference preference2 = new UserGuiPreference(); + preference2.setKey("test"); + preference2.setValue("new value"); + annotationSchema.addGuiPreference(preference2); + assertEquals(1, annotationSchema.getGuiPreferences().size()); + assertEquals("new value", annotationSchema.getGuiPreferences().iterator().next().getValue()); } @Test public void testSerialization() { - try { - SerializationUtils.serialize(new UserAnnotationSchema()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + SerializationUtils.serialize(new UserAnnotationSchema()); } @Test public void testGetters() { - try { - UserAnnotationSchema uas = new UserAnnotationSchema(); - Boolean validateMiriamTypes = true; - List<UserClassAnnotators> classAnnotators = new ArrayList<>(); - List<UserClassValidAnnotations> classValidAnnotators = new ArrayList<>(); - List<UserClassRequiredAnnotations> classRequiredAnnotators = new ArrayList<>(); - User user = new User(); - - Boolean sbgnFormat = true; - Boolean networkLayoutAsDefault = true; - - uas.setValidateMiriamTypes(validateMiriamTypes); - uas.setClassAnnotators(classAnnotators); - uas.setClassValidAnnotators(classValidAnnotators); - uas.setClassRequiredAnnotators(classRequiredAnnotators); - uas.setSbgnFormat(sbgnFormat); - uas.setNetworkLayoutAsDefault(networkLayoutAsDefault); - uas.setUser(user); - - assertEquals(validateMiriamTypes, uas.getValidateMiriamTypes()); - assertEquals(classAnnotators, uas.getClassAnnotators()); - assertEquals(classValidAnnotators, uas.getClassValidAnnotators()); - assertEquals(classRequiredAnnotators, uas.getClassRequiredAnnotators()); - assertEquals(sbgnFormat, uas.getSbgnFormat()); - assertEquals(networkLayoutAsDefault, uas.getNetworkLayoutAsDefault()); - assertEquals(user, uas.getUser()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + UserAnnotationSchema uas = new UserAnnotationSchema(); + Boolean validateMiriamTypes = true; + List<UserClassAnnotators> classAnnotators = new ArrayList<>(); + List<UserClassValidAnnotations> classValidAnnotators = new ArrayList<>(); + List<UserClassRequiredAnnotations> classRequiredAnnotators = new ArrayList<>(); + User user = new User(); + + Boolean sbgnFormat = true; + Boolean networkLayoutAsDefault = true; + + uas.setValidateMiriamTypes(validateMiriamTypes); + uas.setClassAnnotators(classAnnotators); + uas.setClassValidAnnotators(classValidAnnotators); + uas.setClassRequiredAnnotators(classRequiredAnnotators); + uas.setSbgnFormat(sbgnFormat); + uas.setNetworkLayoutAsDefault(networkLayoutAsDefault); + uas.setUser(user); + + assertEquals(validateMiriamTypes, uas.getValidateMiriamTypes()); + assertEquals(classAnnotators, uas.getClassAnnotators()); + assertEquals(classValidAnnotators, uas.getClassValidAnnotators()); + assertEquals(classRequiredAnnotators, uas.getClassRequiredAnnotators()); + assertEquals(sbgnFormat, uas.getSbgnFormat()); + assertEquals(networkLayoutAsDefault, uas.getNetworkLayoutAsDefault()); + assertEquals(user, uas.getUser()); } } diff --git a/model/src/test/java/lcsb/mapviewer/model/user/UserClassAnnotatorsTest.java b/model/src/test/java/lcsb/mapviewer/model/user/UserClassAnnotatorsTest.java index 4226c8aeb50ff54769a5397e18a5c412af346f5a..3d60065c9163ff9a2b40309e580792157e5e1305 100644 --- a/model/src/test/java/lcsb/mapviewer/model/user/UserClassAnnotatorsTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/user/UserClassAnnotatorsTest.java @@ -1,72 +1,55 @@ package lcsb.mapviewer.model.user; -import static org.junit.Assert.assertEquals; +import static org.junit.Assert.*; import java.util.ArrayList; import java.util.List; import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; +import lcsb.mapviewer.ModelTestFunctions; import lcsb.mapviewer.model.user.annotator.AnnotatorData; -public class UserClassAnnotatorsTest { - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testSerialization() { - try { - SerializationUtils.serialize(new UserClassAnnotators()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testConstructor() { - try { - List<AnnotatorData> list = new ArrayList<>(); - list.add(new AnnotatorData(Object.class)); - UserClassAnnotators uca = new UserClassAnnotators(String.class,list); - - assertEquals(1,uca.getAnnotators().size()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - @Test - public void testGetters() { - try { - UserClassAnnotators uca = new UserClassAnnotators(); - Integer id = 26; - UserAnnotationSchema annotationSchema = new UserAnnotationSchema(); - List<AnnotatorData> annotators = new ArrayList<>(); - AnnotatorData annotator = new AnnotatorData(Object.class); - - uca.setId(id); - uca.setAnnotationSchema(annotationSchema); - uca.setAnnotators(annotators); - uca.addAnnotator(annotator); - - assertEquals(id, uca.getId()); - assertEquals(annotationSchema, uca.getAnnotationSchema()); - assertEquals(annotator, uca.getAnnotators().get(0)); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } +public class UserClassAnnotatorsTest extends ModelTestFunctions { + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testSerialization() { + SerializationUtils.serialize(new UserClassAnnotators()); + } + + @Test + public void testConstructor() { + List<AnnotatorData> list = new ArrayList<>(); + list.add(new AnnotatorData(Object.class)); + UserClassAnnotators uca = new UserClassAnnotators(String.class, list); + + assertEquals(1, uca.getAnnotators().size()); + } + + @Test + public void testGetters() { + UserClassAnnotators uca = new UserClassAnnotators(); + Integer id = 26; + UserAnnotationSchema annotationSchema = new UserAnnotationSchema(); + List<AnnotatorData> annotators = new ArrayList<>(); + AnnotatorData annotator = new AnnotatorData(Object.class); + + uca.setId(id); + uca.setAnnotationSchema(annotationSchema); + uca.setAnnotators(annotators); + uca.addAnnotator(annotator); + + assertEquals(id, uca.getId()); + assertEquals(annotationSchema, uca.getAnnotationSchema()); + assertEquals(annotator, uca.getAnnotators().get(0)); + } } diff --git a/model/src/test/java/lcsb/mapviewer/model/user/UserClassRequiredAnnotationsTest.java b/model/src/test/java/lcsb/mapviewer/model/user/UserClassRequiredAnnotationsTest.java index 367d4d3fd096e539522ca4acadb2f3620e21a2a6..c5be48dff66f2aac1d900c5155074c7e6d0d0624 100644 --- a/model/src/test/java/lcsb/mapviewer/model/user/UserClassRequiredAnnotationsTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/user/UserClassRequiredAnnotationsTest.java @@ -1,97 +1,69 @@ package lcsb.mapviewer.model.user; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.Assert.*; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; +import java.util.*; import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; +import lcsb.mapviewer.ModelTestFunctions; import lcsb.mapviewer.model.map.MiriamType; -public class UserClassRequiredAnnotationsTest { - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testSerialization() { - try { - SerializationUtils.serialize(new UserClassRequiredAnnotations()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testGetters() { - try { - UserClassRequiredAnnotations obj = new UserClassRequiredAnnotations(); - Integer id= 24; - List<MiriamType> requiredMiriamTypes = new ArrayList<>(); - Boolean requireAtLestOneAnnotation = true; - UserAnnotationSchema annotationSchema = new UserAnnotationSchema(); - - obj.setId(id); - obj.setRequiredMiriamTypes(requiredMiriamTypes); - obj.setRequireAtLeastOneAnnotation(requireAtLestOneAnnotation); - obj.setAnnotationSchema(annotationSchema); - - assertEquals(id, obj.getId()); - assertEquals(requiredMiriamTypes, obj.getRequiredMiriamTypes()); - assertEquals(requireAtLestOneAnnotation, obj.getRequireAtLeastOneAnnotation()); - - assertEquals(annotationSchema, obj.getAnnotationSchema()); - - obj.addRequiredMiriamType(MiriamType.CCDS); - assertEquals(1,obj.getRequiredMiriamTypes().size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testConstructor() { - try { - UserClassRequiredAnnotations obj = new UserClassRequiredAnnotations(String.class,(Collection<MiriamType>)null); - assertFalse(obj.getRequireAtLeastOneAnnotation()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testConstructor2() { - try { - UserClassRequiredAnnotations obj = new UserClassRequiredAnnotations(String.class,new MiriamType[]{MiriamType.CAS}); - assertTrue(obj.getRequireAtLeastOneAnnotation()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - @Test - public void testConstructor3() { - try { - UserClassRequiredAnnotations obj = new UserClassRequiredAnnotations(String.class,new MiriamType[]{}); - assertFalse(obj.getRequireAtLeastOneAnnotation()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } +public class UserClassRequiredAnnotationsTest extends ModelTestFunctions { + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testSerialization() { + SerializationUtils.serialize(new UserClassRequiredAnnotations()); + } + + @Test + public void testGetters() { + UserClassRequiredAnnotations obj = new UserClassRequiredAnnotations(); + Integer id = 24; + List<MiriamType> requiredMiriamTypes = new ArrayList<>(); + Boolean requireAtLestOneAnnotation = true; + UserAnnotationSchema annotationSchema = new UserAnnotationSchema(); + + obj.setId(id); + obj.setRequiredMiriamTypes(requiredMiriamTypes); + obj.setRequireAtLeastOneAnnotation(requireAtLestOneAnnotation); + obj.setAnnotationSchema(annotationSchema); + + assertEquals(id, obj.getId()); + assertEquals(requiredMiriamTypes, obj.getRequiredMiriamTypes()); + assertEquals(requireAtLestOneAnnotation, obj.getRequireAtLeastOneAnnotation()); + + assertEquals(annotationSchema, obj.getAnnotationSchema()); + + obj.addRequiredMiriamType(MiriamType.CCDS); + assertEquals(1, obj.getRequiredMiriamTypes().size()); + } + + @Test + public void testConstructor() { + UserClassRequiredAnnotations obj = new UserClassRequiredAnnotations(String.class, (Collection<MiriamType>) null); + assertFalse(obj.getRequireAtLeastOneAnnotation()); + } + + @Test + public void testConstructor2() { + UserClassRequiredAnnotations obj = new UserClassRequiredAnnotations(String.class, + new MiriamType[] { MiriamType.CAS }); + assertTrue(obj.getRequireAtLeastOneAnnotation()); + } + + @Test + public void testConstructor3() { + UserClassRequiredAnnotations obj = new UserClassRequiredAnnotations(String.class, new MiriamType[] {}); + assertFalse(obj.getRequireAtLeastOneAnnotation()); + } } diff --git a/model/src/test/java/lcsb/mapviewer/model/user/UserClassValidAnnotationsTest.java b/model/src/test/java/lcsb/mapviewer/model/user/UserClassValidAnnotationsTest.java index a53c5c0f51c80fb6b3276b1b8d22673af5d00131..c6f7394bfd8e1df24a39ccb2e2d0a8098e72420a 100644 --- a/model/src/test/java/lcsb/mapviewer/model/user/UserClassValidAnnotationsTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/user/UserClassValidAnnotationsTest.java @@ -1,80 +1,55 @@ package lcsb.mapviewer.model.user; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.Assert.*; import java.util.ArrayList; import java.util.List; import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; +import lcsb.mapviewer.ModelTestFunctions; import lcsb.mapviewer.model.map.MiriamType; -public class UserClassValidAnnotationsTest { - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testSerialization() { - try { - SerializationUtils.serialize(new UserClassValidAnnotations()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testConstructor() { - try { - UserClassValidAnnotations usva = new UserClassValidAnnotations(Object.class, new MiriamType[] { MiriamType.CAS }); - assertNotNull(usva); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testGetters() { - try { - UserClassValidAnnotations usva = new UserClassValidAnnotations(); - List<MiriamType> validMiriamTypes = new ArrayList<>(); - UserAnnotationSchema schema = new UserAnnotationSchema(); - Integer id = 69; - usva.setValidMiriamTypes(validMiriamTypes); - assertEquals(validMiriamTypes, usva.getValidMiriamTypes()); - usva.setId(id); - assertEquals(id, usva.getId()); - usva.setAnnotationSchema(schema); - assertEquals(schema, usva.getAnnotationSchema()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testAddValidMiriamType() { - try { - UserClassValidAnnotations usva = new UserClassValidAnnotations(); - usva.addValidMiriamType(MiriamType.CAS); - assertTrue(usva.getValidMiriamTypes().contains(MiriamType.CAS)); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } +public class UserClassValidAnnotationsTest extends ModelTestFunctions { + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testSerialization() { + SerializationUtils.serialize(new UserClassValidAnnotations()); + } + + @Test + public void testConstructor() { + UserClassValidAnnotations usva = new UserClassValidAnnotations(Object.class, new MiriamType[] { MiriamType.CAS }); + assertNotNull(usva); + } + + @Test + public void testGetters() { + UserClassValidAnnotations usva = new UserClassValidAnnotations(); + List<MiriamType> validMiriamTypes = new ArrayList<>(); + UserAnnotationSchema schema = new UserAnnotationSchema(); + Integer id = 69; + usva.setValidMiriamTypes(validMiriamTypes); + assertEquals(validMiriamTypes, usva.getValidMiriamTypes()); + usva.setId(id); + assertEquals(id, usva.getId()); + usva.setAnnotationSchema(schema); + assertEquals(schema, usva.getAnnotationSchema()); + } + + @Test + public void testAddValidMiriamType() { + UserClassValidAnnotations usva = new UserClassValidAnnotations(); + usva.addValidMiriamType(MiriamType.CAS); + assertTrue(usva.getValidMiriamTypes().contains(MiriamType.CAS)); + } } diff --git a/model/src/test/java/lcsb/mapviewer/model/user/UserTest.java b/model/src/test/java/lcsb/mapviewer/model/user/UserTest.java index 20f13d7827bb406fb173ab8b80b4707df23a8cb4..3c243c43f7fa81d01ea149991a24877ba3b2ea78 100644 --- a/model/src/test/java/lcsb/mapviewer/model/user/UserTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/user/UserTest.java @@ -1,114 +1,91 @@ package lcsb.mapviewer.model.user; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.*; import java.awt.Color; import java.util.HashSet; import java.util.Set; +import org.apache.commons.lang3.SerializationUtils; +import org.junit.*; + +import lcsb.mapviewer.ModelTestFunctions; import lcsb.mapviewer.model.security.Privilege; import lcsb.mapviewer.model.security.PrivilegeType; -import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -public class UserTest { - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testSerialization() { - try { - SerializationUtils.serialize(new User()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testToString() { - try { - assertNotNull(new User().toString()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testAddPrivilege() { - try { - User user = new User(); - user.addPrivilege(new Privilege(PrivilegeType.IS_ADMIN)); - assertEquals(1, user.getPrivileges().size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testGetters() { - try { - User user = new User(); - int id = 737; - String login = "log 54"; - String cryptedPassword = "pa"; - String name = "ccr"; - String email= "a.a@pl.pl"; - String surname = "cccv"; - Set<Privilege> privileges = new HashSet<>(); - boolean removed = true; - UserAnnotationSchema annotationSchema = new UserAnnotationSchema(); - Color minColor = Color.BLACK; - Color maxColor = Color.BLUE; - - user.setMaxColor(maxColor); - assertEquals(maxColor, user.getMaxColor()); - - user.setMinColor(minColor); - assertEquals(minColor, user.getMinColor()); - - user.setId(id); - assertEquals((Integer)id, user.getId()); - - user.setLogin(login); - assertEquals(login, user.getLogin()); - - user.setCryptedPassword(cryptedPassword); - assertEquals(cryptedPassword, user.getCryptedPassword()); - - user.setName(name); - assertEquals(name, user.getName()); - - user.setSurname(surname); - assertEquals(surname, user.getSurname()); - - user.setPrivileges(privileges); - assertEquals(privileges, user.getPrivileges()); - - user.setRemoved(removed); - assertEquals(removed, user.isRemoved()); - - user.setEmail(email); - assertEquals(email, user.getEmail()); - - user.setAnnotationSchema(annotationSchema); - assertEquals(annotationSchema, user.getAnnotationSchema()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } +public class UserTest extends ModelTestFunctions { + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testSerialization() { + SerializationUtils.serialize(new User()); + } + + @Test + public void testToString() { + assertNotNull(new User().toString()); + } + + @Test + public void testAddPrivilege() { + User user = new User(); + user.addPrivilege(new Privilege(PrivilegeType.IS_ADMIN)); + assertEquals(1, user.getPrivileges().size()); + } + + @Test + public void testGetters() { + User user = new User(); + int id = 737; + String login = "log 54"; + String cryptedPassword = "pa"; + String name = "ccr"; + String email = "a.a@pl.pl"; + String surname = "cccv"; + Set<Privilege> privileges = new HashSet<>(); + boolean removed = true; + UserAnnotationSchema annotationSchema = new UserAnnotationSchema(); + Color minColor = Color.BLACK; + Color maxColor = Color.BLUE; + + user.setMaxColor(maxColor); + assertEquals(maxColor, user.getMaxColor()); + + user.setMinColor(minColor); + assertEquals(minColor, user.getMinColor()); + + user.setId(id); + assertEquals((Integer) id, user.getId()); + + user.setLogin(login); + assertEquals(login, user.getLogin()); + + user.setCryptedPassword(cryptedPassword); + assertEquals(cryptedPassword, user.getCryptedPassword()); + + user.setName(name); + assertEquals(name, user.getName()); + + user.setSurname(surname); + assertEquals(surname, user.getSurname()); + + user.setPrivileges(privileges); + assertEquals(privileges, user.getPrivileges()); + + user.setRemoved(removed); + assertEquals(removed, user.isRemoved()); + + user.setEmail(email); + assertEquals(email, user.getEmail()); + + user.setAnnotationSchema(annotationSchema); + assertEquals(annotationSchema, user.getAnnotationSchema()); + } } diff --git a/model/src/test/java/lcsb/mapviewer/modelutils/map/ClassTreeNodeTest.java b/model/src/test/java/lcsb/mapviewer/modelutils/map/ClassTreeNodeTest.java index db90ccf76848eb7f8a7977f1c48e109cba8cbf3c..0b80b693bc25a63c9e779be310700c2be5d2fccd 100644 --- a/model/src/test/java/lcsb/mapviewer/modelutils/map/ClassTreeNodeTest.java +++ b/model/src/test/java/lcsb/mapviewer/modelutils/map/ClassTreeNodeTest.java @@ -1,43 +1,37 @@ package lcsb.mapviewer.modelutils.map; -import static org.junit.Assert.assertEquals; +import static org.junit.Assert.*; import java.util.ArrayList; import java.util.List; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -public class ClassTreeNodeTest { - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testSetters() { - try { - ClassTreeNode node = new ClassTreeNode(Object.class); - Class<?> clazz = String.class; - List<ClassTreeNode> children = new ArrayList<>(); - String commonName= "test"; - node.setClazz(clazz); - node.setChildren(children); - node.setCommonName(commonName); - - assertEquals(clazz, node.getClazz()); - assertEquals(children, node.getChildren()); - assertEquals(commonName, node.getCommonName()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } +import org.junit.*; + +import lcsb.mapviewer.ModelTestFunctions; + +public class ClassTreeNodeTest extends ModelTestFunctions { + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testSetters() { + ClassTreeNode node = new ClassTreeNode(Object.class); + Class<?> clazz = String.class; + List<ClassTreeNode> children = new ArrayList<>(); + String commonName = "test"; + node.setClazz(clazz); + node.setChildren(children); + node.setCommonName(commonName); + + assertEquals(clazz, node.getClazz()); + assertEquals(children, node.getChildren()); + assertEquals(commonName, node.getCommonName()); + } } diff --git a/model/src/test/java/lcsb/mapviewer/modelutils/map/ElementUtilsTest.java b/model/src/test/java/lcsb/mapviewer/modelutils/map/ElementUtilsTest.java index 274be50b07e454c2eb95671e73bed67925fffc5c..52a54352b5ee1e673944349ef0b3aea950c098a4 100644 --- a/model/src/test/java/lcsb/mapviewer/modelutils/map/ElementUtilsTest.java +++ b/model/src/test/java/lcsb/mapviewer/modelutils/map/ElementUtilsTest.java @@ -1,32 +1,21 @@ package lcsb.mapviewer.modelutils.map; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.junit.Assert.*; -import java.util.LinkedList; -import java.util.List; -import java.util.Queue; +import java.util.*; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.mockito.Mockito; +import lcsb.mapviewer.ModelTestFunctions; import lcsb.mapviewer.common.exception.InvalidArgumentException; import lcsb.mapviewer.model.map.reaction.Reaction; import lcsb.mapviewer.model.map.reaction.type.UnknownNegativeInfluenceReaction; -import lcsb.mapviewer.model.map.species.Element; -import lcsb.mapviewer.model.map.species.GenericProtein; -import lcsb.mapviewer.model.map.species.Ion; -import lcsb.mapviewer.model.map.species.IonChannelProtein; -import lcsb.mapviewer.model.map.species.Protein; +import lcsb.mapviewer.model.map.species.*; -public class ElementUtilsTest { +public class ElementUtilsTest extends ModelTestFunctions { Logger logger = LogManager.getLogger(ElementUtilsTest.class); @Before @@ -41,66 +30,40 @@ public class ElementUtilsTest { @Test public void testClassTree() throws Exception { - try { - ElementUtils elementUtils = new ElementUtils(); + ElementUtils elementUtils = new ElementUtils(); - ClassTreeNode top = elementUtils.getAnnotatedElementClassTree(); - elementUtils.getAnnotatedElementClassTree(); - elementUtils.getAnnotatedElementClassTree(); - elementUtils.getAnnotatedElementClassTree(); - elementUtils.getAnnotatedElementClassTree(); + ClassTreeNode top = elementUtils.getAnnotatedElementClassTree(); + elementUtils.getAnnotatedElementClassTree(); + elementUtils.getAnnotatedElementClassTree(); + elementUtils.getAnnotatedElementClassTree(); + elementUtils.getAnnotatedElementClassTree(); - assertNotNull(top); + assertNotNull(top); - assertTrue(top.getChildren().size() > 0); - - // print(top, 0); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertTrue(top.getChildren().size() > 0); } @Test public void testGetTag() throws Exception { - try { - ElementUtils elementUtils = new ElementUtils(); + ElementUtils elementUtils = new ElementUtils(); - assertNotNull(elementUtils.getElementTag(Mockito.spy(new Reaction()))); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertNotNull(elementUtils.getElementTag(Mockito.spy(new Reaction()))); } @Test public void testGetTag2() throws Exception { - try { - ElementUtils elementUtils = new ElementUtils(); + ElementUtils elementUtils = new ElementUtils(); - GenericProtein protein = new GenericProtein("id"); + GenericProtein protein = new GenericProtein("id"); - assertNotNull(elementUtils.getElementTag(protein, new Object())); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertNotNull(elementUtils.getElementTag(protein, new Object())); } @Test public void testTagForNull() throws Exception { - try { - ElementUtils elementUtils = new ElementUtils(); + ElementUtils elementUtils = new ElementUtils(); - assertNotNull(elementUtils.getElementTag(null, null)); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertNotNull(elementUtils.getElementTag(null, null)); } protected void print(ClassTreeNode top, int indent) { @@ -119,99 +82,65 @@ public class ElementUtilsTest { @Test public void tesGetAvailableElementSubclasses() throws Exception { - try { - ElementUtils elementUtils = new ElementUtils(); - - List<Class<? extends Element>> list = elementUtils.getAvailableElementSubclasses(); - assertTrue(list.contains(IonChannelProtein.class)); - assertFalse(list.contains(Protein.class)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + ElementUtils elementUtils = new ElementUtils(); + + List<Class<? extends Element>> list = elementUtils.getAvailableElementSubclasses(); + assertTrue(list.contains(IonChannelProtein.class)); + assertFalse(list.contains(Protein.class)); } @Test public void tesClassByName() throws Exception { - try { - ElementUtils elementUtils = new ElementUtils(); - assertEquals(Ion.class, elementUtils.getClassByName(Ion.class.getSimpleName())); - assertEquals(Ion.class, elementUtils.getClassByName("Ion")); - assertNull(elementUtils.getClassByName("unknown class name")); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + ElementUtils elementUtils = new ElementUtils(); + assertEquals(Ion.class, elementUtils.getClassByName(Ion.class.getSimpleName())); + assertEquals(Ion.class, elementUtils.getClassByName("Ion")); + assertNull(elementUtils.getClassByName("unknown class name")); } @Test public void tesGetAvailableReactionSubclasses() throws Exception { - try { - ElementUtils elementUtils = new ElementUtils(); - - List<Class<? extends Reaction>> list = elementUtils.getAvailableReactionSubclasses(); - assertTrue(list.contains(UnknownNegativeInfluenceReaction.class)); - assertFalse(list.contains(Reaction.class)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + ElementUtils elementUtils = new ElementUtils(); + + List<Class<? extends Reaction>> list = elementUtils.getAvailableReactionSubclasses(); + assertTrue(list.contains(UnknownNegativeInfluenceReaction.class)); + assertFalse(list.contains(Reaction.class)); } @Test public void tesClassByName2() throws Exception { - try { - ElementUtils elementUtils = new ElementUtils(); - assertEquals(UnknownNegativeInfluenceReaction.class, elementUtils.getClassByName("UnknownNegativeInfluence")); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + ElementUtils elementUtils = new ElementUtils(); + assertEquals(UnknownNegativeInfluenceReaction.class, elementUtils.getClassByName("UnknownNegativeInfluence")); } @Test public void tesAnnotatedElementClassTree() throws Exception { - try { - ElementUtils elementUtils = new ElementUtils(); - ClassTreeNode tree = elementUtils.getAnnotatedElementClassTree(); - Queue<ClassTreeNode> queue = new LinkedList<ClassTreeNode>(); - queue.add(tree); - while (!queue.isEmpty()) { - ClassTreeNode node = queue.poll(); - for (ClassTreeNode child : node.getChildren()) { - queue.add(child); - } - assertNotNull("Data for class " + node.getClazz() + " is null", node.getData()); + ElementUtils elementUtils = new ElementUtils(); + ClassTreeNode tree = elementUtils.getAnnotatedElementClassTree(); + Queue<ClassTreeNode> queue = new LinkedList<ClassTreeNode>(); + queue.add(tree); + while (!queue.isEmpty()) { + ClassTreeNode node = queue.poll(); + for (ClassTreeNode child : node.getChildren()) { + queue.add(child); } - - } catch (Exception e) { - e.printStackTrace(); - throw e; + assertNotNull("Data for class " + node.getClazz() + " is null", node.getData()); } } @Test public void tesAnnotatedElementClassTreeSorted() throws Exception { - try { - ElementUtils elementUtils = new ElementUtils(); - ClassTreeNode tree = elementUtils.getAnnotatedElementClassTree(); - Queue<ClassTreeNode> queue = new LinkedList<ClassTreeNode>(); - queue.add(tree); - while (!queue.isEmpty()) { - ClassTreeNode node = queue.poll(); - String lastChild = ""; - for (ClassTreeNode child : node.getChildren()) { - queue.add(child); - assertTrue(lastChild.compareTo(child.getCommonName()) <= 0); - lastChild = child.getCommonName(); - } + ElementUtils elementUtils = new ElementUtils(); + ClassTreeNode tree = elementUtils.getAnnotatedElementClassTree(); + Queue<ClassTreeNode> queue = new LinkedList<ClassTreeNode>(); + queue.add(tree); + while (!queue.isEmpty()) { + ClassTreeNode node = queue.poll(); + String lastChild = ""; + for (ClassTreeNode child : node.getChildren()) { + queue.add(child); + assertTrue(lastChild.compareTo(child.getCommonName()) <= 0); + lastChild = child.getCommonName(); } - - } catch (Exception e) { - e.printStackTrace(); - throw e; } } diff --git a/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/ComplexReactionToModelTest.java b/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/ComplexReactionToModelTest.java index e3ad0ce78ee96389b4b07f5769eec724fd871356..6cbde646a39149423d4c105198b8b097d5d36873 100644 --- a/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/ComplexReactionToModelTest.java +++ b/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/ComplexReactionToModelTest.java @@ -1,12 +1,11 @@ package lcsb.mapviewer.wikipathway; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.Assert.*; import java.awt.Color; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.junit.Test; import lcsb.mapviewer.model.map.model.Model; @@ -17,182 +16,134 @@ import lcsb.mapviewer.model.map.species.Element; import lcsb.mapviewer.wikipathway.XML.GPMLToModel; public class ComplexReactionToModelTest extends WikipathwaysTestFunctions { - /** - * Default class logger. - */ + static Logger logger = LogManager.getLogger(ComplexReactionToModelTest.class); @Test public void ComplexReactionTest() throws Exception { - try { - String fileName = "testFiles/reactions/two_segment_reaction.gpml"; + String fileName = "testFiles/reactions/two_segment_reaction.gpml"; - Model model1 = new GPMLToModel().getModel(fileName); + Model model1 = new GPMLToModel().getModel(fileName); - assertEquals(1, model1.getReactions().size()); + assertEquals(1, model1.getReactions().size()); - Reaction reaction = model1.getReactions().iterator().next(); + Reaction reaction = model1.getReactions().iterator().next(); - assertEquals(1, reaction.getReactants().size()); - assertEquals(1, reaction.getProducts().size()); + assertEquals(1, reaction.getReactants().size()); + assertEquals(1, reaction.getProducts().size()); - assertEquals(0, getWarnings().size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, getWarnings().size()); } @Test public void ComplexReactantReactionTest() throws Exception { - try { - String fileName = "testFiles/reactions/two_reactants_reaction.gpml"; + String fileName = "testFiles/reactions/two_reactants_reaction.gpml"; - Model model1 = new GPMLToModel().getModel(fileName); + Model model1 = new GPMLToModel().getModel(fileName); - assertEquals(1, model1.getReactions().size()); + assertEquals(1, model1.getReactions().size()); - Reaction reaction = model1.getReactions().iterator().next(); + Reaction reaction = model1.getReactions().iterator().next(); - assertEquals(2, reaction.getReactants().size()); - assertEquals(1, reaction.getProducts().size()); + assertEquals(2, reaction.getReactants().size()); + assertEquals(1, reaction.getProducts().size()); - assertEquals(1, getWarnings().size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(1, getWarnings().size()); } @Test public void ComplexSplitReactionTest() throws Exception { - try { - String fileName = "testFiles/reactions/split_two_segment_reaction.gpml"; + String fileName = "testFiles/reactions/split_two_segment_reaction.gpml"; - Model model1 = new GPMLToModel().getModel(fileName); + Model model1 = new GPMLToModel().getModel(fileName); - assertEquals(1, model1.getReactions().size()); + assertEquals(1, model1.getReactions().size()); - Reaction reaction = model1.getReactions().iterator().next(); + Reaction reaction = model1.getReactions().iterator().next(); - assertEquals(1, reaction.getReactants().size()); - assertEquals(2, reaction.getProducts().size()); + assertEquals(1, reaction.getReactants().size()); + assertEquals(2, reaction.getProducts().size()); - assertEquals(0, getWarnings().size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, getWarnings().size()); } @Test public void problematicReactantTest() throws Exception { - try { - ModelComparator mc = new ModelComparator(1.0); + ModelComparator mc = new ModelComparator(1.0); - String fileName = "testFiles/small/problematic_reactant.gpml"; + String fileName = "testFiles/small/problematic_reactant.gpml"; - Model model1 = new GPMLToModel().getModel(fileName); + Model model1 = new GPMLToModel().getModel(fileName); - Model model2 = serializeModelOverCellDesignerParser(model1); - assertEquals("File " + fileName + " different after transformation", 0, mc.compare(model1, model2)); + Model model2 = serializeModelOverCellDesignerParser(model1); + assertEquals("File " + fileName + " different after transformation", 0, mc.compare(model1, model2)); - assertEquals(7, getWarnings().size()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(7, getWarnings().size()); } @Test public void problematicReactant2Test() throws Exception { - try { - ModelComparator mc = new ModelComparator(1.0); - - String fileName = "testFiles/small/problematic_reactant_2.gpml"; + ModelComparator mc = new ModelComparator(1.0); - Model model1 = new GPMLToModel().getModel(fileName); + String fileName = "testFiles/small/problematic_reactant_2.gpml"; - Model model2 = serializeModelOverCellDesignerParser(model1); - assertEquals("File " + fileName + " different after transformation", 0, mc.compare(model1, model2)); + Model model1 = new GPMLToModel().getModel(fileName); - assertEquals(3, getWarnings().size()); + Model model2 = serializeModelOverCellDesignerParser(model1); + assertEquals("File " + fileName + " different after transformation", 0, mc.compare(model1, model2)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(3, getWarnings().size()); } @Test public void missingNodesInReactionTest() throws Exception { - try { - ModelComparator mc = new ModelComparator(1.0); - - String fileName = "testFiles/small/missing_nodes_in_reaction.gpml"; + ModelComparator mc = new ModelComparator(1.0); - Model model1 = new GPMLToModel().getModel(fileName); + String fileName = "testFiles/small/missing_nodes_in_reaction.gpml"; - Model model2 = serializeModelOverCellDesignerParser(model1); + Model model1 = new GPMLToModel().getModel(fileName); - assertEquals("File " + fileName + " different after transformation", 0, mc.compare(model1, model2)); + Model model2 = serializeModelOverCellDesignerParser(model1); - assertEquals(5, getWarnings().size()); + assertEquals("File " + fileName + " different after transformation", 0, mc.compare(model1, model2)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(5, getWarnings().size()); } @Test public void testColorReaction() throws Exception { - try { - String fileName = "testFiles/small/color_reaction.gpml"; - Model model = new GPMLToModel().getModel(fileName); + String fileName = "testFiles/small/color_reaction.gpml"; + Model model = new GPMLToModel().getModel(fileName); - assertEquals(1, model.getReactions().size()); + assertEquals(1, model.getReactions().size()); - Reaction reaction = model.getReactions().iterator().next(); + Reaction reaction = model.getReactions().iterator().next(); - assertFalse(Color.BLACK.equals(reaction.getReactants().get(0).getLine().getColor())); + assertFalse(Color.BLACK.equals(reaction.getReactants().get(0).getLine().getColor())); - Element redAlias = model.getElementByElementId("d9620"); - Element blackAlias = model.getElementByElementId("d046f"); - assertFalse(Color.BLACK.equals(redAlias.getColor())); - assertTrue(Color.WHITE.equals(blackAlias.getColor())); + Element redAlias = model.getElementByElementId("d9620"); + Element blackAlias = model.getElementByElementId("d046f"); + assertFalse(Color.BLACK.equals(redAlias.getColor())); + assertTrue(Color.WHITE.equals(blackAlias.getColor())); - assertEquals(1, getWarnings().size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(1, getWarnings().size()); } - /** - * @throws Exception - */ @Test public void testReactionWithTwoSegments() throws Exception { - try { - String fileName = "testFiles/small/color_reaction.gpml"; - Model model = new GPMLToModel().getModel(fileName); + String fileName = "testFiles/small/color_reaction.gpml"; + Model model = new GPMLToModel().getModel(fileName); - Reaction reaction = model.getReactions().iterator().next(); + Reaction reaction = model.getReactions().iterator().next(); - int lineCount = 0; - for (AbstractNode node : reaction.getNodes()) { - lineCount += node.getLine().getLines().size(); - } + int lineCount = 0; + for (AbstractNode node : reaction.getNodes()) { + lineCount += node.getLine().getLines().size(); + } - assertEquals(4, lineCount); + assertEquals(4, lineCount); - assertEquals(1, getWarnings().size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(1, getWarnings().size()); } } diff --git a/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/GPMLToModelTest.java b/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/GPMLToModelTest.java index dc6f13d664c93fad3c1c291b89c0f559be78c3a3..ea1b53f84105eaedb7ac7434cf36736d09c5b162 100644 --- a/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/GPMLToModelTest.java +++ b/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/GPMLToModelTest.java @@ -1,9 +1,6 @@ package lcsb.mapviewer.wikipathway; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.Assert.*; import java.awt.geom.Line2D; @@ -17,15 +14,11 @@ import lcsb.mapviewer.model.map.compartment.Compartment; import lcsb.mapviewer.model.map.model.Model; import lcsb.mapviewer.model.map.model.ModelComparator; import lcsb.mapviewer.model.map.reaction.Reaction; -import lcsb.mapviewer.model.map.species.Complex; -import lcsb.mapviewer.model.map.species.Gene; -import lcsb.mapviewer.model.map.species.Protein; +import lcsb.mapviewer.model.map.species.*; import lcsb.mapviewer.wikipathway.XML.GPMLToModel; public class GPMLToModelTest extends WikipathwaysTestFunctions { - /** - * Default class logger. - */ + static Logger logger = LogManager.getLogger(GPMLToModelTest.class); private ModelComparator mc = new ModelComparator(1.0); @@ -34,484 +27,335 @@ public class GPMLToModelTest extends WikipathwaysTestFunctions { @Test public void DopamineTest() throws Exception { - try { - Model model1 = new GPMLToModel().getModel("testFiles/wikipathways/Dopamine.gpml"); + Model model1 = new GPMLToModel().getModel("testFiles/wikipathways/Dopamine.gpml"); - assertEquals(22, getWarnings().size()); - Model model2 = serializeModelOverCellDesignerParser(model1); + assertEquals(22, getWarnings().size()); + Model model2 = serializeModelOverCellDesignerParser(model1); - assertEquals(0, mc.compare(model1, model2)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } @Test public void WP1403_75220Test() throws Exception { - try { - Model model1 = new GPMLToModel().getModel("testFiles/wikipathways/WP1403_75220.gpml"); + Model model1 = new GPMLToModel().getModel("testFiles/wikipathways/WP1403_75220.gpml"); - assertEquals(22, getWarnings().size()); - Model model2 = serializeModelOverCellDesignerParser(model1); + assertEquals(22, getWarnings().size()); + Model model2 = serializeModelOverCellDesignerParser(model1); - assertEquals(0, mc.compare(model1, model2)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } @Test public void WP528_76269Test() throws Exception { - try { - Model model1 = new GPMLToModel().getModel("testFiles/wikipathways/WP528_76269.gpml"); + Model model1 = new GPMLToModel().getModel("testFiles/wikipathways/WP528_76269.gpml"); - assertEquals(15, getWarnings().size()); - Model model2 = serializeModelOverCellDesignerParser(model1); + assertEquals(15, getWarnings().size()); + Model model2 = serializeModelOverCellDesignerParser(model1); - assertEquals(0, mc.compare(model1, model2)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } @Test public void WP550_73391Test() throws Exception { - try { - Model model1 = new GPMLToModel().getModel("testFiles/wikipathways/WP550_73391.gpml"); + Model model1 = new GPMLToModel().getModel("testFiles/wikipathways/WP550_73391.gpml"); - assertEquals(16, getWarnings().size()); + assertEquals(16, getWarnings().size()); - Model model2 = serializeModelOverCellDesignerParser(model1); + Model model2 = serializeModelOverCellDesignerParser(model1); - assertEquals(0, mc.compare(model1, model2)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } @Test public void WP197_69902Test() throws Exception { - try { - Model model1 = new GPMLToModel().getModel("testFiles/wikipathways/WP197_69902.gpml"); + Model model1 = new GPMLToModel().getModel("testFiles/wikipathways/WP197_69902.gpml"); - assertEquals(3, getWarnings().size()); + assertEquals(3, getWarnings().size()); - Model model2 = serializeModelOverCellDesignerParser(model1); + Model model2 = serializeModelOverCellDesignerParser(model1); - assertEquals(0, mc.compare(model1, model2)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } @Test public void WP179_70629Test() throws Exception { - try { - Model model1 = new GPMLToModel().getModel("testFiles/wikipathways/WP179_70629.gpml"); + Model model1 = new GPMLToModel().getModel("testFiles/wikipathways/WP179_70629.gpml"); - assertEquals(38, getWarnings().size()); + assertEquals(38, getWarnings().size()); - Model model2 = serializeModelOverCellDesignerParser(model1); + Model model2 = serializeModelOverCellDesignerParser(model1); - assertEquals(0, mc.compare(model1, model2)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } @Test public void WP306_71714Test() throws Exception { - try { - Model model1 = new GPMLToModel().getModel("testFiles/wikipathways/WP306_71714.gpml"); + Model model1 = new GPMLToModel().getModel("testFiles/wikipathways/WP306_71714.gpml"); - assertEquals(41, getWarnings().size()); + assertEquals(41, getWarnings().size()); - Model model2 = serializeModelOverCellDesignerParser(model1); + Model model2 = serializeModelOverCellDesignerParser(model1); - assertEquals(0, mc.compare(model1, model2)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } @Test public void WP481_72080Test() throws Exception { - try { - Model model1 = new GPMLToModel().getModel("testFiles/wikipathways/WP481_72080.gpml"); + Model model1 = new GPMLToModel().getModel("testFiles/wikipathways/WP481_72080.gpml"); - assertEquals(22, getWarnings().size()); + assertEquals(22, getWarnings().size()); - Model model2 = serializeModelOverCellDesignerParser(model1); + Model model2 = serializeModelOverCellDesignerParser(model1); - assertEquals(0, mc.compare(model1, model2)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } @Test public void testTwoReactants() throws Exception { - try { - Model model1 = new GPMLToModel().getModel("testFiles/small/two_reactant.gpml"); + Model model1 = new GPMLToModel().getModel("testFiles/small/two_reactant.gpml"); - assertEquals(0, getWarnings().size()); + assertEquals(0, getWarnings().size()); - Model model2 = serializeModelOverCellDesignerParser(model1); + Model model2 = serializeModelOverCellDesignerParser(model1); - assertEquals(0, mc.compare(model1, model2)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } @Test public void testTwoPubmeds() throws Exception { - try { - Model model1 = new GPMLToModel().getModel("testFiles/small/reaction_with_two_pubmeds.gpml"); - assertEquals(2, model1.getReactions().iterator().next().getMiriamData().size()); + Model model1 = new GPMLToModel().getModel("testFiles/small/reaction_with_two_pubmeds.gpml"); + assertEquals(2, model1.getReactions().iterator().next().getMiriamData().size()); - assertEquals(0, getWarnings().size()); + assertEquals(0, getWarnings().size()); - Model model2 = serializeModelOverCellDesignerParser(model1); + Model model2 = serializeModelOverCellDesignerParser(model1); - assertEquals(0, mc.compare(model1, model2)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } @Test public void testComment() throws Exception { - try { - Model model1 = new GPMLToModel().getModel("testFiles/small/comment.gpml"); - assertTrue(model1.getNotes().contains("Metabolic Process")); + Model model1 = new GPMLToModel().getModel("testFiles/small/comment.gpml"); + assertTrue(model1.getNotes().contains("Metabolic Process")); - assertEquals(0, getWarnings().size()); + assertEquals(0, getWarnings().size()); - Model model2 = serializeModelOverCellDesignerParser(model1); + Model model2 = serializeModelOverCellDesignerParser(model1); - assertEquals(0, mc.compare(model1, model2)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } @Test public void testGstp() throws Exception { - try { - Model model1 = new GPMLToModel().getModel("testFiles/wikipathways/gstp.gpml"); + Model model1 = new GPMLToModel().getModel("testFiles/wikipathways/gstp.gpml"); - assertEquals(3, getWarnings().size()); + assertEquals(3, getWarnings().size()); - Model model2 = serializeModelOverCellDesignerParser(model1); + Model model2 = serializeModelOverCellDesignerParser(model1); - assertEquals(0, mc.compare(model1, model2)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } @Test public void testMissingAliasesInCompartment() throws Exception { - try { - Model model1 = new GPMLToModel().getModel("testFiles/small/missing_aliases_in_compartment.gpml"); + Model model1 = new GPMLToModel().getModel("testFiles/small/missing_aliases_in_compartment.gpml"); - assertEquals(3, getWarnings().size()); + assertEquals(3, getWarnings().size()); - Model model2 = serializeModelOverCellDesignerParser(model1); + Model model2 = serializeModelOverCellDesignerParser(model1); - assertEquals(0, mc.compare(model1, model2)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } @Test public void testModelLines() throws Exception { - try { - Model model1 = new GPMLToModel().getModel("testFiles/small/model_with_line.gpml"); + Model model1 = new GPMLToModel().getModel("testFiles/small/model_with_line.gpml"); - assertEquals(0, getWarnings().size()); + assertEquals(0, getWarnings().size()); - assertEquals(1, model1.getLayers().iterator().next().getLines().size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(1, model1.getLayers().iterator().next().getLines().size()); } @Test public void testModelShapes() throws Exception { - try { - new GPMLToModel().getModel("testFiles/small/shapes.gpml"); - - assertEquals(11, getWarnings().size()); + new GPMLToModel().getModel("testFiles/small/shapes.gpml"); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(11, getWarnings().size()); } @Test public void testHypotheticlaComplex() throws Exception { - try { - Model model = new GPMLToModel().getModel("testFiles/complex/hypothetical_complex.gpml"); - for (Complex species : model.getComplexList()) { - assertTrue("Complex parsed from gpml should be hypothetical", species.isHypothetical()); - } - - assertEquals(0, getWarnings().size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; + Model model = new GPMLToModel().getModel("testFiles/complex/hypothetical_complex.gpml"); + for (Complex species : model.getComplexList()) { + assertTrue("Complex parsed from gpml should be hypothetical", species.isHypothetical()); } + + assertEquals(0, getWarnings().size()); } @Test public void testNonHypotheticlaComplex() throws Exception { - try { - String fileName = "testFiles/complex/nonhypothetical_complex.gpml"; - Model model = new GPMLToModel().getModel(fileName); - for (Complex species : model.getComplexList()) { - assertFalse("Complex parsed from gpml should be hypothetical", species.isHypothetical()); - } - assertEquals(0, getWarnings().size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; + String fileName = "testFiles/complex/nonhypothetical_complex.gpml"; + Model model = new GPMLToModel().getModel(fileName); + for (Complex species : model.getComplexList()) { + assertFalse("Complex parsed from gpml should be hypothetical", species.isHypothetical()); } + assertEquals(0, getWarnings().size()); } @Test public void testComplexName() throws Exception { - try { - String fileName = "testFiles/complex/complex_with_name.gpml"; - Model model = new GPMLToModel().getModel(fileName); - boolean nameFound = false; - for (Complex species : model.getComplexList()) { - if ("p70 S6 Kinases".equals(species.getName())) { - nameFound = true; - } + String fileName = "testFiles/complex/complex_with_name.gpml"; + Model model = new GPMLToModel().getModel(fileName); + boolean nameFound = false; + for (Complex species : model.getComplexList()) { + if ("p70 S6 Kinases".equals(species.getName())) { + nameFound = true; } - assertTrue("Complex parsed from gpml should have a valid name", nameFound); - assertEquals(1, getWarnings().size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; } + assertTrue("Complex parsed from gpml should have a valid name", nameFound); + assertEquals(1, getWarnings().size()); } @Test public void testCompartmentName() throws Exception { - try { - String fileName = "testFiles/compartment/compartment_name.gpml"; - Model model = new GPMLToModel().getModel(fileName); - for (Compartment compartment : model.getCompartments()) { - assertEquals("Compartment parsed from gpml should have a valid name", "Label", compartment.getName()); - } - assertEquals(0, getWarnings().size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; + String fileName = "testFiles/compartment/compartment_name.gpml"; + Model model = new GPMLToModel().getModel(fileName); + for (Compartment compartment : model.getCompartments()) { + assertEquals("Compartment parsed from gpml should have a valid name", "Label", compartment.getName()); } + assertEquals(0, getWarnings().size()); } @Test public void testComplexInCompartment() throws Exception { - try { - String fileName = "testFiles/compartment/complex_in_compartment.gpml"; - Model model1 = new GPMLToModel().getModel(fileName); + String fileName = "testFiles/compartment/complex_in_compartment.gpml"; + Model model1 = new GPMLToModel().getModel(fileName); - Model model2 = serializeModelOverCellDesignerParser(model1); + Model model2 = serializeModelOverCellDesignerParser(model1); - assertEquals(0, mc.compare(model1, model2)); + assertEquals(0, mc.compare(model1, model2)); - assertEquals(2, getWarnings().size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(2, getWarnings().size()); } @Test public void testReactionToComplex() throws Exception { - try { - String fileName = "testFiles/small/reaction_to_complex.gpml"; - Model model1 = new GPMLToModel().getModel(fileName); + String fileName = "testFiles/small/reaction_to_complex.gpml"; + Model model1 = new GPMLToModel().getModel(fileName); - Model model2 = serializeModelOverCellDesignerParser(model1); + Model model2 = serializeModelOverCellDesignerParser(model1); - assertEquals(0, mc.compare(model1, model2)); + assertEquals(0, mc.compare(model1, model2)); - assertEquals(54, getWarnings().size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(54, getWarnings().size()); } @Test public void testColorfullComplexReaction() throws Exception { - try { - String fileName = "testFiles/reactions/complex_color_reaction.gpml"; - Model model1 = new GPMLToModel().getModel(fileName); + String fileName = "testFiles/reactions/complex_color_reaction.gpml"; + Model model1 = new GPMLToModel().getModel(fileName); - Model model2 = serializeModelOverCellDesignerParser(model1); + Model model2 = serializeModelOverCellDesignerParser(model1); - assertEquals(0, mc.compare(model1, model2)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } @Test public void testColorfullComplexReaction2() throws Exception { - try { - String fileName = "testFiles/reactions/complex_color_reaction2.gpml"; - Model model1 = new GPMLToModel().getModel(fileName); + String fileName = "testFiles/reactions/complex_color_reaction2.gpml"; + Model model1 = new GPMLToModel().getModel(fileName); - Model model2 = serializeModelOverCellDesignerParser(model1); + Model model2 = serializeModelOverCellDesignerParser(model1); - assertEquals(0, mc.compare(model1, model2)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } @Test public void testProteinWithModification() throws Exception { - try { - String fileName = "testFiles/small/protein_with_modification.gpml"; - Model model1 = new GPMLToModel().getModel(fileName); - - Gene protein = (Gene) model1.getElementByElementId("be3de"); - assertNotNull(protein); - assertEquals(2, protein.getModificationResidues().size()); + String fileName = "testFiles/small/protein_with_modification.gpml"; + Model model1 = new GPMLToModel().getModel(fileName); - Model model2 = serializeModelOverCellDesignerParser(model1); + Gene protein = (Gene) model1.getElementByElementId("be3de"); + assertNotNull(protein); + assertEquals(2, protein.getModificationResidues().size()); - assertEquals(0, mc.compare(model1, model2)); + Model model2 = serializeModelOverCellDesignerParser(model1); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } @Test public void testProteinWithModification2() throws Exception { - try { - String fileName = "testFiles/small/protein_with_modification_2.gpml"; - Model model1 = new GPMLToModel().getModel(fileName); - - Gene protein = (Gene) model1.getElementByElementId("be3de"); - assertNotNull(protein); - assertEquals(2, protein.getModificationResidues().size()); + String fileName = "testFiles/small/protein_with_modification_2.gpml"; + Model model1 = new GPMLToModel().getModel(fileName); - Model model2 = serializeModelOverCellDesignerParser(model1); + Gene protein = (Gene) model1.getElementByElementId("be3de"); + assertNotNull(protein); + assertEquals(2, protein.getModificationResidues().size()); - assertEquals(0, mc.compare(model1, model2)); + Model model2 = serializeModelOverCellDesignerParser(model1); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } @Test public void testModifierPosition() throws Exception { - try { - String fileName = "testFiles/small/modifier_misaligned.gpml"; - Model model1 = new GPMLToModel().getModel(fileName); - - Reaction reaction = model1.getReactions().iterator().next(); + String fileName = "testFiles/small/modifier_misaligned.gpml"; + Model model1 = new GPMLToModel().getModel(fileName); - Line2D centerLine = reaction.getLine().getLines().get(reaction.getLine().getLines().size() / 2); - double distance = pt.getPointOnLine(centerLine.getP1(), centerLine.getP2(), 0.5) - .distance(reaction.getModifiers().get(0).getLine().getEndPoint()); - assertTrue("Modifier is too far from center point: " + distance, - distance < ReactionCellDesignerConverter.RECT_SIZE); + Reaction reaction = model1.getReactions().iterator().next(); - assertEquals(1, getWarnings().size()); + Line2D centerLine = reaction.getLine().getLines().get(reaction.getLine().getLines().size() / 2); + double distance = pt.getPointOnLine(centerLine.getP1(), centerLine.getP2(), 0.5) + .distance(reaction.getModifiers().get(0).getLine().getEndPoint()); + assertTrue("Modifier is too far from center point: " + distance, + distance < ReactionCellDesignerConverter.RECT_SIZE); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(1, getWarnings().size()); } @Test public void testReactionToLabel() throws Exception { - try { - String fileName = "testFiles/small/reaction_to_label.gpml"; - Model model1 = new GPMLToModel().getModel(fileName); + String fileName = "testFiles/small/reaction_to_label.gpml"; + Model model1 = new GPMLToModel().getModel(fileName); - assertEquals(1, getWarnings().size()); + assertEquals(1, getWarnings().size()); - assertEquals(1, model1.getReactions().size()); + assertEquals(1, model1.getReactions().size()); - Model model2 = serializeModelOverCellDesignerParser(model1); + Model model2 = serializeModelOverCellDesignerParser(model1); - assertEquals(0, mc.compare(model1, model2)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } @Test public void testModifierAsLabel() throws Exception { - try { - String fileName = "testFiles/small/modifier_to_label.gpml"; - Model model1 = new GPMLToModel().getModel(fileName); + String fileName = "testFiles/small/modifier_to_label.gpml"; + Model model1 = new GPMLToModel().getModel(fileName); - assertEquals(1, model1.getReactions().size()); - assertEquals(3, model1.getReactions().iterator().next().getNodes().size()); + assertEquals(1, model1.getReactions().size()); + assertEquals(3, model1.getReactions().iterator().next().getNodes().size()); - assertEquals(1, getWarnings().size()); + assertEquals(1, getWarnings().size()); - Model model2 = serializeModelOverCellDesignerParser(model1); + Model model2 = serializeModelOverCellDesignerParser(model1); - assertEquals(0, mc.compare(model1, model2)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } @Test public void testModifierAdsLabel() throws Exception { - try { - String fileName = "testFiles/small/protein_with_state.gpml"; - Model model1 = new GPMLToModel().getModel(fileName); + String fileName = "testFiles/small/protein_with_state.gpml"; + Model model1 = new GPMLToModel().getModel(fileName); - Protein protein = (Protein) model1.getElementsByName("Protein").get(0); - assertEquals(0, protein.getModificationResidues().size()); - assertEquals("GTP", protein.getStructuralState()); + Protein protein = (Protein) model1.getElementsByName("Protein").get(0); + assertEquals(0, protein.getModificationResidues().size()); + assertEquals("GTP", protein.getStructuralState()); - Model model2 = serializeModelOverCellDesignerParser(model1); + Model model2 = serializeModelOverCellDesignerParser(model1); - assertEquals(0, mc.compare(model1, model2)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } } diff --git a/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/ReactionElbowsTest.java b/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/ReactionElbowsTest.java index 05cdc8265a0bfc6c77a384a66544393da77d643c..097555f416a17b871355c3a356bc47384cfc98e2 100644 --- a/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/ReactionElbowsTest.java +++ b/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/ReactionElbowsTest.java @@ -1,11 +1,11 @@ package lcsb.mapviewer.wikipathway; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.Assert.*; import java.awt.geom.Line2D; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.junit.Test; import lcsb.mapviewer.model.map.model.Model; @@ -26,796 +26,650 @@ public class ReactionElbowsTest extends WikipathwaysTestFunctions { @Test public void LineReactionNorthToNorth() throws Exception { - try { - String fileName = "testFiles/elbow/elbow_line_n_n.gpml"; - Model model1 = new GPMLToModel().getModel(fileName); + String fileName = "testFiles/elbow/elbow_line_n_n.gpml"; + Model model1 = new GPMLToModel().getModel(fileName); - assertEquals(1, model1.getReactions().size()); + assertEquals(1, model1.getReactions().size()); - Reaction reaction = model1.getReactions().iterator().next(); + Reaction reaction = model1.getReactions().iterator().next(); - int lines = 0; - for (AbstractNode node : reaction.getNodes()) { - for (Line2D line : node.getLine().getLines()) { - assertTrue("Lines should be horizontal or vertical, but found: " + line.getP1() + " - " + line.getP2(), - isHvLine(line)); - lines++; - } + int lines = 0; + for (AbstractNode node : reaction.getNodes()) { + for (Line2D line : node.getLine().getLines()) { + assertTrue("Lines should be horizontal or vertical, but found: " + line.getP1() + " - " + line.getP2(), + isHvLine(line)); + lines++; } + } - assertEquals(5, lines); - - assertEquals(1, getWarnings().size()); + assertEquals(5, lines); - Model model2 = serializeModelOverCellDesignerParser(model1); + assertEquals(1, getWarnings().size()); - assertEquals(0, mc.compare(model1, model2)); + Model model2 = serializeModelOverCellDesignerParser(model1); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } @Test public void LineReactionNorthToEast() throws Exception { - try { - String fileName = "testFiles/elbow/elbow_line_n_e.gpml"; - Model model1 = new GPMLToModel().getModel(fileName); + String fileName = "testFiles/elbow/elbow_line_n_e.gpml"; + Model model1 = new GPMLToModel().getModel(fileName); - assertEquals(1, model1.getReactions().size()); + assertEquals(1, model1.getReactions().size()); - Reaction reaction = model1.getReactions().iterator().next(); + Reaction reaction = model1.getReactions().iterator().next(); - int lines = 0; - for (AbstractNode node : reaction.getNodes()) { - for (Line2D line : node.getLine().getLines()) { - assertTrue("Lines should be horizontal or vertical, but found: " + line.getP1() + " - " + line.getP2(), - isHvLine(line)); - lines++; - } + int lines = 0; + for (AbstractNode node : reaction.getNodes()) { + for (Line2D line : node.getLine().getLines()) { + assertTrue("Lines should be horizontal or vertical, but found: " + line.getP1() + " - " + line.getP2(), + isHvLine(line)); + lines++; } + } - assertEquals(6, lines); - - assertEquals(1, getWarnings().size()); + assertEquals(6, lines); - Model model2 = serializeModelOverCellDesignerParser(model1); + assertEquals(1, getWarnings().size()); - assertEquals(0, mc.compare(model1, model2)); + Model model2 = serializeModelOverCellDesignerParser(model1); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } @Test public void LineReactionNorthToEast2() throws Exception { - try { - String fileName = "testFiles/elbow/elbow_line_n_e_2.gpml"; - Model model1 = new GPMLToModel().getModel(fileName); + String fileName = "testFiles/elbow/elbow_line_n_e_2.gpml"; + Model model1 = new GPMLToModel().getModel(fileName); - assertEquals(1, model1.getReactions().size()); + assertEquals(1, model1.getReactions().size()); - Reaction reaction = model1.getReactions().iterator().next(); + Reaction reaction = model1.getReactions().iterator().next(); - int lines = 0; - for (AbstractNode node : reaction.getNodes()) { - for (Line2D line : node.getLine().getLines()) { - assertTrue("Lines should be horizontal or vertical, but found: " + line.getP1() + " - " + line.getP2(), - isHvLine(line)); - lines++; - } + int lines = 0; + for (AbstractNode node : reaction.getNodes()) { + for (Line2D line : node.getLine().getLines()) { + assertTrue("Lines should be horizontal or vertical, but found: " + line.getP1() + " - " + line.getP2(), + isHvLine(line)); + lines++; } + } - assertEquals(4, lines); - - assertEquals(1, getWarnings().size()); + assertEquals(4, lines); - Model model2 = serializeModelOverCellDesignerParser(model1); + assertEquals(1, getWarnings().size()); - assertEquals(0, mc.compare(model1, model2)); + Model model2 = serializeModelOverCellDesignerParser(model1); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } @Test public void LineReactionNorthToSouth() throws Exception { - try { - String fileName = "testFiles/elbow/elbow_line_n_s.gpml"; - Model model1 = new GPMLToModel().getModel(fileName); + String fileName = "testFiles/elbow/elbow_line_n_s.gpml"; + Model model1 = new GPMLToModel().getModel(fileName); - assertEquals(1, model1.getReactions().size()); + assertEquals(1, model1.getReactions().size()); - Reaction reaction = model1.getReactions().iterator().next(); + Reaction reaction = model1.getReactions().iterator().next(); - int lines = 0; - for (AbstractNode node : reaction.getNodes()) { - for (Line2D line : node.getLine().getLines()) { - assertTrue("Lines should be horizontal or vertical, but found: " + line.getP1() + " - " + line.getP2(), - isHvLine(line)); - lines++; - } + int lines = 0; + for (AbstractNode node : reaction.getNodes()) { + for (Line2D line : node.getLine().getLines()) { + assertTrue("Lines should be horizontal or vertical, but found: " + line.getP1() + " - " + line.getP2(), + isHvLine(line)); + lines++; } + } - assertEquals(7, lines); - - assertEquals(1, getWarnings().size()); + assertEquals(7, lines); - Model model2 = serializeModelOverCellDesignerParser(model1); + assertEquals(1, getWarnings().size()); - assertEquals(0, mc.compare(model1, model2)); + Model model2 = serializeModelOverCellDesignerParser(model1); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } @Test public void LineReactionNorthToWest() throws Exception { - try { - String fileName = "testFiles/elbow/elbow_line_n_w.gpml"; - Model model1 = new GPMLToModel().getModel(fileName); + String fileName = "testFiles/elbow/elbow_line_n_w.gpml"; + Model model1 = new GPMLToModel().getModel(fileName); - assertEquals(1, model1.getReactions().size()); + assertEquals(1, model1.getReactions().size()); - Reaction reaction = model1.getReactions().iterator().next(); + Reaction reaction = model1.getReactions().iterator().next(); - int lines = 0; - for (AbstractNode node : reaction.getNodes()) { - for (Line2D line : node.getLine().getLines()) { - assertTrue("Lines should be horizontal or vertical, but found: " + line.getP1() + " - " + line.getP2(), - isHvLine(line)); - lines++; - } + int lines = 0; + for (AbstractNode node : reaction.getNodes()) { + for (Line2D line : node.getLine().getLines()) { + assertTrue("Lines should be horizontal or vertical, but found: " + line.getP1() + " - " + line.getP2(), + isHvLine(line)); + lines++; } + } - assertEquals(6, lines); - - assertEquals(1, getWarnings().size()); + assertEquals(6, lines); - Model model2 = serializeModelOverCellDesignerParser(model1); + assertEquals(1, getWarnings().size()); - logger.debug(model1.getIdModel()); - logger.debug(model2.getIdModel()); - assertEquals(0, mc.compare(model1, model2)); + Model model2 = serializeModelOverCellDesignerParser(model1); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } @Test public void LineReactionNorthToWest2() throws Exception { - try { - String fileName = "testFiles/elbow/elbow_line_n_w_2.gpml"; - Model model1 = new GPMLToModel().getModel(fileName); + String fileName = "testFiles/elbow/elbow_line_n_w_2.gpml"; + Model model1 = new GPMLToModel().getModel(fileName); - assertEquals(1, model1.getReactions().size()); + assertEquals(1, model1.getReactions().size()); - Reaction reaction = model1.getReactions().iterator().next(); + Reaction reaction = model1.getReactions().iterator().next(); - int lines = 0; - for (AbstractNode node : reaction.getNodes()) { - for (Line2D line : node.getLine().getLines()) { - assertTrue("Lines should be horizontal or vertical, but found: " + line.getP1() + " - " + line.getP2(), - isHvLine(line)); - lines++; - } + int lines = 0; + for (AbstractNode node : reaction.getNodes()) { + for (Line2D line : node.getLine().getLines()) { + assertTrue("Lines should be horizontal or vertical, but found: " + line.getP1() + " - " + line.getP2(), + isHvLine(line)); + lines++; } + } - assertEquals(4, lines); - - assertEquals(1, getWarnings().size()); + assertEquals(4, lines); - Model model2 = serializeModelOverCellDesignerParser(model1); + assertEquals(1, getWarnings().size()); - assertEquals(0, mc.compare(model1, model2)); + Model model2 = serializeModelOverCellDesignerParser(model1); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } @Test public void LineReactionEastToNorth() throws Exception { - try { - String fileName = "testFiles/elbow/elbow_line_e_n.gpml"; - Model model1 = new GPMLToModel().getModel(fileName); + String fileName = "testFiles/elbow/elbow_line_e_n.gpml"; + Model model1 = new GPMLToModel().getModel(fileName); - assertEquals(1, model1.getReactions().size()); + assertEquals(1, model1.getReactions().size()); - Reaction reaction = model1.getReactions().iterator().next(); + Reaction reaction = model1.getReactions().iterator().next(); - int lines = 0; - for (AbstractNode node : reaction.getNodes()) { - for (Line2D line : node.getLine().getLines()) { - assertTrue("Lines should be horizontal or vertical, but found: " + line.getP1() + " - " + line.getP2(), - isHvLine(line)); - lines++; - } + int lines = 0; + for (AbstractNode node : reaction.getNodes()) { + for (Line2D line : node.getLine().getLines()) { + assertTrue("Lines should be horizontal or vertical, but found: " + line.getP1() + " - " + line.getP2(), + isHvLine(line)); + lines++; } + } - assertEquals(4, lines); - - assertEquals(1, getWarnings().size()); + assertEquals(4, lines); - Model model2 = serializeModelOverCellDesignerParser(model1); + assertEquals(1, getWarnings().size()); - assertEquals(0, mc.compare(model1, model2)); + Model model2 = serializeModelOverCellDesignerParser(model1); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } @Test public void LineReactionEastToNorth2() throws Exception { - try { - String fileName = "testFiles/elbow/elbow_line_e_n_2.gpml"; - Model model1 = new GPMLToModel().getModel(fileName); + String fileName = "testFiles/elbow/elbow_line_e_n_2.gpml"; + Model model1 = new GPMLToModel().getModel(fileName); - assertEquals(1, model1.getReactions().size()); + assertEquals(1, model1.getReactions().size()); - Reaction reaction = model1.getReactions().iterator().next(); + Reaction reaction = model1.getReactions().iterator().next(); - int lines = 0; - for (AbstractNode node : reaction.getNodes()) { - for (Line2D line : node.getLine().getLines()) { - assertTrue("Lines should be horizontal or vertical, but found: " + line.getP1() + " - " + line.getP2(), - isHvLine(line)); - lines++; - } + int lines = 0; + for (AbstractNode node : reaction.getNodes()) { + for (Line2D line : node.getLine().getLines()) { + assertTrue("Lines should be horizontal or vertical, but found: " + line.getP1() + " - " + line.getP2(), + isHvLine(line)); + lines++; } + } - assertEquals(6, lines); - - assertEquals(1, getWarnings().size()); + assertEquals(6, lines); - Model model2 = serializeModelOverCellDesignerParser(model1); + assertEquals(1, getWarnings().size()); - assertEquals(0, mc.compare(model1, model2)); + Model model2 = serializeModelOverCellDesignerParser(model1); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } @Test public void LineReactionEastToEast() throws Exception { - try { - String fileName = "testFiles/elbow/elbow_line_e_e.gpml"; - Model model1 = new GPMLToModel().getModel(fileName); + String fileName = "testFiles/elbow/elbow_line_e_e.gpml"; + Model model1 = new GPMLToModel().getModel(fileName); - assertEquals(1, model1.getReactions().size()); + assertEquals(1, model1.getReactions().size()); - Reaction reaction = model1.getReactions().iterator().next(); + Reaction reaction = model1.getReactions().iterator().next(); - int lines = 0; - for (AbstractNode node : reaction.getNodes()) { - for (Line2D line : node.getLine().getLines()) { - assertTrue("Lines should be horizontal or vertical, but found: " + line.getP1() + " - " + line.getP2(), - isHvLine(line)); - lines++; - } + int lines = 0; + for (AbstractNode node : reaction.getNodes()) { + for (Line2D line : node.getLine().getLines()) { + assertTrue("Lines should be horizontal or vertical, but found: " + line.getP1() + " - " + line.getP2(), + isHvLine(line)); + lines++; } + } - assertEquals(5, lines); - - assertEquals(1, getWarnings().size()); + assertEquals(5, lines); - Model model2 = serializeModelOverCellDesignerParser(model1); + assertEquals(1, getWarnings().size()); - assertEquals(0, mc.compare(model1, model2)); + Model model2 = serializeModelOverCellDesignerParser(model1); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } @Test public void LineReactionEastToSouth() throws Exception { - try { - String fileName = "testFiles/elbow/elbow_line_e_s.gpml"; - Model model1 = new GPMLToModel().getModel(fileName); + String fileName = "testFiles/elbow/elbow_line_e_s.gpml"; + Model model1 = new GPMLToModel().getModel(fileName); - assertEquals(1, model1.getReactions().size()); + assertEquals(1, model1.getReactions().size()); - Reaction reaction = model1.getReactions().iterator().next(); + Reaction reaction = model1.getReactions().iterator().next(); - int lines = 0; - for (AbstractNode node : reaction.getNodes()) { - for (Line2D line : node.getLine().getLines()) { - assertTrue("Lines should be horizontal or vertical, but found: " + line.getP1() + " - " + line.getP2(), - isHvLine(line)); - lines++; - } + int lines = 0; + for (AbstractNode node : reaction.getNodes()) { + for (Line2D line : node.getLine().getLines()) { + assertTrue("Lines should be horizontal or vertical, but found: " + line.getP1() + " - " + line.getP2(), + isHvLine(line)); + lines++; } + } - assertEquals(6, lines); - - assertEquals(1, getWarnings().size()); + assertEquals(6, lines); - Model model2 = serializeModelOverCellDesignerParser(model1); + assertEquals(1, getWarnings().size()); - assertEquals(0, mc.compare(model1, model2)); + Model model2 = serializeModelOverCellDesignerParser(model1); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } @Test public void LineReactionEastToSouth2() throws Exception { - try { - String fileName = "testFiles/elbow/elbow_line_e_s_2.gpml"; - Model model1 = new GPMLToModel().getModel(fileName); + String fileName = "testFiles/elbow/elbow_line_e_s_2.gpml"; + Model model1 = new GPMLToModel().getModel(fileName); - assertEquals(1, model1.getReactions().size()); + assertEquals(1, model1.getReactions().size()); - Reaction reaction = model1.getReactions().iterator().next(); + Reaction reaction = model1.getReactions().iterator().next(); - int lines = 0; - for (AbstractNode node : reaction.getNodes()) { - for (Line2D line : node.getLine().getLines()) { - assertTrue("Lines should be horizontal or vertical, but found: " + line.getP1() + " - " + line.getP2(), - isHvLine(line)); - lines++; - } + int lines = 0; + for (AbstractNode node : reaction.getNodes()) { + for (Line2D line : node.getLine().getLines()) { + assertTrue("Lines should be horizontal or vertical, but found: " + line.getP1() + " - " + line.getP2(), + isHvLine(line)); + lines++; } + } - assertEquals(4, lines); - - assertEquals(1, getWarnings().size()); + assertEquals(4, lines); - Model model2 = serializeModelOverCellDesignerParser(model1); + assertEquals(1, getWarnings().size()); - assertEquals(0, mc.compare(model1, model2)); + Model model2 = serializeModelOverCellDesignerParser(model1); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } @Test public void LineReactionEastToWest() throws Exception { - try { - String fileName = "testFiles/elbow/elbow_line_e_w.gpml"; - Model model1 = new GPMLToModel().getModel(fileName); + String fileName = "testFiles/elbow/elbow_line_e_w.gpml"; + Model model1 = new GPMLToModel().getModel(fileName); - assertEquals(1, model1.getReactions().size()); + assertEquals(1, model1.getReactions().size()); - Reaction reaction = model1.getReactions().iterator().next(); + Reaction reaction = model1.getReactions().iterator().next(); - int lines = 0; - for (AbstractNode node : reaction.getNodes()) { - for (Line2D line : node.getLine().getLines()) { - assertTrue("Lines should be horizontal or vertical, but found: " + line.getP1() + " - " + line.getP2(), - isHvLine(line)); - lines++; - } + int lines = 0; + for (AbstractNode node : reaction.getNodes()) { + for (Line2D line : node.getLine().getLines()) { + assertTrue("Lines should be horizontal or vertical, but found: " + line.getP1() + " - " + line.getP2(), + isHvLine(line)); + lines++; } + } - assertEquals(5, lines); - - assertEquals(1, getWarnings().size()); + assertEquals(5, lines); - Model model2 = serializeModelOverCellDesignerParser(model1); + assertEquals(1, getWarnings().size()); - assertEquals(0, mc.compare(model1, model2)); + Model model2 = serializeModelOverCellDesignerParser(model1); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } @Test public void LineReactionSouthToNorth() throws Exception { - try { - String fileName = "testFiles/elbow/elbow_line_s_n.gpml"; - Model model1 = new GPMLToModel().getModel(fileName); + String fileName = "testFiles/elbow/elbow_line_s_n.gpml"; + Model model1 = new GPMLToModel().getModel(fileName); - assertEquals(1, model1.getReactions().size()); + assertEquals(1, model1.getReactions().size()); - Reaction reaction = model1.getReactions().iterator().next(); + Reaction reaction = model1.getReactions().iterator().next(); - int lines = 0; - for (AbstractNode node : reaction.getNodes()) { - for (Line2D line : node.getLine().getLines()) { - assertTrue("Lines should be horizontal or vertical, but found: " + line.getP1() + " - " + line.getP2(), - isHvLine(line)); - lines++; - } + int lines = 0; + for (AbstractNode node : reaction.getNodes()) { + for (Line2D line : node.getLine().getLines()) { + assertTrue("Lines should be horizontal or vertical, but found: " + line.getP1() + " - " + line.getP2(), + isHvLine(line)); + lines++; } + } - assertEquals(5, lines); - - assertEquals(1, getWarnings().size()); + assertEquals(5, lines); - Model model2 = serializeModelOverCellDesignerParser(model1); + assertEquals(1, getWarnings().size()); - assertEquals(0, mc.compare(model1, model2)); + Model model2 = serializeModelOverCellDesignerParser(model1); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } @Test public void LineReactionSouthToEast() throws Exception { - try { - String fileName = "testFiles/elbow/elbow_line_s_e.gpml"; - Model model1 = new GPMLToModel().getModel(fileName); + String fileName = "testFiles/elbow/elbow_line_s_e.gpml"; + Model model1 = new GPMLToModel().getModel(fileName); - assertEquals(1, model1.getReactions().size()); + assertEquals(1, model1.getReactions().size()); - Reaction reaction = model1.getReactions().iterator().next(); + Reaction reaction = model1.getReactions().iterator().next(); - int lines = 0; - for (AbstractNode node : reaction.getNodes()) { - for (Line2D line : node.getLine().getLines()) { - assertTrue("Lines should be horizontal or vertical, but found: " + line.getP1() + " - " + line.getP2(), - isHvLine(line)); - lines++; - } + int lines = 0; + for (AbstractNode node : reaction.getNodes()) { + for (Line2D line : node.getLine().getLines()) { + assertTrue("Lines should be horizontal or vertical, but found: " + line.getP1() + " - " + line.getP2(), + isHvLine(line)); + lines++; } + } - assertEquals(6, lines); - - assertEquals(1, getWarnings().size()); + assertEquals(6, lines); - Model model2 = serializeModelOverCellDesignerParser(model1); + assertEquals(1, getWarnings().size()); - assertEquals(0, mc.compare(model1, model2)); + Model model2 = serializeModelOverCellDesignerParser(model1); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } @Test public void LineReactionSouthToEast2() throws Exception { - try { - String fileName = "testFiles/elbow/elbow_line_s_e_2.gpml"; - Model model1 = new GPMLToModel().getModel(fileName); + String fileName = "testFiles/elbow/elbow_line_s_e_2.gpml"; + Model model1 = new GPMLToModel().getModel(fileName); - assertEquals(1, model1.getReactions().size()); + assertEquals(1, model1.getReactions().size()); - Reaction reaction = model1.getReactions().iterator().next(); + Reaction reaction = model1.getReactions().iterator().next(); - int lines = 0; - for (AbstractNode node : reaction.getNodes()) { - for (Line2D line : node.getLine().getLines()) { - assertTrue("Lines should be horizontal or vertical, but found: " + line.getP1() + " - " + line.getP2(), - isHvLine(line)); - lines++; - } + int lines = 0; + for (AbstractNode node : reaction.getNodes()) { + for (Line2D line : node.getLine().getLines()) { + assertTrue("Lines should be horizontal or vertical, but found: " + line.getP1() + " - " + line.getP2(), + isHvLine(line)); + lines++; } + } - assertEquals(4, lines); - - assertEquals(1, getWarnings().size()); + assertEquals(4, lines); - Model model2 = serializeModelOverCellDesignerParser(model1); + assertEquals(1, getWarnings().size()); - assertEquals(0, mc.compare(model1, model2)); + Model model2 = serializeModelOverCellDesignerParser(model1); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } @Test public void LineReactionSouthToSouth() throws Exception { - try { - String fileName = "testFiles/elbow/elbow_line_s_s.gpml"; - Model model1 = new GPMLToModel().getModel(fileName); + String fileName = "testFiles/elbow/elbow_line_s_s.gpml"; + Model model1 = new GPMLToModel().getModel(fileName); - assertEquals(1, model1.getReactions().size()); + assertEquals(1, model1.getReactions().size()); - Reaction reaction = model1.getReactions().iterator().next(); + Reaction reaction = model1.getReactions().iterator().next(); - int lines = 0; - for (AbstractNode node : reaction.getNodes()) { - for (Line2D line : node.getLine().getLines()) { - assertTrue("Lines should be horizontal or vertical, but found: " + line.getP1() + " - " + line.getP2(), - isHvLine(line)); - lines++; - } + int lines = 0; + for (AbstractNode node : reaction.getNodes()) { + for (Line2D line : node.getLine().getLines()) { + assertTrue("Lines should be horizontal or vertical, but found: " + line.getP1() + " - " + line.getP2(), + isHvLine(line)); + lines++; } + } - assertEquals(5, lines); - - assertEquals(1, getWarnings().size()); + assertEquals(5, lines); - Model model2 = serializeModelOverCellDesignerParser(model1); + assertEquals(1, getWarnings().size()); - assertEquals(0, mc.compare(model1, model2)); + Model model2 = serializeModelOverCellDesignerParser(model1); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } @Test public void LineReactionSouthToWest() throws Exception { - try { - String fileName = "testFiles/elbow/elbow_line_s_w.gpml"; - Model model1 = new GPMLToModel().getModel(fileName); + String fileName = "testFiles/elbow/elbow_line_s_w.gpml"; + Model model1 = new GPMLToModel().getModel(fileName); - assertEquals(1, model1.getReactions().size()); + assertEquals(1, model1.getReactions().size()); - Reaction reaction = model1.getReactions().iterator().next(); + Reaction reaction = model1.getReactions().iterator().next(); - int lines = 0; - for (AbstractNode node : reaction.getNodes()) { - for (Line2D line : node.getLine().getLines()) { - assertTrue("Lines should be horizontal or vertical, but found: " + line.getP1() + " - " + line.getP2(), - isHvLine(line)); - lines++; - } + int lines = 0; + for (AbstractNode node : reaction.getNodes()) { + for (Line2D line : node.getLine().getLines()) { + assertTrue("Lines should be horizontal or vertical, but found: " + line.getP1() + " - " + line.getP2(), + isHvLine(line)); + lines++; } + } - assertEquals(4, lines); - - assertEquals(1, getWarnings().size()); + assertEquals(4, lines); - Model model2 = serializeModelOverCellDesignerParser(model1); + assertEquals(1, getWarnings().size()); - assertEquals(0, mc.compare(model1, model2)); + Model model2 = serializeModelOverCellDesignerParser(model1); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } @Test public void LineReactionSouthToWest2() throws Exception { - try { - String fileName = "testFiles/elbow/elbow_line_s_w_2.gpml"; - Model model1 = new GPMLToModel().getModel(fileName); + String fileName = "testFiles/elbow/elbow_line_s_w_2.gpml"; + Model model1 = new GPMLToModel().getModel(fileName); - assertEquals(1, model1.getReactions().size()); + assertEquals(1, model1.getReactions().size()); - Reaction reaction = model1.getReactions().iterator().next(); + Reaction reaction = model1.getReactions().iterator().next(); - int lines = 0; - for (AbstractNode node : reaction.getNodes()) { - for (Line2D line : node.getLine().getLines()) { - assertTrue("Lines should be horizontal or vertical, but found: " + line.getP1() + " - " + line.getP2(), - isHvLine(line)); - lines++; - } + int lines = 0; + for (AbstractNode node : reaction.getNodes()) { + for (Line2D line : node.getLine().getLines()) { + assertTrue("Lines should be horizontal or vertical, but found: " + line.getP1() + " - " + line.getP2(), + isHvLine(line)); + lines++; } + } - assertEquals(6, lines); - - assertEquals(1, getWarnings().size()); + assertEquals(6, lines); - Model model2 = serializeModelOverCellDesignerParser(model1); + assertEquals(1, getWarnings().size()); - assertEquals(0, mc.compare(model1, model2)); + Model model2 = serializeModelOverCellDesignerParser(model1); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } @Test public void LineReactionWestToNorth() throws Exception { - try { - String fileName = "testFiles/elbow/elbow_line_w_n.gpml"; - Model model1 = new GPMLToModel().getModel(fileName); + String fileName = "testFiles/elbow/elbow_line_w_n.gpml"; + Model model1 = new GPMLToModel().getModel(fileName); - assertEquals(1, model1.getReactions().size()); + assertEquals(1, model1.getReactions().size()); - Reaction reaction = model1.getReactions().iterator().next(); + Reaction reaction = model1.getReactions().iterator().next(); - int lines = 0; - for (AbstractNode node : reaction.getNodes()) { - for (Line2D line : node.getLine().getLines()) { - assertTrue("Lines should be horizontal or vertical, but found: " + line.getP1() + " - " + line.getP2(), - isHvLine(line)); - lines++; - } + int lines = 0; + for (AbstractNode node : reaction.getNodes()) { + for (Line2D line : node.getLine().getLines()) { + assertTrue("Lines should be horizontal or vertical, but found: " + line.getP1() + " - " + line.getP2(), + isHvLine(line)); + lines++; } + } - assertEquals(6, lines); - - assertEquals(1, getWarnings().size()); + assertEquals(6, lines); - Model model2 = serializeModelOverCellDesignerParser(model1); + assertEquals(1, getWarnings().size()); - assertEquals(0, mc.compare(model1, model2)); + Model model2 = serializeModelOverCellDesignerParser(model1); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } @Test public void LineReactionWestToNorth2() throws Exception { - try { - String fileName = "testFiles/elbow/elbow_line_w_n_2.gpml"; - Model model1 = new GPMLToModel().getModel(fileName); + String fileName = "testFiles/elbow/elbow_line_w_n_2.gpml"; + Model model1 = new GPMLToModel().getModel(fileName); - assertEquals(1, model1.getReactions().size()); + assertEquals(1, model1.getReactions().size()); - Reaction reaction = model1.getReactions().iterator().next(); + Reaction reaction = model1.getReactions().iterator().next(); - int lines = 0; - for (AbstractNode node : reaction.getNodes()) { - for (Line2D line : node.getLine().getLines()) { - assertTrue("Lines should be horizontal or vertical, but found: " + line.getP1() + " - " + line.getP2(), - isHvLine(line)); - lines++; - } + int lines = 0; + for (AbstractNode node : reaction.getNodes()) { + for (Line2D line : node.getLine().getLines()) { + assertTrue("Lines should be horizontal or vertical, but found: " + line.getP1() + " - " + line.getP2(), + isHvLine(line)); + lines++; } + } - assertEquals(4, lines); - - assertEquals(1, getWarnings().size()); + assertEquals(4, lines); - Model model2 = serializeModelOverCellDesignerParser(model1); + assertEquals(1, getWarnings().size()); - assertEquals(0, mc.compare(model1, model2)); + Model model2 = serializeModelOverCellDesignerParser(model1); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } @Test public void LineReactionWestToEast() throws Exception { - try { - String fileName = "testFiles/elbow/elbow_line_w_e.gpml"; - Model model1 = new GPMLToModel().getModel(fileName); + String fileName = "testFiles/elbow/elbow_line_w_e.gpml"; + Model model1 = new GPMLToModel().getModel(fileName); - assertEquals(1, model1.getReactions().size()); + assertEquals(1, model1.getReactions().size()); - Reaction reaction = model1.getReactions().iterator().next(); + Reaction reaction = model1.getReactions().iterator().next(); - int lines = 0; - for (AbstractNode node : reaction.getNodes()) { - for (Line2D line : node.getLine().getLines()) { - assertTrue("Lines should be horizontal or vertical, but found: " + line.getP1() + " - " + line.getP2(), - isHvLine(line)); - lines++; - } + int lines = 0; + for (AbstractNode node : reaction.getNodes()) { + for (Line2D line : node.getLine().getLines()) { + assertTrue("Lines should be horizontal or vertical, but found: " + line.getP1() + " - " + line.getP2(), + isHvLine(line)); + lines++; } + } - assertEquals(7, lines); - - assertEquals(1, getWarnings().size()); + assertEquals(7, lines); - Model model2 = serializeModelOverCellDesignerParser(model1); + assertEquals(1, getWarnings().size()); - assertEquals(0, mc.compare(model1, model2)); + Model model2 = serializeModelOverCellDesignerParser(model1); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } @Test public void LineReactionWestToSouth() throws Exception { - try { - String fileName = "testFiles/elbow/elbow_line_w_s.gpml"; - Model model1 = new GPMLToModel().getModel(fileName); + String fileName = "testFiles/elbow/elbow_line_w_s.gpml"; + Model model1 = new GPMLToModel().getModel(fileName); - assertEquals(1, model1.getReactions().size()); + assertEquals(1, model1.getReactions().size()); - Reaction reaction = model1.getReactions().iterator().next(); + Reaction reaction = model1.getReactions().iterator().next(); - int lines = 0; - for (AbstractNode node : reaction.getNodes()) { - for (Line2D line : node.getLine().getLines()) { - assertTrue("Lines should be horizontal or vertical, but found: " + line.getP1() + " - " + line.getP2(), - isHvLine(line)); - lines++; - } + int lines = 0; + for (AbstractNode node : reaction.getNodes()) { + for (Line2D line : node.getLine().getLines()) { + assertTrue("Lines should be horizontal or vertical, but found: " + line.getP1() + " - " + line.getP2(), + isHvLine(line)); + lines++; } + } - assertEquals(6, lines); - - assertEquals(1, getWarnings().size()); + assertEquals(6, lines); - Model model2 = serializeModelOverCellDesignerParser(model1); + assertEquals(1, getWarnings().size()); - assertEquals(0, mc.compare(model1, model2)); + Model model2 = serializeModelOverCellDesignerParser(model1); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } @Test public void LineReactionWestToSouth2() throws Exception { - try { - String fileName = "testFiles/elbow/elbow_line_w_s_2.gpml"; - Model model1 = new GPMLToModel().getModel(fileName); + String fileName = "testFiles/elbow/elbow_line_w_s_2.gpml"; + Model model1 = new GPMLToModel().getModel(fileName); - assertEquals(1, model1.getReactions().size()); + assertEquals(1, model1.getReactions().size()); - Reaction reaction = model1.getReactions().iterator().next(); + Reaction reaction = model1.getReactions().iterator().next(); - int lines = 0; - for (AbstractNode node : reaction.getNodes()) { - for (Line2D line : node.getLine().getLines()) { - assertTrue("Lines should be horizontal or vertical, but found: " + line.getP1() + " - " + line.getP2(), - isHvLine(line)); - lines++; - } + int lines = 0; + for (AbstractNode node : reaction.getNodes()) { + for (Line2D line : node.getLine().getLines()) { + assertTrue("Lines should be horizontal or vertical, but found: " + line.getP1() + " - " + line.getP2(), + isHvLine(line)); + lines++; } + } - assertEquals(4, lines); - - assertEquals(1, getWarnings().size()); + assertEquals(4, lines); - Model model2 = serializeModelOverCellDesignerParser(model1); + assertEquals(1, getWarnings().size()); - assertEquals(0, mc.compare(model1, model2)); + Model model2 = serializeModelOverCellDesignerParser(model1); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } @Test public void LineReactionWestToWest() throws Exception { - try { - String fileName = "testFiles/elbow/elbow_line_w_w.gpml"; - Model model1 = new GPMLToModel().getModel(fileName); + String fileName = "testFiles/elbow/elbow_line_w_w.gpml"; + Model model1 = new GPMLToModel().getModel(fileName); - assertEquals(1, model1.getReactions().size()); + assertEquals(1, model1.getReactions().size()); - Reaction reaction = model1.getReactions().iterator().next(); + Reaction reaction = model1.getReactions().iterator().next(); - int lines = 0; - for (AbstractNode node : reaction.getNodes()) { - for (Line2D line : node.getLine().getLines()) { - assertTrue("Lines should be horizontal or vertical, but found: " + line.getP1() + " - " + line.getP2(), - isHvLine(line)); - lines++; - } + int lines = 0; + for (AbstractNode node : reaction.getNodes()) { + for (Line2D line : node.getLine().getLines()) { + assertTrue("Lines should be horizontal or vertical, but found: " + line.getP1() + " - " + line.getP2(), + isHvLine(line)); + lines++; } + } - assertEquals(5, lines); - - assertEquals(1, getWarnings().size()); + assertEquals(5, lines); - Model model2 = serializeModelOverCellDesignerParser(model1); + assertEquals(1, getWarnings().size()); - assertEquals(0, mc.compare(model1, model2)); + Model model2 = serializeModelOverCellDesignerParser(model1); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } private boolean isHvLine(Line2D line) { diff --git a/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/ReactionGpmlInputToModelTest.java b/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/ReactionGpmlInputToModelTest.java index d06b396d13c82b91d69bbfde1b9134eb0da83709..b0cafb8f6bb0bb44870d0bff5b662ee190f38762 100644 --- a/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/ReactionGpmlInputToModelTest.java +++ b/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/ReactionGpmlInputToModelTest.java @@ -1,1344 +1,1140 @@ package lcsb.mapviewer.wikipathway; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.junit.Assert.*; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.junit.Test; import lcsb.mapviewer.model.map.model.Model; import lcsb.mapviewer.model.map.model.ModelComparator; -import lcsb.mapviewer.model.map.modifier.Catalysis; -import lcsb.mapviewer.model.map.modifier.Inhibition; -import lcsb.mapviewer.model.map.modifier.Modulation; -import lcsb.mapviewer.model.map.modifier.PhysicalStimulation; -import lcsb.mapviewer.model.map.modifier.UnknownCatalysis; -import lcsb.mapviewer.model.map.modifier.UnknownInhibition; -import lcsb.mapviewer.model.map.reaction.Modifier; -import lcsb.mapviewer.model.map.reaction.Product; -import lcsb.mapviewer.model.map.reaction.Reactant; -import lcsb.mapviewer.model.map.reaction.Reaction; +import lcsb.mapviewer.model.map.modifier.*; +import lcsb.mapviewer.model.map.reaction.*; import lcsb.mapviewer.wikipathway.XML.GPMLToModel; public class ReactionGpmlInputToModelTest extends WikipathwaysTestFunctions { - /** - * Default class logger. - */ + static Logger logger = LogManager.getLogger(ReactionGpmlInputToModelTest.class); private ModelComparator mc = new ModelComparator(1.0); @Test public void LineInteractionInputTest() throws Exception { - try { - String fileName = "testFiles/reactions/interaction_line_input.gpml"; - - Model model1 = new GPMLToModel().getModel(fileName); + String fileName = "testFiles/reactions/interaction_line_input.gpml"; - assertEquals(1, model1.getReactions().size()); + Model model1 = new GPMLToModel().getModel(fileName); - Reaction reaction = model1.getReactions().iterator().next(); + assertEquals(1, model1.getReactions().size()); - Product product = null; - if (reaction.getProducts().size() > 1) { - product = reaction.getProducts().get(1); - } - Reactant reactant = null; - if (reaction.getReactants().size() > 1) { - reactant = reaction.getReactants().get(1); - } - Modifier modifier = null; - if (reaction.getModifiers().size() > 0) { - modifier = reaction.getModifiers().get(0); - assertTrue(modifier instanceof Modifier); - } + Reaction reaction = model1.getReactions().iterator().next(); - assertNotNull(reactant); - assertNull(product); - assertNull(modifier); + Product product = null; + if (reaction.getProducts().size() > 1) { + product = reaction.getProducts().get(1); + } + Reactant reactant = null; + if (reaction.getReactants().size() > 1) { + reactant = reaction.getReactants().get(1); + } + Modifier modifier = null; + if (reaction.getModifiers().size() > 0) { + modifier = reaction.getModifiers().get(0); + assertTrue(modifier instanceof Modifier); + } - assertEquals(0, getWarnings().size()); + assertNotNull(reactant); + assertNull(product); + assertNull(modifier); - Model model2 = serializeModelOverCellDesignerParser(model1); + assertEquals(0, getWarnings().size()); - assertEquals(0, mc.compare(model1, model2)); + Model model2 = serializeModelOverCellDesignerParser(model1); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } @Test public void ArrowInteractionInputTest() throws Exception { - try { - String fileName = "testFiles/reactions/interaction_arrow_input.gpml"; + String fileName = "testFiles/reactions/interaction_arrow_input.gpml"; - Model model1 = new GPMLToModel().getModel(fileName); + Model model1 = new GPMLToModel().getModel(fileName); - assertEquals(1, model1.getReactions().size()); + assertEquals(1, model1.getReactions().size()); - Reaction reaction = model1.getReactions().iterator().next(); + Reaction reaction = model1.getReactions().iterator().next(); - Product product = null; - if (reaction.getProducts().size() > 1) { - product = reaction.getProducts().get(1); - } - Reactant reactant = null; - if (reaction.getReactants().size() > 1) { - reactant = reaction.getReactants().get(1); - } - Modifier modifier = null; - if (reaction.getModifiers().size() > 0) { - modifier = reaction.getModifiers().get(0); - assertTrue(modifier instanceof Modulation); - } - - assertNull(reactant); - assertNull(product); - assertNotNull(modifier); + Product product = null; + if (reaction.getProducts().size() > 1) { + product = reaction.getProducts().get(1); + } + Reactant reactant = null; + if (reaction.getReactants().size() > 1) { + reactant = reaction.getReactants().get(1); + } + Modifier modifier = null; + if (reaction.getModifiers().size() > 0) { + modifier = reaction.getModifiers().get(0); + assertTrue(modifier instanceof Modulation); + } - assertEquals(1, getWarnings().size()); + assertNull(reactant); + assertNull(product); + assertNotNull(modifier); - Model model2 = serializeModelOverCellDesignerParser(model1); + assertEquals(1, getWarnings().size()); - assertEquals(0, mc.compare(model1, model2)); + Model model2 = serializeModelOverCellDesignerParser(model1); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } @Test public void DashedLineInteractionInputTest() throws Exception { - try { - String fileName = "testFiles/reactions/interaction_dashed_line_input.gpml"; + String fileName = "testFiles/reactions/interaction_dashed_line_input.gpml"; - Model model1 = new GPMLToModel().getModel(fileName); + Model model1 = new GPMLToModel().getModel(fileName); - assertEquals(1, model1.getReactions().size()); + assertEquals(1, model1.getReactions().size()); - Reaction reaction = model1.getReactions().iterator().next(); + Reaction reaction = model1.getReactions().iterator().next(); - Product product = null; - if (reaction.getProducts().size() > 1) { - product = reaction.getProducts().get(1); - } - Reactant reactant = null; - if (reaction.getReactants().size() > 1) { - reactant = reaction.getReactants().get(1); - } - Modifier modifier = null; - if (reaction.getModifiers().size() > 0) { - modifier = reaction.getModifiers().get(0); - assertTrue(modifier instanceof Modifier); - } - - assertNotNull(reactant); - assertNull(product); - assertNull(modifier); + Product product = null; + if (reaction.getProducts().size() > 1) { + product = reaction.getProducts().get(1); + } + Reactant reactant = null; + if (reaction.getReactants().size() > 1) { + reactant = reaction.getReactants().get(1); + } + Modifier modifier = null; + if (reaction.getModifiers().size() > 0) { + modifier = reaction.getModifiers().get(0); + assertTrue(modifier instanceof Modifier); + } - assertEquals(1, getWarnings().size()); + assertNotNull(reactant); + assertNull(product); + assertNull(modifier); - Model model2 = serializeModelOverCellDesignerParser(model1); + assertEquals(1, getWarnings().size()); - assertEquals(0, mc.compare(model1, model2)); + Model model2 = serializeModelOverCellDesignerParser(model1); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } @Test public void DashedArrowInteractionInputTest() throws Exception { - try { - String fileName = "testFiles/reactions/interaction_dashed_arrow_input.gpml"; + String fileName = "testFiles/reactions/interaction_dashed_arrow_input.gpml"; - Model model1 = new GPMLToModel().getModel(fileName); + Model model1 = new GPMLToModel().getModel(fileName); - assertEquals(1, model1.getReactions().size()); + assertEquals(1, model1.getReactions().size()); - Reaction reaction = model1.getReactions().iterator().next(); + Reaction reaction = model1.getReactions().iterator().next(); - Product product = null; - if (reaction.getProducts().size() > 1) { - product = reaction.getProducts().get(1); - } - Reactant reactant = null; - if (reaction.getReactants().size() > 1) { - reactant = reaction.getReactants().get(1); - } - Modifier modifier = null; - if (reaction.getModifiers().size() > 0) { - modifier = reaction.getModifiers().get(0); - assertTrue(modifier instanceof Modulation); - } - - assertNull(reactant); - assertNull(product); - assertNotNull(modifier); + Product product = null; + if (reaction.getProducts().size() > 1) { + product = reaction.getProducts().get(1); + } + Reactant reactant = null; + if (reaction.getReactants().size() > 1) { + reactant = reaction.getReactants().get(1); + } + Modifier modifier = null; + if (reaction.getModifiers().size() > 0) { + modifier = reaction.getModifiers().get(0); + assertTrue(modifier instanceof Modulation); + } - assertEquals(1, getWarnings().size()); + assertNull(reactant); + assertNull(product); + assertNotNull(modifier); - Model model2 = serializeModelOverCellDesignerParser(model1); + assertEquals(1, getWarnings().size()); - assertEquals(0, mc.compare(model1, model2)); + Model model2 = serializeModelOverCellDesignerParser(model1); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } @Test public void TBarInteractionInputTest() throws Exception { - try { - String fileName = "testFiles/reactions/interaction_tbar_input.gpml"; + String fileName = "testFiles/reactions/interaction_tbar_input.gpml"; - Model model1 = new GPMLToModel().getModel(fileName); + Model model1 = new GPMLToModel().getModel(fileName); - assertEquals(1, model1.getReactions().size()); + assertEquals(1, model1.getReactions().size()); - Reaction reaction = model1.getReactions().iterator().next(); + Reaction reaction = model1.getReactions().iterator().next(); - Product product = null; - if (reaction.getProducts().size() > 1) { - product = reaction.getProducts().get(1); - } - Reactant reactant = null; - if (reaction.getReactants().size() > 1) { - reactant = reaction.getReactants().get(1); - } - Modifier modifier = null; - if (reaction.getModifiers().size() > 0) { - modifier = reaction.getModifiers().get(0); - assertTrue(modifier instanceof Inhibition); - } - - assertNull(reactant); - assertNull(product); - assertNotNull(modifier); + Product product = null; + if (reaction.getProducts().size() > 1) { + product = reaction.getProducts().get(1); + } + Reactant reactant = null; + if (reaction.getReactants().size() > 1) { + reactant = reaction.getReactants().get(1); + } + Modifier modifier = null; + if (reaction.getModifiers().size() > 0) { + modifier = reaction.getModifiers().get(0); + assertTrue(modifier instanceof Inhibition); + } - assertEquals(0, getWarnings().size()); + assertNull(reactant); + assertNull(product); + assertNotNull(modifier); - Model model2 = serializeModelOverCellDesignerParser(model1); + assertEquals(0, getWarnings().size()); - assertEquals(0, mc.compare(model1, model2)); + Model model2 = serializeModelOverCellDesignerParser(model1); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } @Test public void NecessaryStimulationInteractionInputTest() throws Exception { - try { - String fileName = "testFiles/reactions/interaction_mim_necessary_stimulation_input.gpml"; + String fileName = "testFiles/reactions/interaction_mim_necessary_stimulation_input.gpml"; - Model model1 = new GPMLToModel().getModel(fileName); + Model model1 = new GPMLToModel().getModel(fileName); - assertEquals(1, model1.getReactions().size()); + assertEquals(1, model1.getReactions().size()); - Reaction reaction = model1.getReactions().iterator().next(); + Reaction reaction = model1.getReactions().iterator().next(); - Product product = null; - if (reaction.getProducts().size() > 1) { - product = reaction.getProducts().get(1); - } - Reactant reactant = null; - if (reaction.getReactants().size() > 1) { - reactant = reaction.getReactants().get(1); - } - Modifier modifier = null; - if (reaction.getModifiers().size() > 0) { - modifier = reaction.getModifiers().get(0); - assertTrue(modifier instanceof PhysicalStimulation); - } - - assertNull(reactant); - assertNull(product); - assertNotNull(modifier); + Product product = null; + if (reaction.getProducts().size() > 1) { + product = reaction.getProducts().get(1); + } + Reactant reactant = null; + if (reaction.getReactants().size() > 1) { + reactant = reaction.getReactants().get(1); + } + Modifier modifier = null; + if (reaction.getModifiers().size() > 0) { + modifier = reaction.getModifiers().get(0); + assertTrue(modifier instanceof PhysicalStimulation); + } - assertEquals(0, getWarnings().size()); + assertNull(reactant); + assertNull(product); + assertNotNull(modifier); - Model model2 = serializeModelOverCellDesignerParser(model1); + assertEquals(0, getWarnings().size()); - assertEquals(0, mc.compare(model1, model2)); + Model model2 = serializeModelOverCellDesignerParser(model1); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } @Test public void BindingInteractionInputTest() throws Exception { - try { - String fileName = "testFiles/reactions/interaction_mim_binding_input.gpml"; + String fileName = "testFiles/reactions/interaction_mim_binding_input.gpml"; - Model model1 = new GPMLToModel().getModel(fileName); + Model model1 = new GPMLToModel().getModel(fileName); - assertEquals(1, model1.getReactions().size()); + assertEquals(1, model1.getReactions().size()); - Reaction reaction = model1.getReactions().iterator().next(); + Reaction reaction = model1.getReactions().iterator().next(); - Product product = null; - if (reaction.getProducts().size() > 1) { - product = reaction.getProducts().get(1); - } - Reactant reactant = null; - if (reaction.getReactants().size() > 1) { - reactant = reaction.getReactants().get(1); - } - Modifier modifier = null; - if (reaction.getModifiers().size() > 0) { - modifier = reaction.getModifiers().get(0); - assertTrue(modifier instanceof Modulation); - } - - assertNull(reactant); - assertNull(product); - assertNotNull(modifier); + Product product = null; + if (reaction.getProducts().size() > 1) { + product = reaction.getProducts().get(1); + } + Reactant reactant = null; + if (reaction.getReactants().size() > 1) { + reactant = reaction.getReactants().get(1); + } + Modifier modifier = null; + if (reaction.getModifiers().size() > 0) { + modifier = reaction.getModifiers().get(0); + assertTrue(modifier instanceof Modulation); + } - assertEquals(1, getWarnings().size()); + assertNull(reactant); + assertNull(product); + assertNotNull(modifier); - Model model2 = serializeModelOverCellDesignerParser(model1); + assertEquals(1, getWarnings().size()); - assertEquals(0, mc.compare(model1, model2)); + Model model2 = serializeModelOverCellDesignerParser(model1); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } @Test public void ConversionInteractionInputTest() throws Exception { - try { - String fileName = "testFiles/reactions/interaction_mim_conversion_input.gpml"; + String fileName = "testFiles/reactions/interaction_mim_conversion_input.gpml"; - Model model1 = new GPMLToModel().getModel(fileName); + Model model1 = new GPMLToModel().getModel(fileName); - assertEquals(1, model1.getReactions().size()); + assertEquals(1, model1.getReactions().size()); - Reaction reaction = model1.getReactions().iterator().next(); + Reaction reaction = model1.getReactions().iterator().next(); - Product product = null; - if (reaction.getProducts().size() > 1) { - product = reaction.getProducts().get(1); - } - Reactant reactant = null; - if (reaction.getReactants().size() > 1) { - reactant = reaction.getReactants().get(1); - } - Modifier modifier = null; - if (reaction.getModifiers().size() > 0) { - modifier = reaction.getModifiers().get(0); - assertTrue(modifier instanceof Modulation); - } - - assertNull(reactant); - assertNull(product); - assertNotNull(modifier); + Product product = null; + if (reaction.getProducts().size() > 1) { + product = reaction.getProducts().get(1); + } + Reactant reactant = null; + if (reaction.getReactants().size() > 1) { + reactant = reaction.getReactants().get(1); + } + Modifier modifier = null; + if (reaction.getModifiers().size() > 0) { + modifier = reaction.getModifiers().get(0); + assertTrue(modifier instanceof Modulation); + } - assertEquals(1, getWarnings().size()); + assertNull(reactant); + assertNull(product); + assertNotNull(modifier); - Model model2 = serializeModelOverCellDesignerParser(model1); + assertEquals(1, getWarnings().size()); - assertEquals(0, mc.compare(model1, model2)); + Model model2 = serializeModelOverCellDesignerParser(model1); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } @Test public void StimulationInteractionInputTest() throws Exception { - try { - String fileName = "testFiles/reactions/interaction_mim_stimulation_input.gpml"; + String fileName = "testFiles/reactions/interaction_mim_stimulation_input.gpml"; - Model model1 = new GPMLToModel().getModel(fileName); + Model model1 = new GPMLToModel().getModel(fileName); - assertEquals(1, model1.getReactions().size()); + assertEquals(1, model1.getReactions().size()); - Reaction reaction = model1.getReactions().iterator().next(); + Reaction reaction = model1.getReactions().iterator().next(); - Product product = null; - if (reaction.getProducts().size() > 1) { - product = reaction.getProducts().get(1); - } - Reactant reactant = null; - if (reaction.getReactants().size() > 1) { - reactant = reaction.getReactants().get(1); - } - Modifier modifier = null; - if (reaction.getModifiers().size() > 0) { - modifier = reaction.getModifiers().get(0); - assertTrue(modifier instanceof PhysicalStimulation); - } - - assertNull(reactant); - assertNull(product); - assertNotNull(modifier); + Product product = null; + if (reaction.getProducts().size() > 1) { + product = reaction.getProducts().get(1); + } + Reactant reactant = null; + if (reaction.getReactants().size() > 1) { + reactant = reaction.getReactants().get(1); + } + Modifier modifier = null; + if (reaction.getModifiers().size() > 0) { + modifier = reaction.getModifiers().get(0); + assertTrue(modifier instanceof PhysicalStimulation); + } - assertEquals(0, getWarnings().size()); + assertNull(reactant); + assertNull(product); + assertNotNull(modifier); - Model model2 = serializeModelOverCellDesignerParser(model1); + assertEquals(0, getWarnings().size()); - assertEquals(0, mc.compare(model1, model2)); + Model model2 = serializeModelOverCellDesignerParser(model1); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } @Test public void ModificationInteractionInputTest() throws Exception { - try { - String fileName = "testFiles/reactions/interaction_mim_modification_input.gpml"; + String fileName = "testFiles/reactions/interaction_mim_modification_input.gpml"; - Model model1 = new GPMLToModel().getModel(fileName); + Model model1 = new GPMLToModel().getModel(fileName); - assertEquals(1, model1.getReactions().size()); + assertEquals(1, model1.getReactions().size()); - Reaction reaction = model1.getReactions().iterator().next(); + Reaction reaction = model1.getReactions().iterator().next(); - Product product = null; - if (reaction.getProducts().size() > 1) { - product = reaction.getProducts().get(1); - } - Reactant reactant = null; - if (reaction.getReactants().size() > 1) { - reactant = reaction.getReactants().get(1); - } - Modifier modifier = null; - if (reaction.getModifiers().size() > 0) { - modifier = reaction.getModifiers().get(0); - assertTrue(modifier instanceof Modulation); - } - - assertNull(reactant); - assertNull(product); - assertNotNull(modifier); + Product product = null; + if (reaction.getProducts().size() > 1) { + product = reaction.getProducts().get(1); + } + Reactant reactant = null; + if (reaction.getReactants().size() > 1) { + reactant = reaction.getReactants().get(1); + } + Modifier modifier = null; + if (reaction.getModifiers().size() > 0) { + modifier = reaction.getModifiers().get(0); + assertTrue(modifier instanceof Modulation); + } - assertEquals(0, getWarnings().size()); + assertNull(reactant); + assertNull(product); + assertNotNull(modifier); - Model model2 = serializeModelOverCellDesignerParser(model1); + assertEquals(0, getWarnings().size()); - assertEquals(0, mc.compare(model1, model2)); + Model model2 = serializeModelOverCellDesignerParser(model1); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } @Test public void CatalystInteractionInputTest() throws Exception { - try { - String fileName = "testFiles/reactions/interaction_mim_catalyst_input.gpml"; + String fileName = "testFiles/reactions/interaction_mim_catalyst_input.gpml"; - Model model1 = new GPMLToModel().getModel(fileName); + Model model1 = new GPMLToModel().getModel(fileName); - assertEquals(1, model1.getReactions().size()); + assertEquals(1, model1.getReactions().size()); - Reaction reaction = model1.getReactions().iterator().next(); + Reaction reaction = model1.getReactions().iterator().next(); - Product product = null; - if (reaction.getProducts().size() > 1) { - product = reaction.getProducts().get(1); - } - Reactant reactant = null; - if (reaction.getReactants().size() > 1) { - reactant = reaction.getReactants().get(1); - } - Modifier modifier = null; - if (reaction.getModifiers().size() > 0) { - modifier = reaction.getModifiers().get(0); - assertTrue(modifier instanceof Catalysis); - } - - assertNull(reactant); - assertNull(product); - assertNotNull(modifier); + Product product = null; + if (reaction.getProducts().size() > 1) { + product = reaction.getProducts().get(1); + } + Reactant reactant = null; + if (reaction.getReactants().size() > 1) { + reactant = reaction.getReactants().get(1); + } + Modifier modifier = null; + if (reaction.getModifiers().size() > 0) { + modifier = reaction.getModifiers().get(0); + assertTrue(modifier instanceof Catalysis); + } - assertEquals(0, getWarnings().size()); + assertNull(reactant); + assertNull(product); + assertNotNull(modifier); - Model model2 = serializeModelOverCellDesignerParser(model1); + assertEquals(0, getWarnings().size()); - assertEquals(0, mc.compare(model1, model2)); + Model model2 = serializeModelOverCellDesignerParser(model1); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } @Test public void InhibitionInteractionInputTest() throws Exception { - try { - String fileName = "testFiles/reactions/interaction_mim_inhibition_input.gpml"; + String fileName = "testFiles/reactions/interaction_mim_inhibition_input.gpml"; - Model model1 = new GPMLToModel().getModel(fileName); + Model model1 = new GPMLToModel().getModel(fileName); - assertEquals(1, model1.getReactions().size()); + assertEquals(1, model1.getReactions().size()); - Reaction reaction = model1.getReactions().iterator().next(); + Reaction reaction = model1.getReactions().iterator().next(); - Product product = null; - if (reaction.getProducts().size() > 1) { - product = reaction.getProducts().get(1); - } - Reactant reactant = null; - if (reaction.getReactants().size() > 1) { - reactant = reaction.getReactants().get(1); - } - Modifier modifier = null; - if (reaction.getModifiers().size() > 0) { - modifier = reaction.getModifiers().get(0); - assertTrue(modifier instanceof Inhibition); - } - - assertNull(reactant); - assertNull(product); - assertNotNull(modifier); + Product product = null; + if (reaction.getProducts().size() > 1) { + product = reaction.getProducts().get(1); + } + Reactant reactant = null; + if (reaction.getReactants().size() > 1) { + reactant = reaction.getReactants().get(1); + } + Modifier modifier = null; + if (reaction.getModifiers().size() > 0) { + modifier = reaction.getModifiers().get(0); + assertTrue(modifier instanceof Inhibition); + } - assertEquals(0, getWarnings().size()); + assertNull(reactant); + assertNull(product); + assertNotNull(modifier); - Model model2 = serializeModelOverCellDesignerParser(model1); + assertEquals(0, getWarnings().size()); - assertEquals(0, mc.compare(model1, model2)); + Model model2 = serializeModelOverCellDesignerParser(model1); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } @Test public void CleavageInteractionInputTest() throws Exception { - try { - String fileName = "testFiles/reactions/interaction_mim_cleavage_input.gpml"; + String fileName = "testFiles/reactions/interaction_mim_cleavage_input.gpml"; - Model model1 = new GPMLToModel().getModel(fileName); + Model model1 = new GPMLToModel().getModel(fileName); - assertEquals(1, model1.getReactions().size()); + assertEquals(1, model1.getReactions().size()); - Reaction reaction = model1.getReactions().iterator().next(); + Reaction reaction = model1.getReactions().iterator().next(); - Product product = null; - if (reaction.getProducts().size() > 1) { - product = reaction.getProducts().get(1); - } - Reactant reactant = null; - if (reaction.getReactants().size() > 1) { - reactant = reaction.getReactants().get(1); - } - Modifier modifier = null; - if (reaction.getModifiers().size() > 0) { - modifier = reaction.getModifiers().get(0); - assertTrue(modifier instanceof Modulation); - } - - assertNull(reactant); - assertNull(product); - assertNotNull(modifier); + Product product = null; + if (reaction.getProducts().size() > 1) { + product = reaction.getProducts().get(1); + } + Reactant reactant = null; + if (reaction.getReactants().size() > 1) { + reactant = reaction.getReactants().get(1); + } + Modifier modifier = null; + if (reaction.getModifiers().size() > 0) { + modifier = reaction.getModifiers().get(0); + assertTrue(modifier instanceof Modulation); + } - assertEquals(1, getWarnings().size()); + assertNull(reactant); + assertNull(product); + assertNotNull(modifier); - Model model2 = serializeModelOverCellDesignerParser(model1); + assertEquals(1, getWarnings().size()); - assertEquals(0, mc.compare(model1, model2)); + Model model2 = serializeModelOverCellDesignerParser(model1); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } @Test public void CovalentBondInteractionInputTest() throws Exception { - try { - String fileName = "testFiles/reactions/interaction_mim_covalent_bond_input.gpml"; + String fileName = "testFiles/reactions/interaction_mim_covalent_bond_input.gpml"; - Model model1 = new GPMLToModel().getModel(fileName); + Model model1 = new GPMLToModel().getModel(fileName); - assertEquals(1, model1.getReactions().size()); + assertEquals(1, model1.getReactions().size()); - Reaction reaction = model1.getReactions().iterator().next(); + Reaction reaction = model1.getReactions().iterator().next(); - Product product = null; - if (reaction.getProducts().size() > 1) { - product = reaction.getProducts().get(1); - } - Reactant reactant = null; - if (reaction.getReactants().size() > 1) { - reactant = reaction.getReactants().get(1); - } - Modifier modifier = null; - if (reaction.getModifiers().size() > 0) { - modifier = reaction.getModifiers().get(0); - assertTrue(modifier instanceof Modifier); - } - - assertNotNull(reactant); - assertNull(product); - assertNull(modifier); + Product product = null; + if (reaction.getProducts().size() > 1) { + product = reaction.getProducts().get(1); + } + Reactant reactant = null; + if (reaction.getReactants().size() > 1) { + reactant = reaction.getReactants().get(1); + } + Modifier modifier = null; + if (reaction.getModifiers().size() > 0) { + modifier = reaction.getModifiers().get(0); + assertTrue(modifier instanceof Modifier); + } - assertEquals(1, getWarnings().size()); + assertNotNull(reactant); + assertNull(product); + assertNull(modifier); - Model model2 = serializeModelOverCellDesignerParser(model1); + assertEquals(1, getWarnings().size()); - assertEquals(0, mc.compare(model1, model2)); + Model model2 = serializeModelOverCellDesignerParser(model1); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } @Test public void BranchingLeftInteractionInputTest() throws Exception { - try { - String fileName = "testFiles/reactions/interaction_mim_branching_left_input.gpml"; + String fileName = "testFiles/reactions/interaction_mim_branching_left_input.gpml"; - Model model1 = new GPMLToModel().getModel(fileName); + Model model1 = new GPMLToModel().getModel(fileName); - assertEquals(1, model1.getReactions().size()); + assertEquals(1, model1.getReactions().size()); - Reaction reaction = model1.getReactions().iterator().next(); + Reaction reaction = model1.getReactions().iterator().next(); - Product product = null; - if (reaction.getProducts().size() > 1) { - product = reaction.getProducts().get(1); - } - Reactant reactant = null; - if (reaction.getReactants().size() > 1) { - reactant = reaction.getReactants().get(1); - } - Modifier modifier = null; - if (reaction.getModifiers().size() > 0) { - modifier = reaction.getModifiers().get(0); - assertTrue(modifier instanceof Modifier); - } - - assertNotNull(reactant); - assertNull(product); - assertNull(modifier); + Product product = null; + if (reaction.getProducts().size() > 1) { + product = reaction.getProducts().get(1); + } + Reactant reactant = null; + if (reaction.getReactants().size() > 1) { + reactant = reaction.getReactants().get(1); + } + Modifier modifier = null; + if (reaction.getModifiers().size() > 0) { + modifier = reaction.getModifiers().get(0); + assertTrue(modifier instanceof Modifier); + } - assertEquals(0, getWarnings().size()); + assertNotNull(reactant); + assertNull(product); + assertNull(modifier); - Model model2 = serializeModelOverCellDesignerParser(model1); + assertEquals(0, getWarnings().size()); - assertEquals(0, mc.compare(model1, model2)); + Model model2 = serializeModelOverCellDesignerParser(model1); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } @Test public void BranchingRightInteractionInputTest() throws Exception { - try { - String fileName = "testFiles/reactions/interaction_mim_branching_right_input.gpml"; + String fileName = "testFiles/reactions/interaction_mim_branching_right_input.gpml"; - Model model1 = new GPMLToModel().getModel(fileName); + Model model1 = new GPMLToModel().getModel(fileName); - assertEquals(1, model1.getReactions().size()); + assertEquals(1, model1.getReactions().size()); - Reaction reaction = model1.getReactions().iterator().next(); + Reaction reaction = model1.getReactions().iterator().next(); - Product product = null; - if (reaction.getProducts().size() > 1) { - product = reaction.getProducts().get(1); - } - Reactant reactant = null; - if (reaction.getReactants().size() > 1) { - reactant = reaction.getReactants().get(1); - } - Modifier modifier = null; - if (reaction.getModifiers().size() > 0) { - modifier = reaction.getModifiers().get(0); - assertTrue(modifier instanceof Modifier); - } - - assertNotNull(reactant); - assertNull(product); - assertNull(modifier); + Product product = null; + if (reaction.getProducts().size() > 1) { + product = reaction.getProducts().get(1); + } + Reactant reactant = null; + if (reaction.getReactants().size() > 1) { + reactant = reaction.getReactants().get(1); + } + Modifier modifier = null; + if (reaction.getModifiers().size() > 0) { + modifier = reaction.getModifiers().get(0); + assertTrue(modifier instanceof Modifier); + } - assertEquals(0, getWarnings().size()); + assertNotNull(reactant); + assertNull(product); + assertNull(modifier); - Model model2 = serializeModelOverCellDesignerParser(model1); + assertEquals(0, getWarnings().size()); - assertEquals(0, mc.compare(model1, model2)); + Model model2 = serializeModelOverCellDesignerParser(model1); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } @Test public void TranscriptionTranslationInteractionInputTest() throws Exception { - try { - String fileName = "testFiles/reactions/interaction_mim_transcription_translation_input.gpml"; + String fileName = "testFiles/reactions/interaction_mim_transcription_translation_input.gpml"; - Model model1 = new GPMLToModel().getModel(fileName); + Model model1 = new GPMLToModel().getModel(fileName); - assertEquals(1, model1.getReactions().size()); + assertEquals(1, model1.getReactions().size()); - Reaction reaction = model1.getReactions().iterator().next(); + Reaction reaction = model1.getReactions().iterator().next(); - Product product = null; - if (reaction.getProducts().size() > 1) { - product = reaction.getProducts().get(1); - } - Reactant reactant = null; - if (reaction.getReactants().size() > 1) { - reactant = reaction.getReactants().get(1); - } - Modifier modifier = null; - if (reaction.getModifiers().size() > 0) { - modifier = reaction.getModifiers().get(0); - assertTrue(modifier instanceof Modulation); - } - - assertNull(reactant); - assertNull(product); - assertNotNull(modifier); + Product product = null; + if (reaction.getProducts().size() > 1) { + product = reaction.getProducts().get(1); + } + Reactant reactant = null; + if (reaction.getReactants().size() > 1) { + reactant = reaction.getReactants().get(1); + } + Modifier modifier = null; + if (reaction.getModifiers().size() > 0) { + modifier = reaction.getModifiers().get(0); + assertTrue(modifier instanceof Modulation); + } - assertEquals(1, getWarnings().size()); + assertNull(reactant); + assertNull(product); + assertNotNull(modifier); - Model model2 = serializeModelOverCellDesignerParser(model1); + assertEquals(1, getWarnings().size()); - assertEquals(0, mc.compare(model1, model2)); + Model model2 = serializeModelOverCellDesignerParser(model1); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } @Test public void GapInteractionInputTest() throws Exception { - try { - String fileName = "testFiles/reactions/interaction_mim_gap_input.gpml"; + String fileName = "testFiles/reactions/interaction_mim_gap_input.gpml"; - Model model1 = new GPMLToModel().getModel(fileName); + Model model1 = new GPMLToModel().getModel(fileName); - assertEquals(1, model1.getReactions().size()); + assertEquals(1, model1.getReactions().size()); - Reaction reaction = model1.getReactions().iterator().next(); + Reaction reaction = model1.getReactions().iterator().next(); - Product product = null; - if (reaction.getProducts().size() > 1) { - product = reaction.getProducts().get(1); - } - Reactant reactant = null; - if (reaction.getReactants().size() > 1) { - reactant = reaction.getReactants().get(1); - } - Modifier modifier = null; - if (reaction.getModifiers().size() > 0) { - modifier = reaction.getModifiers().get(0); - assertTrue(modifier instanceof Modulation); - } - - assertNull(reactant); - assertNull(product); - assertNotNull(modifier); + Product product = null; + if (reaction.getProducts().size() > 1) { + product = reaction.getProducts().get(1); + } + Reactant reactant = null; + if (reaction.getReactants().size() > 1) { + reactant = reaction.getReactants().get(1); + } + Modifier modifier = null; + if (reaction.getModifiers().size() > 0) { + modifier = reaction.getModifiers().get(0); + assertTrue(modifier instanceof Modulation); + } - assertEquals(1, getWarnings().size()); + assertNull(reactant); + assertNull(product); + assertNotNull(modifier); - Model model2 = serializeModelOverCellDesignerParser(model1); + assertEquals(1, getWarnings().size()); - assertEquals(0, mc.compare(model1, model2)); + Model model2 = serializeModelOverCellDesignerParser(model1); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } @Test public void TBarInteractionDashedInputTest() throws Exception { - try { - String fileName = "testFiles/reactions/interaction_dashed_tbar_input.gpml"; + String fileName = "testFiles/reactions/interaction_dashed_tbar_input.gpml"; - Model model1 = new GPMLToModel().getModel(fileName); + Model model1 = new GPMLToModel().getModel(fileName); - assertEquals(1, model1.getReactions().size()); + assertEquals(1, model1.getReactions().size()); - Reaction reaction = model1.getReactions().iterator().next(); + Reaction reaction = model1.getReactions().iterator().next(); - Product product = null; - if (reaction.getProducts().size() > 1) { - product = reaction.getProducts().get(1); - } - Reactant reactant = null; - if (reaction.getReactants().size() > 1) { - reactant = reaction.getReactants().get(1); - } - Modifier modifier = null; - if (reaction.getModifiers().size() > 0) { - modifier = reaction.getModifiers().get(0); - assertTrue(modifier instanceof UnknownInhibition); - } - - assertNull(reactant); - assertNull(product); - assertNotNull(modifier); + Product product = null; + if (reaction.getProducts().size() > 1) { + product = reaction.getProducts().get(1); + } + Reactant reactant = null; + if (reaction.getReactants().size() > 1) { + reactant = reaction.getReactants().get(1); + } + Modifier modifier = null; + if (reaction.getModifiers().size() > 0) { + modifier = reaction.getModifiers().get(0); + assertTrue(modifier instanceof UnknownInhibition); + } - assertEquals(1, getWarnings().size()); + assertNull(reactant); + assertNull(product); + assertNotNull(modifier); - Model model2 = serializeModelOverCellDesignerParser(model1); + assertEquals(1, getWarnings().size()); - assertEquals(0, mc.compare(model1, model2)); + Model model2 = serializeModelOverCellDesignerParser(model1); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } @Test public void NecessaryStimulationInteractionDashedInputTest() throws Exception { - try { - String fileName = "testFiles/reactions/interaction_dashed_mim_necessary_stimulation_input.gpml"; + String fileName = "testFiles/reactions/interaction_dashed_mim_necessary_stimulation_input.gpml"; - Model model1 = new GPMLToModel().getModel(fileName); + Model model1 = new GPMLToModel().getModel(fileName); - assertEquals(1, model1.getReactions().size()); + assertEquals(1, model1.getReactions().size()); - Reaction reaction = model1.getReactions().iterator().next(); + Reaction reaction = model1.getReactions().iterator().next(); - Product product = null; - if (reaction.getProducts().size() > 1) { - product = reaction.getProducts().get(1); - } - Reactant reactant = null; - if (reaction.getReactants().size() > 1) { - reactant = reaction.getReactants().get(1); - } - Modifier modifier = null; - if (reaction.getModifiers().size() > 0) { - modifier = reaction.getModifiers().get(0); - assertTrue(modifier instanceof Modulation); - } - - assertNull(reactant); - assertNull(product); - assertNotNull(modifier); + Product product = null; + if (reaction.getProducts().size() > 1) { + product = reaction.getProducts().get(1); + } + Reactant reactant = null; + if (reaction.getReactants().size() > 1) { + reactant = reaction.getReactants().get(1); + } + Modifier modifier = null; + if (reaction.getModifiers().size() > 0) { + modifier = reaction.getModifiers().get(0); + assertTrue(modifier instanceof Modulation); + } - assertEquals(2, getWarnings().size()); + assertNull(reactant); + assertNull(product); + assertNotNull(modifier); - Model model2 = serializeModelOverCellDesignerParser(model1); + assertEquals(2, getWarnings().size()); - assertEquals(0, mc.compare(model1, model2)); + Model model2 = serializeModelOverCellDesignerParser(model1); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } @Test public void BindingInteractionDashedInputTest() throws Exception { - try { - String fileName = "testFiles/reactions/interaction_dashed_mim_binding_input.gpml"; + String fileName = "testFiles/reactions/interaction_dashed_mim_binding_input.gpml"; - Model model1 = new GPMLToModel().getModel(fileName); + Model model1 = new GPMLToModel().getModel(fileName); - assertEquals(1, model1.getReactions().size()); + assertEquals(1, model1.getReactions().size()); - Reaction reaction = model1.getReactions().iterator().next(); + Reaction reaction = model1.getReactions().iterator().next(); - Product product = null; - if (reaction.getProducts().size() > 1) { - product = reaction.getProducts().get(1); - } - Reactant reactant = null; - if (reaction.getReactants().size() > 1) { - reactant = reaction.getReactants().get(1); - } - Modifier modifier = null; - if (reaction.getModifiers().size() > 0) { - modifier = reaction.getModifiers().get(0); - assertTrue(modifier instanceof Modulation); - } - - assertNull(reactant); - assertNull(product); - assertNotNull(modifier); + Product product = null; + if (reaction.getProducts().size() > 1) { + product = reaction.getProducts().get(1); + } + Reactant reactant = null; + if (reaction.getReactants().size() > 1) { + reactant = reaction.getReactants().get(1); + } + Modifier modifier = null; + if (reaction.getModifiers().size() > 0) { + modifier = reaction.getModifiers().get(0); + assertTrue(modifier instanceof Modulation); + } - assertEquals(2, getWarnings().size()); + assertNull(reactant); + assertNull(product); + assertNotNull(modifier); - Model model2 = serializeModelOverCellDesignerParser(model1); + assertEquals(2, getWarnings().size()); - assertEquals(0, mc.compare(model1, model2)); + Model model2 = serializeModelOverCellDesignerParser(model1); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } @Test public void ConversionInteractionDashedInputTest() throws Exception { - try { - String fileName = "testFiles/reactions/interaction_dashed_mim_conversion_input.gpml"; + String fileName = "testFiles/reactions/interaction_dashed_mim_conversion_input.gpml"; - Model model1 = new GPMLToModel().getModel(fileName); + Model model1 = new GPMLToModel().getModel(fileName); - assertEquals(1, model1.getReactions().size()); + assertEquals(1, model1.getReactions().size()); - Reaction reaction = model1.getReactions().iterator().next(); + Reaction reaction = model1.getReactions().iterator().next(); - Product product = null; - if (reaction.getProducts().size() > 1) { - product = reaction.getProducts().get(1); - } - Reactant reactant = null; - if (reaction.getReactants().size() > 1) { - reactant = reaction.getReactants().get(1); - } - Modifier modifier = null; - if (reaction.getModifiers().size() > 0) { - modifier = reaction.getModifiers().get(0); - assertTrue(modifier instanceof Modulation); - } - - assertNull(reactant); - assertNull(product); - assertNotNull(modifier); + Product product = null; + if (reaction.getProducts().size() > 1) { + product = reaction.getProducts().get(1); + } + Reactant reactant = null; + if (reaction.getReactants().size() > 1) { + reactant = reaction.getReactants().get(1); + } + Modifier modifier = null; + if (reaction.getModifiers().size() > 0) { + modifier = reaction.getModifiers().get(0); + assertTrue(modifier instanceof Modulation); + } - assertEquals(2, getWarnings().size()); + assertNull(reactant); + assertNull(product); + assertNotNull(modifier); - Model model2 = serializeModelOverCellDesignerParser(model1); + assertEquals(2, getWarnings().size()); - assertEquals(0, mc.compare(model1, model2)); + Model model2 = serializeModelOverCellDesignerParser(model1); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } @Test public void StimulationInteractionDashedInputTest() throws Exception { - try { - String fileName = "testFiles/reactions/interaction_dashed_mim_stimulation_input.gpml"; + String fileName = "testFiles/reactions/interaction_dashed_mim_stimulation_input.gpml"; - Model model1 = new GPMLToModel().getModel(fileName); + Model model1 = new GPMLToModel().getModel(fileName); - assertEquals(1, model1.getReactions().size()); + assertEquals(1, model1.getReactions().size()); - Reaction reaction = model1.getReactions().iterator().next(); + Reaction reaction = model1.getReactions().iterator().next(); - Product product = null; - if (reaction.getProducts().size() > 1) { - product = reaction.getProducts().get(1); - } - Reactant reactant = null; - if (reaction.getReactants().size() > 1) { - reactant = reaction.getReactants().get(1); - } - Modifier modifier = null; - if (reaction.getModifiers().size() > 0) { - modifier = reaction.getModifiers().get(0); - assertTrue(modifier instanceof Modulation); - } - - assertNull(reactant); - assertNull(product); - assertNotNull(modifier); + Product product = null; + if (reaction.getProducts().size() > 1) { + product = reaction.getProducts().get(1); + } + Reactant reactant = null; + if (reaction.getReactants().size() > 1) { + reactant = reaction.getReactants().get(1); + } + Modifier modifier = null; + if (reaction.getModifiers().size() > 0) { + modifier = reaction.getModifiers().get(0); + assertTrue(modifier instanceof Modulation); + } - assertEquals(2, getWarnings().size()); + assertNull(reactant); + assertNull(product); + assertNotNull(modifier); - Model model2 = serializeModelOverCellDesignerParser(model1); + assertEquals(2, getWarnings().size()); - assertEquals(0, mc.compare(model1, model2)); + Model model2 = serializeModelOverCellDesignerParser(model1); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } @Test public void ModificationInteractionDashedInputTest() throws Exception { - try { - String fileName = "testFiles/reactions/interaction_dashed_mim_modification_input.gpml"; + String fileName = "testFiles/reactions/interaction_dashed_mim_modification_input.gpml"; - Model model1 = new GPMLToModel().getModel(fileName); + Model model1 = new GPMLToModel().getModel(fileName); - assertEquals(1, model1.getReactions().size()); + assertEquals(1, model1.getReactions().size()); - Reaction reaction = model1.getReactions().iterator().next(); + Reaction reaction = model1.getReactions().iterator().next(); - Product product = null; - if (reaction.getProducts().size() > 1) { - product = reaction.getProducts().get(1); - } - Reactant reactant = null; - if (reaction.getReactants().size() > 1) { - reactant = reaction.getReactants().get(1); - } - Modifier modifier = null; - if (reaction.getModifiers().size() > 0) { - modifier = reaction.getModifiers().get(0); - assertTrue(modifier instanceof Modulation); - } - - assertNull(reactant); - assertNull(product); - assertNotNull(modifier); + Product product = null; + if (reaction.getProducts().size() > 1) { + product = reaction.getProducts().get(1); + } + Reactant reactant = null; + if (reaction.getReactants().size() > 1) { + reactant = reaction.getReactants().get(1); + } + Modifier modifier = null; + if (reaction.getModifiers().size() > 0) { + modifier = reaction.getModifiers().get(0); + assertTrue(modifier instanceof Modulation); + } - assertEquals(2, getWarnings().size()); + assertNull(reactant); + assertNull(product); + assertNotNull(modifier); - Model model2 = serializeModelOverCellDesignerParser(model1); + assertEquals(2, getWarnings().size()); - assertEquals(0, mc.compare(model1, model2)); + Model model2 = serializeModelOverCellDesignerParser(model1); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } @Test public void CatalystInteractionDashedInputTest() throws Exception { - try { - String fileName = "testFiles/reactions/interaction_dashed_mim_catalyst_input.gpml"; + String fileName = "testFiles/reactions/interaction_dashed_mim_catalyst_input.gpml"; - Model model1 = new GPMLToModel().getModel(fileName); + Model model1 = new GPMLToModel().getModel(fileName); - assertEquals(1, model1.getReactions().size()); + assertEquals(1, model1.getReactions().size()); - Reaction reaction = model1.getReactions().iterator().next(); + Reaction reaction = model1.getReactions().iterator().next(); - Product product = null; - if (reaction.getProducts().size() > 1) { - product = reaction.getProducts().get(1); - } - Reactant reactant = null; - if (reaction.getReactants().size() > 1) { - reactant = reaction.getReactants().get(1); - } - Modifier modifier = null; - if (reaction.getModifiers().size() > 0) { - modifier = reaction.getModifiers().get(0); - assertTrue(modifier instanceof UnknownCatalysis); - } - - assertNull(reactant); - assertNull(product); - assertNotNull(modifier); + Product product = null; + if (reaction.getProducts().size() > 1) { + product = reaction.getProducts().get(1); + } + Reactant reactant = null; + if (reaction.getReactants().size() > 1) { + reactant = reaction.getReactants().get(1); + } + Modifier modifier = null; + if (reaction.getModifiers().size() > 0) { + modifier = reaction.getModifiers().get(0); + assertTrue(modifier instanceof UnknownCatalysis); + } - assertEquals(1, getWarnings().size()); + assertNull(reactant); + assertNull(product); + assertNotNull(modifier); - Model model2 = serializeModelOverCellDesignerParser(model1); + assertEquals(1, getWarnings().size()); - assertEquals(0, mc.compare(model1, model2)); + Model model2 = serializeModelOverCellDesignerParser(model1); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } @Test public void InhibitionInteractionDashedInputTest() throws Exception { - try { - String fileName = "testFiles/reactions/interaction_dashed_mim_inhibition_input.gpml"; + String fileName = "testFiles/reactions/interaction_dashed_mim_inhibition_input.gpml"; - Model model1 = new GPMLToModel().getModel(fileName); + Model model1 = new GPMLToModel().getModel(fileName); - assertEquals(1, model1.getReactions().size()); + assertEquals(1, model1.getReactions().size()); - Reaction reaction = model1.getReactions().iterator().next(); + Reaction reaction = model1.getReactions().iterator().next(); - Product product = null; - if (reaction.getProducts().size() > 1) { - product = reaction.getProducts().get(1); - } - Reactant reactant = null; - if (reaction.getReactants().size() > 1) { - reactant = reaction.getReactants().get(1); - } - Modifier modifier = null; - if (reaction.getModifiers().size() > 0) { - modifier = reaction.getModifiers().get(0); - assertTrue(modifier instanceof UnknownInhibition); - } - - assertNull(reactant); - assertNull(product); - assertNotNull(modifier); + Product product = null; + if (reaction.getProducts().size() > 1) { + product = reaction.getProducts().get(1); + } + Reactant reactant = null; + if (reaction.getReactants().size() > 1) { + reactant = reaction.getReactants().get(1); + } + Modifier modifier = null; + if (reaction.getModifiers().size() > 0) { + modifier = reaction.getModifiers().get(0); + assertTrue(modifier instanceof UnknownInhibition); + } - assertEquals(2, getWarnings().size()); + assertNull(reactant); + assertNull(product); + assertNotNull(modifier); - Model model2 = serializeModelOverCellDesignerParser(model1); + assertEquals(2, getWarnings().size()); - assertEquals(0, mc.compare(model1, model2)); + Model model2 = serializeModelOverCellDesignerParser(model1); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } @Test public void CleavageInteractionDashedInputTest() throws Exception { - try { - String fileName = "testFiles/reactions/interaction_dashed_mim_cleavage_input.gpml"; + String fileName = "testFiles/reactions/interaction_dashed_mim_cleavage_input.gpml"; - Model model1 = new GPMLToModel().getModel(fileName); + Model model1 = new GPMLToModel().getModel(fileName); - assertEquals(1, model1.getReactions().size()); + assertEquals(1, model1.getReactions().size()); - Reaction reaction = model1.getReactions().iterator().next(); + Reaction reaction = model1.getReactions().iterator().next(); - Product product = null; - if (reaction.getProducts().size() > 1) { - product = reaction.getProducts().get(1); - } - Reactant reactant = null; - if (reaction.getReactants().size() > 1) { - reactant = reaction.getReactants().get(1); - } - Modifier modifier = null; - if (reaction.getModifiers().size() > 0) { - modifier = reaction.getModifiers().get(0); - assertTrue(modifier instanceof Modulation); - } - - assertNull(reactant); - assertNull(product); - assertNotNull(modifier); + Product product = null; + if (reaction.getProducts().size() > 1) { + product = reaction.getProducts().get(1); + } + Reactant reactant = null; + if (reaction.getReactants().size() > 1) { + reactant = reaction.getReactants().get(1); + } + Modifier modifier = null; + if (reaction.getModifiers().size() > 0) { + modifier = reaction.getModifiers().get(0); + assertTrue(modifier instanceof Modulation); + } - assertEquals(2, getWarnings().size()); + assertNull(reactant); + assertNull(product); + assertNotNull(modifier); - Model model2 = serializeModelOverCellDesignerParser(model1); + assertEquals(2, getWarnings().size()); - assertEquals(0, mc.compare(model1, model2)); + Model model2 = serializeModelOverCellDesignerParser(model1); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } @Test public void CovalentBondInteractionDashedInputTest() throws Exception { - try { - String fileName = "testFiles/reactions/interaction_dashed_mim_covalent_bond_input.gpml"; + String fileName = "testFiles/reactions/interaction_dashed_mim_covalent_bond_input.gpml"; - Model model1 = new GPMLToModel().getModel(fileName); + Model model1 = new GPMLToModel().getModel(fileName); - assertEquals(1, model1.getReactions().size()); + assertEquals(1, model1.getReactions().size()); - Reaction reaction = model1.getReactions().iterator().next(); + Reaction reaction = model1.getReactions().iterator().next(); - Product product = null; - if (reaction.getProducts().size() > 1) { - product = reaction.getProducts().get(1); - } - Reactant reactant = null; - if (reaction.getReactants().size() > 1) { - reactant = reaction.getReactants().get(1); - } - Modifier modifier = null; - if (reaction.getModifiers().size() > 0) { - modifier = reaction.getModifiers().get(0); - assertTrue(modifier instanceof Modifier); - } - - assertNotNull(reactant); - assertNull(product); - assertNull(modifier); + Product product = null; + if (reaction.getProducts().size() > 1) { + product = reaction.getProducts().get(1); + } + Reactant reactant = null; + if (reaction.getReactants().size() > 1) { + reactant = reaction.getReactants().get(1); + } + Modifier modifier = null; + if (reaction.getModifiers().size() > 0) { + modifier = reaction.getModifiers().get(0); + assertTrue(modifier instanceof Modifier); + } - assertEquals(2, getWarnings().size()); + assertNotNull(reactant); + assertNull(product); + assertNull(modifier); - Model model2 = serializeModelOverCellDesignerParser(model1); + assertEquals(2, getWarnings().size()); - assertEquals(0, mc.compare(model1, model2)); + Model model2 = serializeModelOverCellDesignerParser(model1); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } @Test public void BranchingLeftInteractionDashedInputTest() throws Exception { - try { - String fileName = "testFiles/reactions/interaction_dashed_mim_branching_left_input.gpml"; + String fileName = "testFiles/reactions/interaction_dashed_mim_branching_left_input.gpml"; - Model model1 = new GPMLToModel().getModel(fileName); + Model model1 = new GPMLToModel().getModel(fileName); - assertEquals(1, model1.getReactions().size()); + assertEquals(1, model1.getReactions().size()); - Reaction reaction = model1.getReactions().iterator().next(); + Reaction reaction = model1.getReactions().iterator().next(); - Product product = null; - if (reaction.getProducts().size() > 1) { - product = reaction.getProducts().get(1); - } - Reactant reactant = null; - if (reaction.getReactants().size() > 1) { - reactant = reaction.getReactants().get(1); - } - Modifier modifier = null; - if (reaction.getModifiers().size() > 0) { - modifier = reaction.getModifiers().get(0); - assertTrue(modifier instanceof Modifier); - } - - assertNotNull(reactant); - assertNull(product); - assertNull(modifier); + Product product = null; + if (reaction.getProducts().size() > 1) { + product = reaction.getProducts().get(1); + } + Reactant reactant = null; + if (reaction.getReactants().size() > 1) { + reactant = reaction.getReactants().get(1); + } + Modifier modifier = null; + if (reaction.getModifiers().size() > 0) { + modifier = reaction.getModifiers().get(0); + assertTrue(modifier instanceof Modifier); + } - assertEquals(2, getWarnings().size()); + assertNotNull(reactant); + assertNull(product); + assertNull(modifier); - Model model2 = serializeModelOverCellDesignerParser(model1); + assertEquals(2, getWarnings().size()); - assertEquals(0, mc.compare(model1, model2)); + Model model2 = serializeModelOverCellDesignerParser(model1); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } @Test public void BranchingRightInteractionDashedInputTest() throws Exception { - try { - String fileName = "testFiles/reactions/interaction_dashed_mim_branching_right_input.gpml"; + String fileName = "testFiles/reactions/interaction_dashed_mim_branching_right_input.gpml"; - Model model1 = new GPMLToModel().getModel(fileName); + Model model1 = new GPMLToModel().getModel(fileName); - assertEquals(1, model1.getReactions().size()); + assertEquals(1, model1.getReactions().size()); - Reaction reaction = model1.getReactions().iterator().next(); + Reaction reaction = model1.getReactions().iterator().next(); - Product product = null; - if (reaction.getProducts().size() > 1) { - product = reaction.getProducts().get(1); - } - Reactant reactant = null; - if (reaction.getReactants().size() > 1) { - reactant = reaction.getReactants().get(1); - } - Modifier modifier = null; - if (reaction.getModifiers().size() > 0) { - modifier = reaction.getModifiers().get(0); - assertTrue(modifier instanceof Modifier); - } - - assertNotNull(reactant); - assertNull(product); - assertNull(modifier); + Product product = null; + if (reaction.getProducts().size() > 1) { + product = reaction.getProducts().get(1); + } + Reactant reactant = null; + if (reaction.getReactants().size() > 1) { + reactant = reaction.getReactants().get(1); + } + Modifier modifier = null; + if (reaction.getModifiers().size() > 0) { + modifier = reaction.getModifiers().get(0); + assertTrue(modifier instanceof Modifier); + } - assertEquals(2, getWarnings().size()); + assertNotNull(reactant); + assertNull(product); + assertNull(modifier); - Model model2 = serializeModelOverCellDesignerParser(model1); + assertEquals(2, getWarnings().size()); - assertEquals(0, mc.compare(model1, model2)); + Model model2 = serializeModelOverCellDesignerParser(model1); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } @Test public void TranscriptionTranslationInteractionDashedInputTest() throws Exception { - try { - String fileName = "testFiles/reactions/interaction_dashed_mim_transcription_translation_input.gpml"; + String fileName = "testFiles/reactions/interaction_dashed_mim_transcription_translation_input.gpml"; - Model model1 = new GPMLToModel().getModel(fileName); + Model model1 = new GPMLToModel().getModel(fileName); - assertEquals(1, model1.getReactions().size()); + assertEquals(1, model1.getReactions().size()); - Reaction reaction = model1.getReactions().iterator().next(); + Reaction reaction = model1.getReactions().iterator().next(); - Product product = null; - if (reaction.getProducts().size() > 1) { - product = reaction.getProducts().get(1); - } - Reactant reactant = null; - if (reaction.getReactants().size() > 1) { - reactant = reaction.getReactants().get(1); - } - Modifier modifier = null; - if (reaction.getModifiers().size() > 0) { - modifier = reaction.getModifiers().get(0); - assertTrue(modifier instanceof Modulation); - } - - assertNull(reactant); - assertNull(product); - assertNotNull(modifier); + Product product = null; + if (reaction.getProducts().size() > 1) { + product = reaction.getProducts().get(1); + } + Reactant reactant = null; + if (reaction.getReactants().size() > 1) { + reactant = reaction.getReactants().get(1); + } + Modifier modifier = null; + if (reaction.getModifiers().size() > 0) { + modifier = reaction.getModifiers().get(0); + assertTrue(modifier instanceof Modulation); + } - assertEquals(2, getWarnings().size()); + assertNull(reactant); + assertNull(product); + assertNotNull(modifier); - Model model2 = serializeModelOverCellDesignerParser(model1); + assertEquals(2, getWarnings().size()); - assertEquals(0, mc.compare(model1, model2)); + Model model2 = serializeModelOverCellDesignerParser(model1); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } @Test public void GapInteractionDashedInputTest() throws Exception { - try { - String fileName = "testFiles/reactions/interaction_dashed_mim_gap_input.gpml"; + String fileName = "testFiles/reactions/interaction_dashed_mim_gap_input.gpml"; - Model model1 = new GPMLToModel().getModel(fileName); + Model model1 = new GPMLToModel().getModel(fileName); - assertEquals(1, model1.getReactions().size()); + assertEquals(1, model1.getReactions().size()); - Reaction reaction = model1.getReactions().iterator().next(); + Reaction reaction = model1.getReactions().iterator().next(); - Product product = null; - if (reaction.getProducts().size() > 1) { - product = reaction.getProducts().get(1); - } - Reactant reactant = null; - if (reaction.getReactants().size() > 1) { - reactant = reaction.getReactants().get(1); - } - Modifier modifier = null; - if (reaction.getModifiers().size() > 0) { - modifier = reaction.getModifiers().get(0); - assertTrue(modifier instanceof Modulation); - } - - assertNull(reactant); - assertNull(product); - assertNotNull(modifier); + Product product = null; + if (reaction.getProducts().size() > 1) { + product = reaction.getProducts().get(1); + } + Reactant reactant = null; + if (reaction.getReactants().size() > 1) { + reactant = reaction.getReactants().get(1); + } + Modifier modifier = null; + if (reaction.getModifiers().size() > 0) { + modifier = reaction.getModifiers().get(0); + assertTrue(modifier instanceof Modulation); + } - assertEquals(2, getWarnings().size()); + assertNull(reactant); + assertNull(product); + assertNotNull(modifier); - Model model2 = serializeModelOverCellDesignerParser(model1); + assertEquals(2, getWarnings().size()); - assertEquals(0, mc.compare(model1, model2)); + Model model2 = serializeModelOverCellDesignerParser(model1); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } } diff --git a/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/ReactionGpmlOutputToModelTest.java b/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/ReactionGpmlOutputToModelTest.java index ae5032bab58069a6bcc28f003bc29f7d8d8b36d9..d8c9d6564d32f267caa8043cab3bdfbd2efd0c28 100644 --- a/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/ReactionGpmlOutputToModelTest.java +++ b/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/ReactionGpmlOutputToModelTest.java @@ -1,1342 +1,1142 @@ package lcsb.mapviewer.wikipathway; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.junit.Assert.*; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.junit.Test; import lcsb.mapviewer.model.map.model.Model; import lcsb.mapviewer.model.map.model.ModelComparator; -import lcsb.mapviewer.model.map.modifier.Catalysis; -import lcsb.mapviewer.model.map.modifier.Inhibition; -import lcsb.mapviewer.model.map.modifier.Modulation; -import lcsb.mapviewer.model.map.modifier.PhysicalStimulation; -import lcsb.mapviewer.model.map.reaction.Modifier; -import lcsb.mapviewer.model.map.reaction.Product; -import lcsb.mapviewer.model.map.reaction.Reactant; -import lcsb.mapviewer.model.map.reaction.Reaction; +import lcsb.mapviewer.model.map.modifier.*; +import lcsb.mapviewer.model.map.reaction.*; import lcsb.mapviewer.wikipathway.XML.GPMLToModel; public class ReactionGpmlOutputToModelTest extends WikipathwaysTestFunctions { - /** - * Default class logger. - */ + static Logger logger = LogManager.getLogger(ReactionGpmlOutputToModelTest.class); private ModelComparator mc = new ModelComparator(1.0); @Test public void LineInteractionOutputTest() throws Exception { - try { - String fileName = "testFiles/reactions/interaction_line_output.gpml"; - - Model model1 = new GPMLToModel().getModel(fileName); + String fileName = "testFiles/reactions/interaction_line_output.gpml"; - assertEquals(1, model1.getReactions().size()); + Model model1 = new GPMLToModel().getModel(fileName); - Reaction reaction = model1.getReactions().iterator().next(); + assertEquals(1, model1.getReactions().size()); - Product product = null; - if (reaction.getProducts().size() > 1) { - product = reaction.getProducts().get(1); - } - Reactant reactant = null; - if (reaction.getReactants().size() > 1) { - reactant = reaction.getReactants().get(1); - } - Modifier modifier = null; - if (reaction.getModifiers().size() > 0) { - modifier = reaction.getModifiers().get(0); - assertTrue(modifier instanceof Modifier); - } + Reaction reaction = model1.getReactions().iterator().next(); - assertNotNull(reactant); - assertNull(product); - assertNull(modifier); + Product product = null; + if (reaction.getProducts().size() > 1) { + product = reaction.getProducts().get(1); + } + Reactant reactant = null; + if (reaction.getReactants().size() > 1) { + reactant = reaction.getReactants().get(1); + } + Modifier modifier = null; + if (reaction.getModifiers().size() > 0) { + modifier = reaction.getModifiers().get(0); + assertTrue(modifier instanceof Modifier); + } - assertEquals(0, getWarnings().size()); + assertNotNull(reactant); + assertNull(product); + assertNull(modifier); - Model model2 = serializeModelOverCellDesignerParser(model1); + assertEquals(0, getWarnings().size()); - assertEquals(0, mc.compare(model1, model2)); + Model model2 = serializeModelOverCellDesignerParser(model1); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } @Test public void ArrowInteractionOutputTest() throws Exception { - try { - String fileName = "testFiles/reactions/interaction_arrow_output.gpml"; + String fileName = "testFiles/reactions/interaction_arrow_output.gpml"; - Model model1 = new GPMLToModel().getModel(fileName); + Model model1 = new GPMLToModel().getModel(fileName); - assertEquals(1, model1.getReactions().size()); + assertEquals(1, model1.getReactions().size()); - Reaction reaction = model1.getReactions().iterator().next(); + Reaction reaction = model1.getReactions().iterator().next(); - Product product = null; - if (reaction.getProducts().size() > 1) { - product = reaction.getProducts().get(1); - } - Reactant reactant = null; - if (reaction.getReactants().size() > 1) { - reactant = reaction.getReactants().get(1); - } - Modifier modifier = null; - if (reaction.getModifiers().size() > 0) { - modifier = reaction.getModifiers().get(0); - assertTrue(modifier instanceof Modulation); - } + Product product = null; + if (reaction.getProducts().size() > 1) { + product = reaction.getProducts().get(1); + } + Reactant reactant = null; + if (reaction.getReactants().size() > 1) { + reactant = reaction.getReactants().get(1); + } + Modifier modifier = null; + if (reaction.getModifiers().size() > 0) { + modifier = reaction.getModifiers().get(0); + assertTrue(modifier instanceof Modulation); + } - assertNull(reactant); - assertNotNull(product); - assertNull(modifier); + assertNull(reactant); + assertNotNull(product); + assertNull(modifier); - assertEquals(0, getWarnings().size()); + assertEquals(0, getWarnings().size()); - Model model2 = serializeModelOverCellDesignerParser(model1); + Model model2 = serializeModelOverCellDesignerParser(model1); - assertEquals(0, mc.compare(model1, model2)); + assertEquals(0, mc.compare(model1, model2)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } } @Test public void DashedLineInteractionOutputTest() throws Exception { - try { - String fileName = "testFiles/reactions/interaction_dashed_line_output.gpml"; + String fileName = "testFiles/reactions/interaction_dashed_line_output.gpml"; - Model model1 = new GPMLToModel().getModel(fileName); + Model model1 = new GPMLToModel().getModel(fileName); - assertEquals(1, model1.getReactions().size()); + assertEquals(1, model1.getReactions().size()); - Reaction reaction = model1.getReactions().iterator().next(); + Reaction reaction = model1.getReactions().iterator().next(); - Product product = null; - if (reaction.getProducts().size() > 1) { - product = reaction.getProducts().get(1); - } - Reactant reactant = null; - if (reaction.getReactants().size() > 1) { - reactant = reaction.getReactants().get(1); - } - Modifier modifier = null; - if (reaction.getModifiers().size() > 0) { - modifier = reaction.getModifiers().get(0); - assertTrue(modifier instanceof Modifier); - } + Product product = null; + if (reaction.getProducts().size() > 1) { + product = reaction.getProducts().get(1); + } + Reactant reactant = null; + if (reaction.getReactants().size() > 1) { + reactant = reaction.getReactants().get(1); + } + Modifier modifier = null; + if (reaction.getModifiers().size() > 0) { + modifier = reaction.getModifiers().get(0); + assertTrue(modifier instanceof Modifier); + } - assertNotNull(reactant); - assertNull(product); - assertNull(modifier); + assertNotNull(reactant); + assertNull(product); + assertNull(modifier); - assertEquals(1, getWarnings().size()); + assertEquals(1, getWarnings().size()); - Model model2 = serializeModelOverCellDesignerParser(model1); + Model model2 = serializeModelOverCellDesignerParser(model1); - assertEquals(0, mc.compare(model1, model2)); + assertEquals(0, mc.compare(model1, model2)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } } @Test public void DashedArrowInteractionOutputTest() throws Exception { - try { - String fileName = "testFiles/reactions/interaction_dashed_arrow_output.gpml"; - - Model model1 = new GPMLToModel().getModel(fileName); + String fileName = "testFiles/reactions/interaction_dashed_arrow_output.gpml"; - assertEquals(1, model1.getReactions().size()); + Model model1 = new GPMLToModel().getModel(fileName); - Reaction reaction = model1.getReactions().iterator().next(); + assertEquals(1, model1.getReactions().size()); - Product product = null; - if (reaction.getProducts().size() > 1) { - product = reaction.getProducts().get(1); - } - Reactant reactant = null; - if (reaction.getReactants().size() > 1) { - reactant = reaction.getReactants().get(1); - } - Modifier modifier = null; - if (reaction.getModifiers().size() > 0) { - modifier = reaction.getModifiers().get(0); - assertTrue(modifier instanceof Modulation); - } + Reaction reaction = model1.getReactions().iterator().next(); - assertNull(reactant); - assertNotNull(product); - assertNull(modifier); + Product product = null; + if (reaction.getProducts().size() > 1) { + product = reaction.getProducts().get(1); + } + Reactant reactant = null; + if (reaction.getReactants().size() > 1) { + reactant = reaction.getReactants().get(1); + } + Modifier modifier = null; + if (reaction.getModifiers().size() > 0) { + modifier = reaction.getModifiers().get(0); + assertTrue(modifier instanceof Modulation); + } - assertEquals(1, getWarnings().size()); + assertNull(reactant); + assertNotNull(product); + assertNull(modifier); - Model model2 = serializeModelOverCellDesignerParser(model1); + assertEquals(1, getWarnings().size()); - assertEquals(0, mc.compare(model1, model2)); + Model model2 = serializeModelOverCellDesignerParser(model1); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } @Test public void TBarInteractionOutputTest() throws Exception { - try { - String fileName = "testFiles/reactions/interaction_tbar_output.gpml"; - - Model model1 = new GPMLToModel().getModel(fileName); + String fileName = "testFiles/reactions/interaction_tbar_output.gpml"; - assertEquals(1, model1.getReactions().size()); + Model model1 = new GPMLToModel().getModel(fileName); - Reaction reaction = model1.getReactions().iterator().next(); + assertEquals(1, model1.getReactions().size()); - Product product = null; - if (reaction.getProducts().size() > 1) { - product = reaction.getProducts().get(1); - } - Reactant reactant = null; - if (reaction.getReactants().size() > 1) { - reactant = reaction.getReactants().get(1); - } - Modifier modifier = null; - if (reaction.getModifiers().size() > 0) { - modifier = reaction.getModifiers().get(0); - assertTrue(modifier instanceof Inhibition); - } + Reaction reaction = model1.getReactions().iterator().next(); - assertNull(reactant); - assertNotNull(product); - assertNull(modifier); + Product product = null; + if (reaction.getProducts().size() > 1) { + product = reaction.getProducts().get(1); + } + Reactant reactant = null; + if (reaction.getReactants().size() > 1) { + reactant = reaction.getReactants().get(1); + } + Modifier modifier = null; + if (reaction.getModifiers().size() > 0) { + modifier = reaction.getModifiers().get(0); + assertTrue(modifier instanceof Inhibition); + } - assertEquals(1, getWarnings().size()); + assertNull(reactant); + assertNotNull(product); + assertNull(modifier); - Model model2 = serializeModelOverCellDesignerParser(model1); + assertEquals(1, getWarnings().size()); - assertEquals(0, mc.compare(model1, model2)); + Model model2 = serializeModelOverCellDesignerParser(model1); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } @Test public void NecessaryStimulationInteractionOutputTest() throws Exception { - try { - String fileName = "testFiles/reactions/interaction_mim_necessary_stimulation_output.gpml"; - - Model model1 = new GPMLToModel().getModel(fileName); + String fileName = "testFiles/reactions/interaction_mim_necessary_stimulation_output.gpml"; - assertEquals(1, model1.getReactions().size()); + Model model1 = new GPMLToModel().getModel(fileName); - Reaction reaction = model1.getReactions().iterator().next(); + assertEquals(1, model1.getReactions().size()); - Product product = null; - if (reaction.getProducts().size() > 1) { - product = reaction.getProducts().get(1); - } - Reactant reactant = null; - if (reaction.getReactants().size() > 1) { - reactant = reaction.getReactants().get(1); - } - Modifier modifier = null; - if (reaction.getModifiers().size() > 0) { - modifier = reaction.getModifiers().get(0); - assertTrue(modifier instanceof PhysicalStimulation); - } + Reaction reaction = model1.getReactions().iterator().next(); - assertNull(reactant); - assertNotNull(product); - assertNull(modifier); + Product product = null; + if (reaction.getProducts().size() > 1) { + product = reaction.getProducts().get(1); + } + Reactant reactant = null; + if (reaction.getReactants().size() > 1) { + reactant = reaction.getReactants().get(1); + } + Modifier modifier = null; + if (reaction.getModifiers().size() > 0) { + modifier = reaction.getModifiers().get(0); + assertTrue(modifier instanceof PhysicalStimulation); + } - assertEquals(1, getWarnings().size()); + assertNull(reactant); + assertNotNull(product); + assertNull(modifier); - Model model2 = serializeModelOverCellDesignerParser(model1); + assertEquals(1, getWarnings().size()); - assertEquals(0, mc.compare(model1, model2)); + Model model2 = serializeModelOverCellDesignerParser(model1); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } @Test public void BindingInteractionOutputTest() throws Exception { - try { - String fileName = "testFiles/reactions/interaction_mim_binding_output.gpml"; - - Model model1 = new GPMLToModel().getModel(fileName); + String fileName = "testFiles/reactions/interaction_mim_binding_output.gpml"; - assertEquals(1, model1.getReactions().size()); + Model model1 = new GPMLToModel().getModel(fileName); - Reaction reaction = model1.getReactions().iterator().next(); + assertEquals(1, model1.getReactions().size()); - Product product = null; - if (reaction.getProducts().size() > 1) { - product = reaction.getProducts().get(1); - } - Reactant reactant = null; - if (reaction.getReactants().size() > 1) { - reactant = reaction.getReactants().get(1); - } - Modifier modifier = null; - if (reaction.getModifiers().size() > 0) { - modifier = reaction.getModifiers().get(0); - assertTrue(modifier instanceof Modulation); - } + Reaction reaction = model1.getReactions().iterator().next(); - assertNull(reactant); - assertNotNull(product); - assertNull(modifier); + Product product = null; + if (reaction.getProducts().size() > 1) { + product = reaction.getProducts().get(1); + } + Reactant reactant = null; + if (reaction.getReactants().size() > 1) { + reactant = reaction.getReactants().get(1); + } + Modifier modifier = null; + if (reaction.getModifiers().size() > 0) { + modifier = reaction.getModifiers().get(0); + assertTrue(modifier instanceof Modulation); + } - assertEquals(1, getWarnings().size()); + assertNull(reactant); + assertNotNull(product); + assertNull(modifier); - Model model2 = serializeModelOverCellDesignerParser(model1); + assertEquals(1, getWarnings().size()); - assertEquals(0, mc.compare(model1, model2)); + Model model2 = serializeModelOverCellDesignerParser(model1); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } @Test public void ConversionInteractionOutputTest() throws Exception { - try { - String fileName = "testFiles/reactions/interaction_mim_conversion_output.gpml"; - - Model model1 = new GPMLToModel().getModel(fileName); + String fileName = "testFiles/reactions/interaction_mim_conversion_output.gpml"; - assertEquals(1, model1.getReactions().size()); + Model model1 = new GPMLToModel().getModel(fileName); - Reaction reaction = model1.getReactions().iterator().next(); + assertEquals(1, model1.getReactions().size()); - Product product = null; - if (reaction.getProducts().size() > 1) { - product = reaction.getProducts().get(1); - } - Reactant reactant = null; - if (reaction.getReactants().size() > 1) { - reactant = reaction.getReactants().get(1); - } - Modifier modifier = null; - if (reaction.getModifiers().size() > 0) { - modifier = reaction.getModifiers().get(0); - assertTrue(modifier instanceof Modulation); - } + Reaction reaction = model1.getReactions().iterator().next(); - assertNull(reactant); - assertNotNull(product); - assertNull(modifier); + Product product = null; + if (reaction.getProducts().size() > 1) { + product = reaction.getProducts().get(1); + } + Reactant reactant = null; + if (reaction.getReactants().size() > 1) { + reactant = reaction.getReactants().get(1); + } + Modifier modifier = null; + if (reaction.getModifiers().size() > 0) { + modifier = reaction.getModifiers().get(0); + assertTrue(modifier instanceof Modulation); + } - assertEquals(0, getWarnings().size()); + assertNull(reactant); + assertNotNull(product); + assertNull(modifier); - Model model2 = serializeModelOverCellDesignerParser(model1); + assertEquals(0, getWarnings().size()); - assertEquals(0, mc.compare(model1, model2)); + Model model2 = serializeModelOverCellDesignerParser(model1); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } @Test public void StimulationInteractionOutputTest() throws Exception { - try { - String fileName = "testFiles/reactions/interaction_mim_stimulation_output.gpml"; - - Model model1 = new GPMLToModel().getModel(fileName); + String fileName = "testFiles/reactions/interaction_mim_stimulation_output.gpml"; - assertEquals(1, model1.getReactions().size()); + Model model1 = new GPMLToModel().getModel(fileName); - Reaction reaction = model1.getReactions().iterator().next(); + assertEquals(1, model1.getReactions().size()); - Product product = null; - if (reaction.getProducts().size() > 1) { - product = reaction.getProducts().get(1); - } - Reactant reactant = null; - if (reaction.getReactants().size() > 1) { - reactant = reaction.getReactants().get(1); - } - Modifier modifier = null; - if (reaction.getModifiers().size() > 0) { - modifier = reaction.getModifiers().get(0); - assertTrue(modifier instanceof PhysicalStimulation); - } + Reaction reaction = model1.getReactions().iterator().next(); - assertNull(reactant); - assertNotNull(product); - assertNull(modifier); + Product product = null; + if (reaction.getProducts().size() > 1) { + product = reaction.getProducts().get(1); + } + Reactant reactant = null; + if (reaction.getReactants().size() > 1) { + reactant = reaction.getReactants().get(1); + } + Modifier modifier = null; + if (reaction.getModifiers().size() > 0) { + modifier = reaction.getModifiers().get(0); + assertTrue(modifier instanceof PhysicalStimulation); + } - assertEquals(1, getWarnings().size()); + assertNull(reactant); + assertNotNull(product); + assertNull(modifier); - Model model2 = serializeModelOverCellDesignerParser(model1); + assertEquals(1, getWarnings().size()); - assertEquals(0, mc.compare(model1, model2)); + Model model2 = serializeModelOverCellDesignerParser(model1); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } @Test public void ModificationInteractionOutputTest() throws Exception { - try { - String fileName = "testFiles/reactions/interaction_mim_modification_output.gpml"; - - Model model1 = new GPMLToModel().getModel(fileName); + String fileName = "testFiles/reactions/interaction_mim_modification_output.gpml"; - assertEquals(1, model1.getReactions().size()); + Model model1 = new GPMLToModel().getModel(fileName); - Reaction reaction = model1.getReactions().iterator().next(); + assertEquals(1, model1.getReactions().size()); - Product product = null; - if (reaction.getProducts().size() > 1) { - product = reaction.getProducts().get(1); - } - Reactant reactant = null; - if (reaction.getReactants().size() > 1) { - reactant = reaction.getReactants().get(1); - } - Modifier modifier = null; - if (reaction.getModifiers().size() > 0) { - modifier = reaction.getModifiers().get(0); - assertTrue(modifier instanceof Modulation); - } + Reaction reaction = model1.getReactions().iterator().next(); - assertNull(reactant); - assertNotNull(product); - assertNull(modifier); + Product product = null; + if (reaction.getProducts().size() > 1) { + product = reaction.getProducts().get(1); + } + Reactant reactant = null; + if (reaction.getReactants().size() > 1) { + reactant = reaction.getReactants().get(1); + } + Modifier modifier = null; + if (reaction.getModifiers().size() > 0) { + modifier = reaction.getModifiers().get(0); + assertTrue(modifier instanceof Modulation); + } - assertEquals(1, getWarnings().size()); + assertNull(reactant); + assertNotNull(product); + assertNull(modifier); - Model model2 = serializeModelOverCellDesignerParser(model1); + assertEquals(1, getWarnings().size()); - assertEquals(0, mc.compare(model1, model2)); + Model model2 = serializeModelOverCellDesignerParser(model1); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } @Test public void CatalystInteractionOutputTest() throws Exception { - try { - String fileName = "testFiles/reactions/interaction_mim_catalyst_output.gpml"; - - Model model1 = new GPMLToModel().getModel(fileName); + String fileName = "testFiles/reactions/interaction_mim_catalyst_output.gpml"; - assertEquals(1, model1.getReactions().size()); + Model model1 = new GPMLToModel().getModel(fileName); - Reaction reaction = model1.getReactions().iterator().next(); + assertEquals(1, model1.getReactions().size()); - Product product = null; - if (reaction.getProducts().size() > 1) { - product = reaction.getProducts().get(1); - } - Reactant reactant = null; - if (reaction.getReactants().size() > 1) { - reactant = reaction.getReactants().get(1); - } - Modifier modifier = null; - if (reaction.getModifiers().size() > 0) { - modifier = reaction.getModifiers().get(0); - assertTrue(modifier instanceof Catalysis); - } + Reaction reaction = model1.getReactions().iterator().next(); - assertNull(reactant); - assertNotNull(product); - assertNull(modifier); + Product product = null; + if (reaction.getProducts().size() > 1) { + product = reaction.getProducts().get(1); + } + Reactant reactant = null; + if (reaction.getReactants().size() > 1) { + reactant = reaction.getReactants().get(1); + } + Modifier modifier = null; + if (reaction.getModifiers().size() > 0) { + modifier = reaction.getModifiers().get(0); + assertTrue(modifier instanceof Catalysis); + } - assertEquals(1, getWarnings().size()); + assertNull(reactant); + assertNotNull(product); + assertNull(modifier); - Model model2 = serializeModelOverCellDesignerParser(model1); + assertEquals(1, getWarnings().size()); - assertEquals(0, mc.compare(model1, model2)); + Model model2 = serializeModelOverCellDesignerParser(model1); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } @Test public void InhibitionInteractionOutputTest() throws Exception { - try { - String fileName = "testFiles/reactions/interaction_mim_inhibition_output.gpml"; - - Model model1 = new GPMLToModel().getModel(fileName); + String fileName = "testFiles/reactions/interaction_mim_inhibition_output.gpml"; - assertEquals(1, model1.getReactions().size()); + Model model1 = new GPMLToModel().getModel(fileName); - Reaction reaction = model1.getReactions().iterator().next(); + assertEquals(1, model1.getReactions().size()); - Product product = null; - if (reaction.getProducts().size() > 1) { - product = reaction.getProducts().get(1); - } - Reactant reactant = null; - if (reaction.getReactants().size() > 1) { - reactant = reaction.getReactants().get(1); - } - Modifier modifier = null; - if (reaction.getModifiers().size() > 0) { - modifier = reaction.getModifiers().get(0); - assertTrue(modifier instanceof Inhibition); - } + Reaction reaction = model1.getReactions().iterator().next(); - assertNull(reactant); - assertNotNull(product); - assertNull(modifier); + Product product = null; + if (reaction.getProducts().size() > 1) { + product = reaction.getProducts().get(1); + } + Reactant reactant = null; + if (reaction.getReactants().size() > 1) { + reactant = reaction.getReactants().get(1); + } + Modifier modifier = null; + if (reaction.getModifiers().size() > 0) { + modifier = reaction.getModifiers().get(0); + assertTrue(modifier instanceof Inhibition); + } - assertEquals(1, getWarnings().size()); + assertNull(reactant); + assertNotNull(product); + assertNull(modifier); - Model model2 = serializeModelOverCellDesignerParser(model1); + assertEquals(1, getWarnings().size()); - assertEquals(0, mc.compare(model1, model2)); + Model model2 = serializeModelOverCellDesignerParser(model1); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } @Test public void CleavageInteractionOutputTest() throws Exception { - try { - String fileName = "testFiles/reactions/interaction_mim_cleavage_output.gpml"; - - Model model1 = new GPMLToModel().getModel(fileName); + String fileName = "testFiles/reactions/interaction_mim_cleavage_output.gpml"; - assertEquals(1, model1.getReactions().size()); + Model model1 = new GPMLToModel().getModel(fileName); - Reaction reaction = model1.getReactions().iterator().next(); + assertEquals(1, model1.getReactions().size()); - Product product = null; - if (reaction.getProducts().size() > 1) { - product = reaction.getProducts().get(1); - } - Reactant reactant = null; - if (reaction.getReactants().size() > 1) { - reactant = reaction.getReactants().get(1); - } - Modifier modifier = null; - if (reaction.getModifiers().size() > 0) { - modifier = reaction.getModifiers().get(0); - assertTrue(modifier instanceof Modulation); - } + Reaction reaction = model1.getReactions().iterator().next(); - assertNull(reactant); - assertNotNull(product); - assertNull(modifier); + Product product = null; + if (reaction.getProducts().size() > 1) { + product = reaction.getProducts().get(1); + } + Reactant reactant = null; + if (reaction.getReactants().size() > 1) { + reactant = reaction.getReactants().get(1); + } + Modifier modifier = null; + if (reaction.getModifiers().size() > 0) { + modifier = reaction.getModifiers().get(0); + assertTrue(modifier instanceof Modulation); + } - assertEquals(0, getWarnings().size()); + assertNull(reactant); + assertNotNull(product); + assertNull(modifier); - Model model2 = serializeModelOverCellDesignerParser(model1); + assertEquals(0, getWarnings().size()); - assertEquals(0, mc.compare(model1, model2)); + Model model2 = serializeModelOverCellDesignerParser(model1); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } @Test public void CovalentBondInteractionOutputTest() throws Exception { - try { - String fileName = "testFiles/reactions/interaction_mim_covalent_bond_output.gpml"; - - Model model1 = new GPMLToModel().getModel(fileName); + String fileName = "testFiles/reactions/interaction_mim_covalent_bond_output.gpml"; - assertEquals(1, model1.getReactions().size()); + Model model1 = new GPMLToModel().getModel(fileName); - Reaction reaction = model1.getReactions().iterator().next(); + assertEquals(1, model1.getReactions().size()); - Product product = null; - if (reaction.getProducts().size() > 1) { - product = reaction.getProducts().get(1); - } - Reactant reactant = null; - if (reaction.getReactants().size() > 1) { - reactant = reaction.getReactants().get(1); - } - Modifier modifier = null; - if (reaction.getModifiers().size() > 0) { - modifier = reaction.getModifiers().get(0); - assertTrue(modifier instanceof Modifier); - } + Reaction reaction = model1.getReactions().iterator().next(); - assertNull(reactant); - assertNotNull(product); - assertNull(modifier); + Product product = null; + if (reaction.getProducts().size() > 1) { + product = reaction.getProducts().get(1); + } + Reactant reactant = null; + if (reaction.getReactants().size() > 1) { + reactant = reaction.getReactants().get(1); + } + Modifier modifier = null; + if (reaction.getModifiers().size() > 0) { + modifier = reaction.getModifiers().get(0); + assertTrue(modifier instanceof Modifier); + } - assertEquals(1, getWarnings().size()); + assertNull(reactant); + assertNotNull(product); + assertNull(modifier); - Model model2 = serializeModelOverCellDesignerParser(model1); + assertEquals(1, getWarnings().size()); - assertEquals(0, mc.compare(model1, model2)); + Model model2 = serializeModelOverCellDesignerParser(model1); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } @Test public void BranchingLeftInteractionOutputTest() throws Exception { - try { - String fileName = "testFiles/reactions/interaction_mim_branching_left_output.gpml"; - - Model model1 = new GPMLToModel().getModel(fileName); + String fileName = "testFiles/reactions/interaction_mim_branching_left_output.gpml"; - assertEquals(1, model1.getReactions().size()); + Model model1 = new GPMLToModel().getModel(fileName); - Reaction reaction = model1.getReactions().iterator().next(); + assertEquals(1, model1.getReactions().size()); - Product product = null; - if (reaction.getProducts().size() > 1) { - product = reaction.getProducts().get(1); - } - Reactant reactant = null; - if (reaction.getReactants().size() > 1) { - reactant = reaction.getReactants().get(1); - } - Modifier modifier = null; - if (reaction.getModifiers().size() > 0) { - modifier = reaction.getModifiers().get(0); - assertTrue(modifier instanceof Modifier); - } + Reaction reaction = model1.getReactions().iterator().next(); - assertNotNull(reactant); - assertNull(product); - assertNull(modifier); + Product product = null; + if (reaction.getProducts().size() > 1) { + product = reaction.getProducts().get(1); + } + Reactant reactant = null; + if (reaction.getReactants().size() > 1) { + reactant = reaction.getReactants().get(1); + } + Modifier modifier = null; + if (reaction.getModifiers().size() > 0) { + modifier = reaction.getModifiers().get(0); + assertTrue(modifier instanceof Modifier); + } - assertEquals(0, getWarnings().size()); + assertNotNull(reactant); + assertNull(product); + assertNull(modifier); - Model model2 = serializeModelOverCellDesignerParser(model1); + assertEquals(0, getWarnings().size()); - assertEquals(0, mc.compare(model1, model2)); + Model model2 = serializeModelOverCellDesignerParser(model1); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } @Test public void BranchingRightInteractionOutputTest() throws Exception { - try { - String fileName = "testFiles/reactions/interaction_mim_branching_right_output.gpml"; - - Model model1 = new GPMLToModel().getModel(fileName); + String fileName = "testFiles/reactions/interaction_mim_branching_right_output.gpml"; - assertEquals(1, model1.getReactions().size()); + Model model1 = new GPMLToModel().getModel(fileName); - Reaction reaction = model1.getReactions().iterator().next(); + assertEquals(1, model1.getReactions().size()); - Product product = null; - if (reaction.getProducts().size() > 1) { - product = reaction.getProducts().get(1); - } - Reactant reactant = null; - if (reaction.getReactants().size() > 1) { - reactant = reaction.getReactants().get(1); - } - Modifier modifier = null; - if (reaction.getModifiers().size() > 0) { - modifier = reaction.getModifiers().get(0); - assertTrue(modifier instanceof Modifier); - } + Reaction reaction = model1.getReactions().iterator().next(); - assertNotNull(reactant); - assertNull(product); - assertNull(modifier); + Product product = null; + if (reaction.getProducts().size() > 1) { + product = reaction.getProducts().get(1); + } + Reactant reactant = null; + if (reaction.getReactants().size() > 1) { + reactant = reaction.getReactants().get(1); + } + Modifier modifier = null; + if (reaction.getModifiers().size() > 0) { + modifier = reaction.getModifiers().get(0); + assertTrue(modifier instanceof Modifier); + } - assertEquals(0, getWarnings().size()); + assertNotNull(reactant); + assertNull(product); + assertNull(modifier); - Model model2 = serializeModelOverCellDesignerParser(model1); + assertEquals(0, getWarnings().size()); - assertEquals(0, mc.compare(model1, model2)); + Model model2 = serializeModelOverCellDesignerParser(model1); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } @Test public void TranscriptionTranslationInteractionOutputTest() throws Exception { - try { - String fileName = "testFiles/reactions/interaction_mim_transcription_translation_output.gpml"; - - Model model1 = new GPMLToModel().getModel(fileName); + String fileName = "testFiles/reactions/interaction_mim_transcription_translation_output.gpml"; - assertEquals(1, model1.getReactions().size()); + Model model1 = new GPMLToModel().getModel(fileName); - Reaction reaction = model1.getReactions().iterator().next(); + assertEquals(1, model1.getReactions().size()); - Product product = null; - if (reaction.getProducts().size() > 1) { - product = reaction.getProducts().get(1); - } - Reactant reactant = null; - if (reaction.getReactants().size() > 1) { - reactant = reaction.getReactants().get(1); - } - Modifier modifier = null; - if (reaction.getModifiers().size() > 0) { - modifier = reaction.getModifiers().get(0); - assertTrue(modifier instanceof Modulation); - } + Reaction reaction = model1.getReactions().iterator().next(); - assertNull(reactant); - assertNotNull(product); - assertNull(modifier); + Product product = null; + if (reaction.getProducts().size() > 1) { + product = reaction.getProducts().get(1); + } + Reactant reactant = null; + if (reaction.getReactants().size() > 1) { + reactant = reaction.getReactants().get(1); + } + Modifier modifier = null; + if (reaction.getModifiers().size() > 0) { + modifier = reaction.getModifiers().get(0); + assertTrue(modifier instanceof Modulation); + } - assertEquals(1, getWarnings().size()); + assertNull(reactant); + assertNotNull(product); + assertNull(modifier); - Model model2 = serializeModelOverCellDesignerParser(model1); + assertEquals(1, getWarnings().size()); - assertEquals(0, mc.compare(model1, model2)); + Model model2 = serializeModelOverCellDesignerParser(model1); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } @Test public void GapInteractionOutputTest() throws Exception { - try { - String fileName = "testFiles/reactions/interaction_mim_gap_output.gpml"; - - Model model1 = new GPMLToModel().getModel(fileName); + String fileName = "testFiles/reactions/interaction_mim_gap_output.gpml"; - assertEquals(1, model1.getReactions().size()); + Model model1 = new GPMLToModel().getModel(fileName); - Reaction reaction = model1.getReactions().iterator().next(); + assertEquals(1, model1.getReactions().size()); - Product product = null; - if (reaction.getProducts().size() > 1) { - product = reaction.getProducts().get(1); - } - Reactant reactant = null; - if (reaction.getReactants().size() > 1) { - reactant = reaction.getReactants().get(1); - } - Modifier modifier = null; - if (reaction.getModifiers().size() > 0) { - modifier = reaction.getModifiers().get(0); - assertTrue(modifier instanceof Modulation); - } + Reaction reaction = model1.getReactions().iterator().next(); - assertNull(reactant); - assertNotNull(product); - assertNull(modifier); + Product product = null; + if (reaction.getProducts().size() > 1) { + product = reaction.getProducts().get(1); + } + Reactant reactant = null; + if (reaction.getReactants().size() > 1) { + reactant = reaction.getReactants().get(1); + } + Modifier modifier = null; + if (reaction.getModifiers().size() > 0) { + modifier = reaction.getModifiers().get(0); + assertTrue(modifier instanceof Modulation); + } - assertEquals(1, getWarnings().size()); + assertNull(reactant); + assertNotNull(product); + assertNull(modifier); - Model model2 = serializeModelOverCellDesignerParser(model1); + assertEquals(1, getWarnings().size()); - assertEquals(0, mc.compare(model1, model2)); + Model model2 = serializeModelOverCellDesignerParser(model1); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } @Test public void TBarInteractionDashedOutputTest() throws Exception { - try { - String fileName = "testFiles/reactions/interaction_dashed_tbar_output.gpml"; - - Model model1 = new GPMLToModel().getModel(fileName); + String fileName = "testFiles/reactions/interaction_dashed_tbar_output.gpml"; - assertEquals(1, model1.getReactions().size()); + Model model1 = new GPMLToModel().getModel(fileName); - Reaction reaction = model1.getReactions().iterator().next(); + assertEquals(1, model1.getReactions().size()); - Product product = null; - if (reaction.getProducts().size() > 1) { - product = reaction.getProducts().get(1); - } - Reactant reactant = null; - if (reaction.getReactants().size() > 1) { - reactant = reaction.getReactants().get(1); - } - Modifier modifier = null; - if (reaction.getModifiers().size() > 0) { - modifier = reaction.getModifiers().get(0); - assertTrue(modifier instanceof Inhibition); - } + Reaction reaction = model1.getReactions().iterator().next(); - assertNull(reactant); - assertNotNull(product); - assertNull(modifier); + Product product = null; + if (reaction.getProducts().size() > 1) { + product = reaction.getProducts().get(1); + } + Reactant reactant = null; + if (reaction.getReactants().size() > 1) { + reactant = reaction.getReactants().get(1); + } + Modifier modifier = null; + if (reaction.getModifiers().size() > 0) { + modifier = reaction.getModifiers().get(0); + assertTrue(modifier instanceof Inhibition); + } - assertEquals(2, getWarnings().size()); + assertNull(reactant); + assertNotNull(product); + assertNull(modifier); - Model model2 = serializeModelOverCellDesignerParser(model1); + assertEquals(2, getWarnings().size()); - assertEquals(0, mc.compare(model1, model2)); + Model model2 = serializeModelOverCellDesignerParser(model1); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } @Test public void NecessaryStimulationInteractionDashedOutputTest() throws Exception { - try { - String fileName = "testFiles/reactions/interaction_dashed_mim_necessary_stimulation_output.gpml"; - - Model model1 = new GPMLToModel().getModel(fileName); + String fileName = "testFiles/reactions/interaction_dashed_mim_necessary_stimulation_output.gpml"; - assertEquals(1, model1.getReactions().size()); + Model model1 = new GPMLToModel().getModel(fileName); - Reaction reaction = model1.getReactions().iterator().next(); + assertEquals(1, model1.getReactions().size()); - Product product = null; - if (reaction.getProducts().size() > 1) { - product = reaction.getProducts().get(1); - } - Reactant reactant = null; - if (reaction.getReactants().size() > 1) { - reactant = reaction.getReactants().get(1); - } - Modifier modifier = null; - if (reaction.getModifiers().size() > 0) { - modifier = reaction.getModifiers().get(0); - assertTrue(modifier instanceof PhysicalStimulation); - } + Reaction reaction = model1.getReactions().iterator().next(); - assertNull(reactant); - assertNotNull(product); - assertNull(modifier); + Product product = null; + if (reaction.getProducts().size() > 1) { + product = reaction.getProducts().get(1); + } + Reactant reactant = null; + if (reaction.getReactants().size() > 1) { + reactant = reaction.getReactants().get(1); + } + Modifier modifier = null; + if (reaction.getModifiers().size() > 0) { + modifier = reaction.getModifiers().get(0); + assertTrue(modifier instanceof PhysicalStimulation); + } - assertEquals(2, getWarnings().size()); + assertNull(reactant); + assertNotNull(product); + assertNull(modifier); - Model model2 = serializeModelOverCellDesignerParser(model1); + assertEquals(2, getWarnings().size()); - assertEquals(0, mc.compare(model1, model2)); + Model model2 = serializeModelOverCellDesignerParser(model1); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } @Test public void BindingInteractionDashedOutputTest() throws Exception { - try { - String fileName = "testFiles/reactions/interaction_dashed_mim_binding_output.gpml"; - - Model model1 = new GPMLToModel().getModel(fileName); + String fileName = "testFiles/reactions/interaction_dashed_mim_binding_output.gpml"; - assertEquals(1, model1.getReactions().size()); + Model model1 = new GPMLToModel().getModel(fileName); - Reaction reaction = model1.getReactions().iterator().next(); + assertEquals(1, model1.getReactions().size()); - Product product = null; - if (reaction.getProducts().size() > 1) { - product = reaction.getProducts().get(1); - } - Reactant reactant = null; - if (reaction.getReactants().size() > 1) { - reactant = reaction.getReactants().get(1); - } - Modifier modifier = null; - if (reaction.getModifiers().size() > 0) { - modifier = reaction.getModifiers().get(0); - assertTrue(modifier instanceof Modulation); - } + Reaction reaction = model1.getReactions().iterator().next(); - assertNull(reactant); - assertNotNull(product); - assertNull(modifier); + Product product = null; + if (reaction.getProducts().size() > 1) { + product = reaction.getProducts().get(1); + } + Reactant reactant = null; + if (reaction.getReactants().size() > 1) { + reactant = reaction.getReactants().get(1); + } + Modifier modifier = null; + if (reaction.getModifiers().size() > 0) { + modifier = reaction.getModifiers().get(0); + assertTrue(modifier instanceof Modulation); + } - assertEquals(2, getWarnings().size()); + assertNull(reactant); + assertNotNull(product); + assertNull(modifier); - Model model2 = serializeModelOverCellDesignerParser(model1); + assertEquals(2, getWarnings().size()); - assertEquals(0, mc.compare(model1, model2)); + Model model2 = serializeModelOverCellDesignerParser(model1); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } @Test public void ConversionInteractionDashedOutputTest() throws Exception { - try { - String fileName = "testFiles/reactions/interaction_dashed_mim_conversion_output.gpml"; - - Model model1 = new GPMLToModel().getModel(fileName); + String fileName = "testFiles/reactions/interaction_dashed_mim_conversion_output.gpml"; - assertEquals(1, model1.getReactions().size()); + Model model1 = new GPMLToModel().getModel(fileName); - Reaction reaction = model1.getReactions().iterator().next(); + assertEquals(1, model1.getReactions().size()); - Product product = null; - if (reaction.getProducts().size() > 1) { - product = reaction.getProducts().get(1); - } - Reactant reactant = null; - if (reaction.getReactants().size() > 1) { - reactant = reaction.getReactants().get(1); - } - Modifier modifier = null; - if (reaction.getModifiers().size() > 0) { - modifier = reaction.getModifiers().get(0); - assertTrue(modifier instanceof Modulation); - } + Reaction reaction = model1.getReactions().iterator().next(); - assertNull(reactant); - assertNotNull(product); - assertNull(modifier); + Product product = null; + if (reaction.getProducts().size() > 1) { + product = reaction.getProducts().get(1); + } + Reactant reactant = null; + if (reaction.getReactants().size() > 1) { + reactant = reaction.getReactants().get(1); + } + Modifier modifier = null; + if (reaction.getModifiers().size() > 0) { + modifier = reaction.getModifiers().get(0); + assertTrue(modifier instanceof Modulation); + } - assertEquals(2, getWarnings().size()); + assertNull(reactant); + assertNotNull(product); + assertNull(modifier); - Model model2 = serializeModelOverCellDesignerParser(model1); + assertEquals(2, getWarnings().size()); - assertEquals(0, mc.compare(model1, model2)); + Model model2 = serializeModelOverCellDesignerParser(model1); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } @Test public void StimulationInteractionDashedOutputTest() throws Exception { - try { - String fileName = "testFiles/reactions/interaction_dashed_mim_stimulation_output.gpml"; - - Model model1 = new GPMLToModel().getModel(fileName); + String fileName = "testFiles/reactions/interaction_dashed_mim_stimulation_output.gpml"; - assertEquals(1, model1.getReactions().size()); + Model model1 = new GPMLToModel().getModel(fileName); - Reaction reaction = model1.getReactions().iterator().next(); + assertEquals(1, model1.getReactions().size()); - Product product = null; - if (reaction.getProducts().size() > 1) { - product = reaction.getProducts().get(1); - } - Reactant reactant = null; - if (reaction.getReactants().size() > 1) { - reactant = reaction.getReactants().get(1); - } - Modifier modifier = null; - if (reaction.getModifiers().size() > 0) { - modifier = reaction.getModifiers().get(0); - assertTrue(modifier instanceof PhysicalStimulation); - } + Reaction reaction = model1.getReactions().iterator().next(); - assertNull(reactant); - assertNotNull(product); - assertNull(modifier); + Product product = null; + if (reaction.getProducts().size() > 1) { + product = reaction.getProducts().get(1); + } + Reactant reactant = null; + if (reaction.getReactants().size() > 1) { + reactant = reaction.getReactants().get(1); + } + Modifier modifier = null; + if (reaction.getModifiers().size() > 0) { + modifier = reaction.getModifiers().get(0); + assertTrue(modifier instanceof PhysicalStimulation); + } - assertEquals(2, getWarnings().size()); + assertNull(reactant); + assertNotNull(product); + assertNull(modifier); - Model model2 = serializeModelOverCellDesignerParser(model1); + assertEquals(2, getWarnings().size()); - assertEquals(0, mc.compare(model1, model2)); + Model model2 = serializeModelOverCellDesignerParser(model1); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } @Test public void ModificationInteractionDashedOutputTest() throws Exception { - try { - String fileName = "testFiles/reactions/interaction_dashed_mim_modification_output.gpml"; - - Model model1 = new GPMLToModel().getModel(fileName); + String fileName = "testFiles/reactions/interaction_dashed_mim_modification_output.gpml"; - assertEquals(1, model1.getReactions().size()); + Model model1 = new GPMLToModel().getModel(fileName); - Reaction reaction = model1.getReactions().iterator().next(); + assertEquals(1, model1.getReactions().size()); - Product product = null; - if (reaction.getProducts().size() > 1) { - product = reaction.getProducts().get(1); - } - Reactant reactant = null; - if (reaction.getReactants().size() > 1) { - reactant = reaction.getReactants().get(1); - } - Modifier modifier = null; - if (reaction.getModifiers().size() > 0) { - modifier = reaction.getModifiers().get(0); - assertTrue(modifier instanceof Modulation); - } + Reaction reaction = model1.getReactions().iterator().next(); - assertNull(reactant); - assertNotNull(product); - assertNull(modifier); + Product product = null; + if (reaction.getProducts().size() > 1) { + product = reaction.getProducts().get(1); + } + Reactant reactant = null; + if (reaction.getReactants().size() > 1) { + reactant = reaction.getReactants().get(1); + } + Modifier modifier = null; + if (reaction.getModifiers().size() > 0) { + modifier = reaction.getModifiers().get(0); + assertTrue(modifier instanceof Modulation); + } - assertEquals(2, getWarnings().size()); + assertNull(reactant); + assertNotNull(product); + assertNull(modifier); - Model model2 = serializeModelOverCellDesignerParser(model1); + assertEquals(2, getWarnings().size()); - assertEquals(0, mc.compare(model1, model2)); + Model model2 = serializeModelOverCellDesignerParser(model1); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } @Test public void CatalystInteractionDashedOutputTest() throws Exception { - try { - String fileName = "testFiles/reactions/interaction_dashed_mim_catalyst_output.gpml"; - - Model model1 = new GPMLToModel().getModel(fileName); + String fileName = "testFiles/reactions/interaction_dashed_mim_catalyst_output.gpml"; - assertEquals(1, model1.getReactions().size()); + Model model1 = new GPMLToModel().getModel(fileName); - Reaction reaction = model1.getReactions().iterator().next(); + assertEquals(1, model1.getReactions().size()); - Product product = null; - if (reaction.getProducts().size() > 1) { - product = reaction.getProducts().get(1); - } - Reactant reactant = null; - if (reaction.getReactants().size() > 1) { - reactant = reaction.getReactants().get(1); - } - Modifier modifier = null; - if (reaction.getModifiers().size() > 0) { - modifier = reaction.getModifiers().get(0); - assertTrue(modifier instanceof Catalysis); - } + Reaction reaction = model1.getReactions().iterator().next(); - assertNull(reactant); - assertNotNull(product); - assertNull(modifier); + Product product = null; + if (reaction.getProducts().size() > 1) { + product = reaction.getProducts().get(1); + } + Reactant reactant = null; + if (reaction.getReactants().size() > 1) { + reactant = reaction.getReactants().get(1); + } + Modifier modifier = null; + if (reaction.getModifiers().size() > 0) { + modifier = reaction.getModifiers().get(0); + assertTrue(modifier instanceof Catalysis); + } - assertEquals(2, getWarnings().size()); + assertNull(reactant); + assertNotNull(product); + assertNull(modifier); - Model model2 = serializeModelOverCellDesignerParser(model1); + assertEquals(2, getWarnings().size()); - assertEquals(0, mc.compare(model1, model2)); + Model model2 = serializeModelOverCellDesignerParser(model1); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } @Test public void InhibitionInteractionDashedOutputTest() throws Exception { - try { - String fileName = "testFiles/reactions/interaction_dashed_mim_inhibition_output.gpml"; - - Model model1 = new GPMLToModel().getModel(fileName); + String fileName = "testFiles/reactions/interaction_dashed_mim_inhibition_output.gpml"; - assertEquals(1, model1.getReactions().size()); + Model model1 = new GPMLToModel().getModel(fileName); - Reaction reaction = model1.getReactions().iterator().next(); + assertEquals(1, model1.getReactions().size()); - Product product = null; - if (reaction.getProducts().size() > 1) { - product = reaction.getProducts().get(1); - } - Reactant reactant = null; - if (reaction.getReactants().size() > 1) { - reactant = reaction.getReactants().get(1); - } - Modifier modifier = null; - if (reaction.getModifiers().size() > 0) { - modifier = reaction.getModifiers().get(0); - assertTrue(modifier instanceof Inhibition); - } + Reaction reaction = model1.getReactions().iterator().next(); - assertNull(reactant); - assertNotNull(product); - assertNull(modifier); + Product product = null; + if (reaction.getProducts().size() > 1) { + product = reaction.getProducts().get(1); + } + Reactant reactant = null; + if (reaction.getReactants().size() > 1) { + reactant = reaction.getReactants().get(1); + } + Modifier modifier = null; + if (reaction.getModifiers().size() > 0) { + modifier = reaction.getModifiers().get(0); + assertTrue(modifier instanceof Inhibition); + } - assertEquals(2, getWarnings().size()); + assertNull(reactant); + assertNotNull(product); + assertNull(modifier); - Model model2 = serializeModelOverCellDesignerParser(model1); + assertEquals(2, getWarnings().size()); - assertEquals(0, mc.compare(model1, model2)); + Model model2 = serializeModelOverCellDesignerParser(model1); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } @Test public void CleavageInteractionDashedOutputTest() throws Exception { - try { - String fileName = "testFiles/reactions/interaction_dashed_mim_cleavage_output.gpml"; - - Model model1 = new GPMLToModel().getModel(fileName); + String fileName = "testFiles/reactions/interaction_dashed_mim_cleavage_output.gpml"; - assertEquals(1, model1.getReactions().size()); + Model model1 = new GPMLToModel().getModel(fileName); - Reaction reaction = model1.getReactions().iterator().next(); + assertEquals(1, model1.getReactions().size()); - Product product = null; - if (reaction.getProducts().size() > 1) { - product = reaction.getProducts().get(1); - } - Reactant reactant = null; - if (reaction.getReactants().size() > 1) { - reactant = reaction.getReactants().get(1); - } - Modifier modifier = null; - if (reaction.getModifiers().size() > 0) { - modifier = reaction.getModifiers().get(0); - assertTrue(modifier instanceof Modulation); - } + Reaction reaction = model1.getReactions().iterator().next(); - assertNull(reactant); - assertNotNull(product); - assertNull(modifier); + Product product = null; + if (reaction.getProducts().size() > 1) { + product = reaction.getProducts().get(1); + } + Reactant reactant = null; + if (reaction.getReactants().size() > 1) { + reactant = reaction.getReactants().get(1); + } + Modifier modifier = null; + if (reaction.getModifiers().size() > 0) { + modifier = reaction.getModifiers().get(0); + assertTrue(modifier instanceof Modulation); + } - assertEquals(2, getWarnings().size()); + assertNull(reactant); + assertNotNull(product); + assertNull(modifier); - Model model2 = serializeModelOverCellDesignerParser(model1); + assertEquals(2, getWarnings().size()); - assertEquals(0, mc.compare(model1, model2)); + Model model2 = serializeModelOverCellDesignerParser(model1); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } @Test public void CovalentBondInteractionDashedOutputTest() throws Exception { - try { - String fileName = "testFiles/reactions/interaction_dashed_mim_covalent_bond_output.gpml"; - - Model model1 = new GPMLToModel().getModel(fileName); + String fileName = "testFiles/reactions/interaction_dashed_mim_covalent_bond_output.gpml"; - assertEquals(1, model1.getReactions().size()); + Model model1 = new GPMLToModel().getModel(fileName); - Reaction reaction = model1.getReactions().iterator().next(); + assertEquals(1, model1.getReactions().size()); - Product product = null; - if (reaction.getProducts().size() > 1) { - product = reaction.getProducts().get(1); - } - Reactant reactant = null; - if (reaction.getReactants().size() > 1) { - reactant = reaction.getReactants().get(1); - } - Modifier modifier = null; - if (reaction.getModifiers().size() > 0) { - modifier = reaction.getModifiers().get(0); - assertTrue(modifier instanceof Modifier); - } + Reaction reaction = model1.getReactions().iterator().next(); - assertNull(reactant); - assertNotNull(product); - assertNull(modifier); + Product product = null; + if (reaction.getProducts().size() > 1) { + product = reaction.getProducts().get(1); + } + Reactant reactant = null; + if (reaction.getReactants().size() > 1) { + reactant = reaction.getReactants().get(1); + } + Modifier modifier = null; + if (reaction.getModifiers().size() > 0) { + modifier = reaction.getModifiers().get(0); + assertTrue(modifier instanceof Modifier); + } - assertEquals(2, getWarnings().size()); + assertNull(reactant); + assertNotNull(product); + assertNull(modifier); - Model model2 = serializeModelOverCellDesignerParser(model1); + assertEquals(2, getWarnings().size()); - assertEquals(0, mc.compare(model1, model2)); + Model model2 = serializeModelOverCellDesignerParser(model1); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } @Test public void BranchingLeftInteractionDashedOutputTest() throws Exception { - try { - String fileName = "testFiles/reactions/interaction_dashed_mim_branching_left_output.gpml"; - - Model model1 = new GPMLToModel().getModel(fileName); + String fileName = "testFiles/reactions/interaction_dashed_mim_branching_left_output.gpml"; - assertEquals(1, model1.getReactions().size()); + Model model1 = new GPMLToModel().getModel(fileName); - Reaction reaction = model1.getReactions().iterator().next(); + assertEquals(1, model1.getReactions().size()); - Product product = null; - if (reaction.getProducts().size() > 1) { - product = reaction.getProducts().get(1); - } - Reactant reactant = null; - if (reaction.getReactants().size() > 1) { - reactant = reaction.getReactants().get(1); - } - Modifier modifier = null; - if (reaction.getModifiers().size() > 0) { - modifier = reaction.getModifiers().get(0); - assertTrue(modifier instanceof Modifier); - } + Reaction reaction = model1.getReactions().iterator().next(); - assertNotNull(reactant); - assertNull(product); - assertNull(modifier); + Product product = null; + if (reaction.getProducts().size() > 1) { + product = reaction.getProducts().get(1); + } + Reactant reactant = null; + if (reaction.getReactants().size() > 1) { + reactant = reaction.getReactants().get(1); + } + Modifier modifier = null; + if (reaction.getModifiers().size() > 0) { + modifier = reaction.getModifiers().get(0); + assertTrue(modifier instanceof Modifier); + } - assertEquals(2, getWarnings().size()); + assertNotNull(reactant); + assertNull(product); + assertNull(modifier); - Model model2 = serializeModelOverCellDesignerParser(model1); + assertEquals(2, getWarnings().size()); - assertEquals(0, mc.compare(model1, model2)); + Model model2 = serializeModelOverCellDesignerParser(model1); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } @Test public void BranchingRightInteractionDashedOutputTest() throws Exception { - try { - String fileName = "testFiles/reactions/interaction_dashed_mim_branching_right_output.gpml"; - - Model model1 = new GPMLToModel().getModel(fileName); + String fileName = "testFiles/reactions/interaction_dashed_mim_branching_right_output.gpml"; - assertEquals(1, model1.getReactions().size()); + Model model1 = new GPMLToModel().getModel(fileName); - Reaction reaction = model1.getReactions().iterator().next(); + assertEquals(1, model1.getReactions().size()); - Product product = null; - if (reaction.getProducts().size() > 1) { - product = reaction.getProducts().get(1); - } - Reactant reactant = null; - if (reaction.getReactants().size() > 1) { - reactant = reaction.getReactants().get(1); - } - Modifier modifier = null; - if (reaction.getModifiers().size() > 0) { - modifier = reaction.getModifiers().get(0); - assertTrue(modifier instanceof Modifier); - } + Reaction reaction = model1.getReactions().iterator().next(); - assertNotNull(reactant); - assertNull(product); - assertNull(modifier); + Product product = null; + if (reaction.getProducts().size() > 1) { + product = reaction.getProducts().get(1); + } + Reactant reactant = null; + if (reaction.getReactants().size() > 1) { + reactant = reaction.getReactants().get(1); + } + Modifier modifier = null; + if (reaction.getModifiers().size() > 0) { + modifier = reaction.getModifiers().get(0); + assertTrue(modifier instanceof Modifier); + } - assertEquals(2, getWarnings().size()); + assertNotNull(reactant); + assertNull(product); + assertNull(modifier); - Model model2 = serializeModelOverCellDesignerParser(model1); + assertEquals(2, getWarnings().size()); - assertEquals(0, mc.compare(model1, model2)); + Model model2 = serializeModelOverCellDesignerParser(model1); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } @Test public void TranscriptionTranslationInteractionDashedOutputTest() throws Exception { - try { - String fileName = "testFiles/reactions/interaction_dashed_mim_transcription_translation_output.gpml"; - - Model model1 = new GPMLToModel().getModel(fileName); + String fileName = "testFiles/reactions/interaction_dashed_mim_transcription_translation_output.gpml"; - assertEquals(1, model1.getReactions().size()); + Model model1 = new GPMLToModel().getModel(fileName); - Reaction reaction = model1.getReactions().iterator().next(); + assertEquals(1, model1.getReactions().size()); - Product product = null; - if (reaction.getProducts().size() > 1) { - product = reaction.getProducts().get(1); - } - Reactant reactant = null; - if (reaction.getReactants().size() > 1) { - reactant = reaction.getReactants().get(1); - } - Modifier modifier = null; - if (reaction.getModifiers().size() > 0) { - modifier = reaction.getModifiers().get(0); - assertTrue(modifier instanceof Modulation); - } + Reaction reaction = model1.getReactions().iterator().next(); - assertNull(reactant); - assertNotNull(product); - assertNull(modifier); + Product product = null; + if (reaction.getProducts().size() > 1) { + product = reaction.getProducts().get(1); + } + Reactant reactant = null; + if (reaction.getReactants().size() > 1) { + reactant = reaction.getReactants().get(1); + } + Modifier modifier = null; + if (reaction.getModifiers().size() > 0) { + modifier = reaction.getModifiers().get(0); + assertTrue(modifier instanceof Modulation); + } - assertEquals(2, getWarnings().size()); + assertNull(reactant); + assertNotNull(product); + assertNull(modifier); - Model model2 = serializeModelOverCellDesignerParser(model1); + assertEquals(2, getWarnings().size()); - assertEquals(0, mc.compare(model1, model2)); + Model model2 = serializeModelOverCellDesignerParser(model1); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } @Test public void GapInteractionDashedOutputTest() throws Exception { - try { - String fileName = "testFiles/reactions/interaction_dashed_mim_gap_output.gpml"; - - Model model1 = new GPMLToModel().getModel(fileName); + String fileName = "testFiles/reactions/interaction_dashed_mim_gap_output.gpml"; - assertEquals(1, model1.getReactions().size()); + Model model1 = new GPMLToModel().getModel(fileName); - Reaction reaction = model1.getReactions().iterator().next(); + assertEquals(1, model1.getReactions().size()); - Product product = null; - if (reaction.getProducts().size() > 1) { - product = reaction.getProducts().get(1); - } - Reactant reactant = null; - if (reaction.getReactants().size() > 1) { - reactant = reaction.getReactants().get(1); - } - Modifier modifier = null; - if (reaction.getModifiers().size() > 0) { - modifier = reaction.getModifiers().get(0); - assertTrue(modifier instanceof Modulation); - } + Reaction reaction = model1.getReactions().iterator().next(); - assertNull(reactant); - assertNotNull(product); - assertNull(modifier); + Product product = null; + if (reaction.getProducts().size() > 1) { + product = reaction.getProducts().get(1); + } + Reactant reactant = null; + if (reaction.getReactants().size() > 1) { + reactant = reaction.getReactants().get(1); + } + Modifier modifier = null; + if (reaction.getModifiers().size() > 0) { + modifier = reaction.getModifiers().get(0); + assertTrue(modifier instanceof Modulation); + } - assertEquals(2, getWarnings().size()); + assertNull(reactant); + assertNotNull(product); + assertNull(modifier); - Model model2 = serializeModelOverCellDesignerParser(model1); + assertEquals(2, getWarnings().size()); - assertEquals(0, mc.compare(model1, model2)); + Model model2 = serializeModelOverCellDesignerParser(model1); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } } diff --git a/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/ReactionGpmlToModelTest.java b/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/ReactionGpmlToModelTest.java index 9711e06417187656b1752297a82faeba03c886c1..0337186314863a028db1bc9de78a741bfcefca52 100644 --- a/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/ReactionGpmlToModelTest.java +++ b/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/ReactionGpmlToModelTest.java @@ -1,23 +1,15 @@ package lcsb.mapviewer.wikipathway; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.Assert.*; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.junit.Test; import lcsb.mapviewer.model.map.model.Model; import lcsb.mapviewer.model.map.model.ModelComparator; import lcsb.mapviewer.model.map.reaction.Reaction; -import lcsb.mapviewer.model.map.reaction.type.HeterodimerAssociationReaction; -import lcsb.mapviewer.model.map.reaction.type.NegativeInfluenceReaction; -import lcsb.mapviewer.model.map.reaction.type.PositiveInfluenceReaction; -import lcsb.mapviewer.model.map.reaction.type.ReducedPhysicalStimulationReaction; -import lcsb.mapviewer.model.map.reaction.type.StateTransitionReaction; -import lcsb.mapviewer.model.map.reaction.type.UnknownNegativeInfluenceReaction; -import lcsb.mapviewer.model.map.reaction.type.UnknownPositiveInfluenceReaction; -import lcsb.mapviewer.model.map.reaction.type.UnknownTransitionReaction; +import lcsb.mapviewer.model.map.reaction.type.*; import lcsb.mapviewer.wikipathway.XML.GPMLToModel; public class ReactionGpmlToModelTest extends WikipathwaysTestFunctions { @@ -30,843 +22,667 @@ public class ReactionGpmlToModelTest extends WikipathwaysTestFunctions { @Test public void LineInteractionTest() throws Exception { - try { - String fileName = "testFiles/reactions/interaction_line.gpml"; + String fileName = "testFiles/reactions/interaction_line.gpml"; - Model model1 = new GPMLToModel().getModel(fileName); + Model model1 = new GPMLToModel().getModel(fileName); - assertEquals(1, model1.getReactions().size()); + assertEquals(1, model1.getReactions().size()); - Reaction reaction = model1.getReactions().iterator().next(); + Reaction reaction = model1.getReactions().iterator().next(); - assertEquals(1, getWarnings().size()); - assertTrue(reaction instanceof UnknownTransitionReaction); - assertTrue(reaction.isReversible()); + assertEquals(1, getWarnings().size()); + assertTrue(reaction instanceof UnknownTransitionReaction); + assertTrue(reaction.isReversible()); - Model model2 = serializeModelOverCellDesignerParser(model1); + Model model2 = serializeModelOverCellDesignerParser(model1); - assertEquals(0, mc.compare(model1, model2)); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } @Test public void ArrowInteractionTest() throws Exception { - try { - String fileName = "testFiles/reactions/interaction_arrow.gpml"; + String fileName = "testFiles/reactions/interaction_arrow.gpml"; - Model model1 = new GPMLToModel().getModel(fileName); + Model model1 = new GPMLToModel().getModel(fileName); - assertEquals(1, model1.getReactions().size()); + assertEquals(1, model1.getReactions().size()); - Reaction reaction = model1.getReactions().iterator().next(); + Reaction reaction = model1.getReactions().iterator().next(); - assertEquals(0, getWarnings().size()); - assertTrue(reaction instanceof StateTransitionReaction); - assertFalse(reaction.isReversible()); + assertEquals(0, getWarnings().size()); + assertTrue(reaction instanceof StateTransitionReaction); + assertFalse(reaction.isReversible()); - Model model2 = serializeModelOverCellDesignerParser(model1); + Model model2 = serializeModelOverCellDesignerParser(model1); - assertEquals(0, mc.compare(model1, model2)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } @Test public void DashedArrowInteractionTest() throws Exception { - try { - String fileName = "testFiles/reactions/interaction_dashed_arrow.gpml"; + String fileName = "testFiles/reactions/interaction_dashed_arrow.gpml"; - Model model1 = new GPMLToModel().getModel(fileName); + Model model1 = new GPMLToModel().getModel(fileName); - assertEquals(1, model1.getReactions().size()); + assertEquals(1, model1.getReactions().size()); - Reaction reaction = model1.getReactions().iterator().next(); + Reaction reaction = model1.getReactions().iterator().next(); - assertEquals(0, getWarnings().size()); - assertTrue(reaction instanceof UnknownPositiveInfluenceReaction); - assertFalse(reaction.isReversible()); + assertEquals(0, getWarnings().size()); + assertTrue(reaction instanceof UnknownPositiveInfluenceReaction); + assertFalse(reaction.isReversible()); - Model model2 = serializeModelOverCellDesignerParser(model1); + Model model2 = serializeModelOverCellDesignerParser(model1); - assertEquals(0, mc.compare(model1, model2)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } @Test public void DashedLineInteractionTest() throws Exception { - try { - String fileName = "testFiles/reactions/interaction_dashed_line.gpml"; + String fileName = "testFiles/reactions/interaction_dashed_line.gpml"; - Model model1 = new GPMLToModel().getModel(fileName); + Model model1 = new GPMLToModel().getModel(fileName); - assertEquals(1, model1.getReactions().size()); + assertEquals(1, model1.getReactions().size()); - Reaction reaction = model1.getReactions().iterator().next(); + Reaction reaction = model1.getReactions().iterator().next(); - assertEquals(1, getWarnings().size()); - assertTrue(reaction instanceof UnknownTransitionReaction); - assertTrue(reaction.isReversible()); + assertEquals(1, getWarnings().size()); + assertTrue(reaction instanceof UnknownTransitionReaction); + assertTrue(reaction.isReversible()); - Model model2 = serializeModelOverCellDesignerParser(model1); + Model model2 = serializeModelOverCellDesignerParser(model1); - assertEquals(0, mc.compare(model1, model2)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } @Test public void BindingInteractionTest() throws Exception { - try { - // invalid mim_binding (contains only one reactant) - String fileName = "testFiles/reactions/interaction_mim_binding.gpml"; + // invalid mim_binding (contains only one reactant) + String fileName = "testFiles/reactions/interaction_mim_binding.gpml"; - Model model1 = new GPMLToModel().getModel(fileName); + Model model1 = new GPMLToModel().getModel(fileName); - assertEquals(1, model1.getReactions().size()); + assertEquals(1, model1.getReactions().size()); - Reaction reaction = model1.getReactions().iterator().next(); + Reaction reaction = model1.getReactions().iterator().next(); - assertEquals(1, getWarnings().size()); - assertTrue(reaction instanceof UnknownTransitionReaction); - assertFalse(reaction.isReversible()); + assertEquals(1, getWarnings().size()); + assertTrue(reaction instanceof UnknownTransitionReaction); + assertFalse(reaction.isReversible()); - Model model2 = serializeModelOverCellDesignerParser(model1); + Model model2 = serializeModelOverCellDesignerParser(model1); - assertEquals(0, mc.compare(model1, model2)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } @Test public void BindingInteractionTest2() throws Exception { - try { - // proper mim_binding (contains two reactants) - String fileName = "testFiles/reactions/interaction_mim_binding2.gpml"; + // proper mim_binding (contains two reactants) + String fileName = "testFiles/reactions/interaction_mim_binding2.gpml"; - Model model1 = new GPMLToModel().getModel(fileName); + Model model1 = new GPMLToModel().getModel(fileName); - assertEquals(1, model1.getReactions().size()); + assertEquals(1, model1.getReactions().size()); - Reaction reaction = model1.getReactions().iterator().next(); + Reaction reaction = model1.getReactions().iterator().next(); - assertEquals(getWarnings().toString(), 0, getWarnings().size()); - assertTrue(reaction instanceof HeterodimerAssociationReaction); - assertFalse(reaction.isReversible()); - assertEquals(2, reaction.getReactants().size()); + assertEquals(getWarnings().toString(), 0, getWarnings().size()); + assertTrue(reaction instanceof HeterodimerAssociationReaction); + assertFalse(reaction.isReversible()); + assertEquals(2, reaction.getReactants().size()); - Model model2 = serializeModelOverCellDesignerParser(model1); - assertEquals(0, mc.compare(model1, model2)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Model model2 = serializeModelOverCellDesignerParser(model1); + assertEquals(0, mc.compare(model1, model2)); } @Test public void BranchingLeftInteractionTest() throws Exception { - try { - String fileName = "testFiles/reactions/interaction_mim_branching_left.gpml"; + String fileName = "testFiles/reactions/interaction_mim_branching_left.gpml"; - Model model1 = new GPMLToModel().getModel(fileName); + Model model1 = new GPMLToModel().getModel(fileName); - assertEquals(1, model1.getReactions().size()); + assertEquals(1, model1.getReactions().size()); - Reaction reaction = model1.getReactions().iterator().next(); + Reaction reaction = model1.getReactions().iterator().next(); - assertEquals(1, getWarnings().size()); - assertTrue(reaction instanceof UnknownTransitionReaction); - assertTrue(reaction.isReversible()); + assertEquals(1, getWarnings().size()); + assertTrue(reaction instanceof UnknownTransitionReaction); + assertTrue(reaction.isReversible()); - Model model2 = serializeModelOverCellDesignerParser(model1); + Model model2 = serializeModelOverCellDesignerParser(model1); - assertEquals(0, mc.compare(model1, model2)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } @Test public void BranchingRightInteractionTest() throws Exception { - try { - String fileName = "testFiles/reactions/interaction_mim_branching_right.gpml"; + String fileName = "testFiles/reactions/interaction_mim_branching_right.gpml"; - Model model1 = new GPMLToModel().getModel(fileName); + Model model1 = new GPMLToModel().getModel(fileName); - assertEquals(1, model1.getReactions().size()); + assertEquals(1, model1.getReactions().size()); - Reaction reaction = model1.getReactions().iterator().next(); + Reaction reaction = model1.getReactions().iterator().next(); - assertEquals(1, getWarnings().size()); - assertTrue(reaction instanceof UnknownTransitionReaction); - assertTrue(reaction.isReversible()); + assertEquals(1, getWarnings().size()); + assertTrue(reaction instanceof UnknownTransitionReaction); + assertTrue(reaction.isReversible()); - Model model2 = serializeModelOverCellDesignerParser(model1); + Model model2 = serializeModelOverCellDesignerParser(model1); - assertEquals(0, mc.compare(model1, model2)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } @Test public void CatalystInteractionTest() throws Exception { - try { - String fileName = "testFiles/reactions/interaction_mim_catalyst.gpml"; + String fileName = "testFiles/reactions/interaction_mim_catalyst.gpml"; - Model model1 = new GPMLToModel().getModel(fileName); + Model model1 = new GPMLToModel().getModel(fileName); - assertEquals(1, model1.getReactions().size()); + assertEquals(1, model1.getReactions().size()); - Reaction reaction = model1.getReactions().iterator().next(); + Reaction reaction = model1.getReactions().iterator().next(); - assertEquals(1, getWarnings().size()); - assertTrue(reaction instanceof PositiveInfluenceReaction); - assertFalse(reaction.isReversible()); + assertEquals(1, getWarnings().size()); + assertTrue(reaction instanceof PositiveInfluenceReaction); + assertFalse(reaction.isReversible()); - Model model2 = serializeModelOverCellDesignerParser(model1); + Model model2 = serializeModelOverCellDesignerParser(model1); - assertEquals(0, mc.compare(model1, model2)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } @Test public void CleavageInteractionTest() throws Exception { - try { - String fileName = "testFiles/reactions/interaction_mim_cleavage.gpml"; + String fileName = "testFiles/reactions/interaction_mim_cleavage.gpml"; - Model model1 = new GPMLToModel().getModel(fileName); + Model model1 = new GPMLToModel().getModel(fileName); - assertEquals(1, model1.getReactions().size()); + assertEquals(1, model1.getReactions().size()); - Reaction reaction = model1.getReactions().iterator().next(); + Reaction reaction = model1.getReactions().iterator().next(); - assertEquals(0, getWarnings().size()); - assertTrue(reaction instanceof StateTransitionReaction); - assertFalse(reaction.isReversible()); + assertEquals(0, getWarnings().size()); + assertTrue(reaction instanceof StateTransitionReaction); + assertFalse(reaction.isReversible()); - Model model2 = serializeModelOverCellDesignerParser(model1); + Model model2 = serializeModelOverCellDesignerParser(model1); - assertEquals(0, mc.compare(model1, model2)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } @Test public void ConversionInteractionTest() throws Exception { - try { - String fileName = "testFiles/reactions/interaction_mim_conversion.gpml"; + String fileName = "testFiles/reactions/interaction_mim_conversion.gpml"; - Model model1 = new GPMLToModel().getModel(fileName); + Model model1 = new GPMLToModel().getModel(fileName); - assertEquals(1, model1.getReactions().size()); + assertEquals(1, model1.getReactions().size()); - Reaction reaction = model1.getReactions().iterator().next(); + Reaction reaction = model1.getReactions().iterator().next(); - assertEquals(0, getWarnings().size()); - assertTrue(reaction instanceof StateTransitionReaction); - assertFalse(reaction.isReversible()); + assertEquals(0, getWarnings().size()); + assertTrue(reaction instanceof StateTransitionReaction); + assertFalse(reaction.isReversible()); - Model model2 = serializeModelOverCellDesignerParser(model1); + Model model2 = serializeModelOverCellDesignerParser(model1); - assertEquals(0, mc.compare(model1, model2)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } @Test public void CovalentBondInteractionTest() throws Exception { - try { - String fileName = "testFiles/reactions/interaction_mim_covalent_bond.gpml"; + String fileName = "testFiles/reactions/interaction_mim_covalent_bond.gpml"; - Model model1 = new GPMLToModel().getModel(fileName); + Model model1 = new GPMLToModel().getModel(fileName); - assertEquals(1, model1.getReactions().size()); + assertEquals(1, model1.getReactions().size()); - Reaction reaction = model1.getReactions().iterator().next(); + Reaction reaction = model1.getReactions().iterator().next(); - assertEquals(1, getWarnings().size()); - assertTrue(reaction instanceof UnknownTransitionReaction); - assertTrue(reaction.isReversible()); + assertEquals(1, getWarnings().size()); + assertTrue(reaction instanceof UnknownTransitionReaction); + assertTrue(reaction.isReversible()); - Model model2 = serializeModelOverCellDesignerParser(model1); + Model model2 = serializeModelOverCellDesignerParser(model1); - assertEquals(0, mc.compare(model1, model2)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } @Test public void GapInteractionTest() throws Exception { - try { - String fileName = "testFiles/reactions/interaction_mim_gap.gpml"; + String fileName = "testFiles/reactions/interaction_mim_gap.gpml"; - Model model1 = new GPMLToModel().getModel(fileName); + Model model1 = new GPMLToModel().getModel(fileName); - assertEquals(1, model1.getReactions().size()); + assertEquals(1, model1.getReactions().size()); - Reaction reaction = model1.getReactions().iterator().next(); + Reaction reaction = model1.getReactions().iterator().next(); - assertEquals(1, getWarnings().size()); - assertTrue(reaction instanceof UnknownTransitionReaction); - assertTrue(reaction.isReversible()); + assertEquals(1, getWarnings().size()); + assertTrue(reaction instanceof UnknownTransitionReaction); + assertTrue(reaction.isReversible()); - Model model2 = serializeModelOverCellDesignerParser(model1); + Model model2 = serializeModelOverCellDesignerParser(model1); - assertEquals(0, mc.compare(model1, model2)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } @Test public void InhibitionInteractionTest() throws Exception { - try { - String fileName = "testFiles/reactions/interaction_mim_inhibition.gpml"; + String fileName = "testFiles/reactions/interaction_mim_inhibition.gpml"; - Model model1 = new GPMLToModel().getModel(fileName); + Model model1 = new GPMLToModel().getModel(fileName); - assertEquals(1, model1.getReactions().size()); + assertEquals(1, model1.getReactions().size()); - Reaction reaction = model1.getReactions().iterator().next(); + Reaction reaction = model1.getReactions().iterator().next(); - assertEquals(0, getWarnings().size()); - assertTrue(reaction instanceof NegativeInfluenceReaction); - assertFalse(reaction.isReversible()); + assertEquals(0, getWarnings().size()); + assertTrue(reaction instanceof NegativeInfluenceReaction); + assertFalse(reaction.isReversible()); - Model model2 = serializeModelOverCellDesignerParser(model1); + Model model2 = serializeModelOverCellDesignerParser(model1); - assertEquals(0, mc.compare(model1, model2)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } @Test public void ModificationInteractionTest() throws Exception { - try { - String fileName = "testFiles/reactions/interaction_mim_modification.gpml"; + String fileName = "testFiles/reactions/interaction_mim_modification.gpml"; - Model model1 = new GPMLToModel().getModel(fileName); + Model model1 = new GPMLToModel().getModel(fileName); - assertEquals(1, model1.getReactions().size()); + assertEquals(1, model1.getReactions().size()); - Reaction reaction = model1.getReactions().iterator().next(); + Reaction reaction = model1.getReactions().iterator().next(); - assertEquals(1, getWarnings().size()); - assertTrue(reaction instanceof PositiveInfluenceReaction); - assertFalse(reaction.isReversible()); + assertEquals(1, getWarnings().size()); + assertTrue(reaction instanceof PositiveInfluenceReaction); + assertFalse(reaction.isReversible()); - Model model2 = serializeModelOverCellDesignerParser(model1); + Model model2 = serializeModelOverCellDesignerParser(model1); - assertEquals(0, mc.compare(model1, model2)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } @Test public void NecessaryStimulationInteractionTest() throws Exception { - try { - String fileName = "testFiles/reactions/interaction_mim_necessary_stimulation.gpml"; + String fileName = "testFiles/reactions/interaction_mim_necessary_stimulation.gpml"; - Model model1 = new GPMLToModel().getModel(fileName); + Model model1 = new GPMLToModel().getModel(fileName); - assertEquals(1, model1.getReactions().size()); + assertEquals(1, model1.getReactions().size()); - Reaction reaction = model1.getReactions().iterator().next(); + Reaction reaction = model1.getReactions().iterator().next(); - assertEquals(0, getWarnings().size()); - assertTrue(reaction instanceof ReducedPhysicalStimulationReaction); - assertFalse(reaction.isReversible()); + assertEquals(0, getWarnings().size()); + assertTrue(reaction instanceof ReducedPhysicalStimulationReaction); + assertFalse(reaction.isReversible()); - Model model2 = serializeModelOverCellDesignerParser(model1); + Model model2 = serializeModelOverCellDesignerParser(model1); - assertEquals(0, mc.compare(model1, model2)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } @Test public void StimulationInteractionTest() throws Exception { - try { - String fileName = "testFiles/reactions/interaction_mim_stimulation.gpml"; + String fileName = "testFiles/reactions/interaction_mim_stimulation.gpml"; - Model model1 = new GPMLToModel().getModel(fileName); + Model model1 = new GPMLToModel().getModel(fileName); - assertEquals(1, model1.getReactions().size()); + assertEquals(1, model1.getReactions().size()); - Reaction reaction = model1.getReactions().iterator().next(); + Reaction reaction = model1.getReactions().iterator().next(); - assertEquals(1, getWarnings().size()); - assertTrue(reaction instanceof ReducedPhysicalStimulationReaction); - assertFalse(reaction.isReversible()); + assertEquals(1, getWarnings().size()); + assertTrue(reaction instanceof ReducedPhysicalStimulationReaction); + assertFalse(reaction.isReversible()); - Model model2 = serializeModelOverCellDesignerParser(model1); + Model model2 = serializeModelOverCellDesignerParser(model1); - assertEquals(0, mc.compare(model1, model2)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } @Test public void TranscriptionTranslationInteractionTest() throws Exception { - try { - String fileName = "testFiles/reactions/interaction_mim_transcription_translation.gpml"; + String fileName = "testFiles/reactions/interaction_mim_transcription_translation.gpml"; - Model model1 = new GPMLToModel().getModel(fileName); + Model model1 = new GPMLToModel().getModel(fileName); - assertEquals(1, model1.getReactions().size()); + assertEquals(1, model1.getReactions().size()); - Reaction reaction = model1.getReactions().iterator().next(); + Reaction reaction = model1.getReactions().iterator().next(); - assertEquals(1, getWarnings().size()); - assertTrue(reaction instanceof PositiveInfluenceReaction); - assertFalse(reaction.isReversible()); + assertEquals(1, getWarnings().size()); + assertTrue(reaction instanceof PositiveInfluenceReaction); + assertFalse(reaction.isReversible()); - Model model2 = serializeModelOverCellDesignerParser(model1); + Model model2 = serializeModelOverCellDesignerParser(model1); - assertEquals(0, mc.compare(model1, model2)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } @Test public void TbarTranslationInteractionTest() throws Exception { - try { - String fileName = "testFiles/reactions/interaction_tbar.gpml"; + String fileName = "testFiles/reactions/interaction_tbar.gpml"; - Model model1 = new GPMLToModel().getModel(fileName); + Model model1 = new GPMLToModel().getModel(fileName); - assertEquals(1, model1.getReactions().size()); + assertEquals(1, model1.getReactions().size()); - Reaction reaction = model1.getReactions().iterator().next(); + Reaction reaction = model1.getReactions().iterator().next(); - assertEquals(1, getWarnings().size()); - assertTrue(reaction instanceof NegativeInfluenceReaction); - assertFalse(reaction.isReversible()); + assertEquals(1, getWarnings().size()); + assertTrue(reaction instanceof NegativeInfluenceReaction); + assertFalse(reaction.isReversible()); - Model model2 = serializeModelOverCellDesignerParser(model1); + Model model2 = serializeModelOverCellDesignerParser(model1); - assertEquals(0, mc.compare(model1, model2)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } @Test public void LineAsInteractionTest2() throws Exception { - try { - // proper mim_binding (contains two reactants) - String fileName = "testFiles/reactions/line_as_interaction.gpml"; + // proper mim_binding (contains two reactants) + String fileName = "testFiles/reactions/line_as_interaction.gpml"; - Model model1 = new GPMLToModel().getModel(fileName); + Model model1 = new GPMLToModel().getModel(fileName); - assertEquals(1, model1.getReactions().size()); + assertEquals(1, model1.getReactions().size()); - Reaction reaction = model1.getReactions().iterator().next(); + Reaction reaction = model1.getReactions().iterator().next(); - assertEquals(1, getWarnings().size()); - assertTrue(reaction instanceof UnknownTransitionReaction); - assertTrue(reaction.isReversible()); + assertEquals(1, getWarnings().size()); + assertTrue(reaction instanceof UnknownTransitionReaction); + assertTrue(reaction.isReversible()); - Model model2 = serializeModelOverCellDesignerParser(model1); + Model model2 = serializeModelOverCellDesignerParser(model1); - assertEquals(0, mc.compare(model1, model2)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } @Test public void BindingInteractionDashedTest() throws Exception { - try { - // invalid mim_binding (contains only one reactant) - String fileName = "testFiles/reactions/interaction_dashed_mim_binding.gpml"; + // invalid mim_binding (contains only one reactant) + String fileName = "testFiles/reactions/interaction_dashed_mim_binding.gpml"; - Model model1 = new GPMLToModel().getModel(fileName); + Model model1 = new GPMLToModel().getModel(fileName); - assertEquals(1, model1.getReactions().size()); + assertEquals(1, model1.getReactions().size()); - Reaction reaction = model1.getReactions().iterator().next(); + Reaction reaction = model1.getReactions().iterator().next(); - assertEquals(0, getWarnings().size()); - assertTrue(reaction instanceof UnknownPositiveInfluenceReaction); - assertFalse(reaction.isReversible()); + assertEquals(0, getWarnings().size()); + assertTrue(reaction instanceof UnknownPositiveInfluenceReaction); + assertFalse(reaction.isReversible()); - Model model2 = serializeModelOverCellDesignerParser(model1); + Model model2 = serializeModelOverCellDesignerParser(model1); - assertEquals(0, mc.compare(model1, model2)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } @Test public void BranchingLeftInteractionDashedTest() throws Exception { - try { - String fileName = "testFiles/reactions/interaction_dashed_mim_branching_left.gpml"; + String fileName = "testFiles/reactions/interaction_dashed_mim_branching_left.gpml"; - Model model1 = new GPMLToModel().getModel(fileName); + Model model1 = new GPMLToModel().getModel(fileName); - assertEquals(1, model1.getReactions().size()); + assertEquals(1, model1.getReactions().size()); - Reaction reaction = model1.getReactions().iterator().next(); + Reaction reaction = model1.getReactions().iterator().next(); - assertEquals(1, getWarnings().size()); - assertTrue(reaction instanceof UnknownTransitionReaction); - assertTrue(reaction.isReversible()); + assertEquals(1, getWarnings().size()); + assertTrue(reaction instanceof UnknownTransitionReaction); + assertTrue(reaction.isReversible()); - Model model2 = serializeModelOverCellDesignerParser(model1); + Model model2 = serializeModelOverCellDesignerParser(model1); - assertEquals(0, mc.compare(model1, model2)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } @Test public void BranchingRightInteractionDashedTest() throws Exception { - try { - String fileName = "testFiles/reactions/interaction_dashed_mim_branching_right.gpml"; + String fileName = "testFiles/reactions/interaction_dashed_mim_branching_right.gpml"; - Model model1 = new GPMLToModel().getModel(fileName); + Model model1 = new GPMLToModel().getModel(fileName); - assertEquals(1, model1.getReactions().size()); + assertEquals(1, model1.getReactions().size()); - Reaction reaction = model1.getReactions().iterator().next(); + Reaction reaction = model1.getReactions().iterator().next(); - assertEquals(1, getWarnings().size()); - assertTrue(reaction instanceof UnknownTransitionReaction); - assertTrue(reaction.isReversible()); + assertEquals(1, getWarnings().size()); + assertTrue(reaction instanceof UnknownTransitionReaction); + assertTrue(reaction.isReversible()); - Model model2 = serializeModelOverCellDesignerParser(model1); + Model model2 = serializeModelOverCellDesignerParser(model1); - assertEquals(0, mc.compare(model1, model2)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } @Test public void CatalystInteractionDashedTest() throws Exception { - try { - String fileName = "testFiles/reactions/interaction_dashed_mim_catalyst.gpml"; + String fileName = "testFiles/reactions/interaction_dashed_mim_catalyst.gpml"; - Model model1 = new GPMLToModel().getModel(fileName); + Model model1 = new GPMLToModel().getModel(fileName); - assertEquals(1, model1.getReactions().size()); + assertEquals(1, model1.getReactions().size()); - Reaction reaction = model1.getReactions().iterator().next(); + Reaction reaction = model1.getReactions().iterator().next(); - assertEquals(1, getWarnings().size()); - assertTrue(reaction instanceof UnknownPositiveInfluenceReaction); - assertFalse(reaction.isReversible()); + assertEquals(1, getWarnings().size()); + assertTrue(reaction instanceof UnknownPositiveInfluenceReaction); + assertFalse(reaction.isReversible()); - Model model2 = serializeModelOverCellDesignerParser(model1); + Model model2 = serializeModelOverCellDesignerParser(model1); - assertEquals(0, mc.compare(model1, model2)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } @Test public void CleavageInteractionDashedTest() throws Exception { - try { - String fileName = "testFiles/reactions/interaction_dashed_mim_cleavage.gpml"; + String fileName = "testFiles/reactions/interaction_dashed_mim_cleavage.gpml"; - Model model1 = new GPMLToModel().getModel(fileName); + Model model1 = new GPMLToModel().getModel(fileName); - assertEquals(1, model1.getReactions().size()); + assertEquals(1, model1.getReactions().size()); - Reaction reaction = model1.getReactions().iterator().next(); + Reaction reaction = model1.getReactions().iterator().next(); - assertEquals(1, getWarnings().size()); - assertTrue(reaction instanceof UnknownTransitionReaction); - assertFalse(reaction.isReversible()); + assertEquals(1, getWarnings().size()); + assertTrue(reaction instanceof UnknownTransitionReaction); + assertFalse(reaction.isReversible()); - Model model2 = serializeModelOverCellDesignerParser(model1); + Model model2 = serializeModelOverCellDesignerParser(model1); - assertEquals(0, mc.compare(model1, model2)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } @Test public void ConversionInteractionDashedTest() throws Exception { - try { - String fileName = "testFiles/reactions/interaction_dashed_mim_conversion.gpml"; + String fileName = "testFiles/reactions/interaction_dashed_mim_conversion.gpml"; - Model model1 = new GPMLToModel().getModel(fileName); + Model model1 = new GPMLToModel().getModel(fileName); - assertEquals(1, model1.getReactions().size()); + assertEquals(1, model1.getReactions().size()); - Reaction reaction = model1.getReactions().iterator().next(); + Reaction reaction = model1.getReactions().iterator().next(); - assertEquals(0, getWarnings().size()); - assertTrue(reaction instanceof UnknownPositiveInfluenceReaction); - assertFalse(reaction.isReversible()); + assertEquals(0, getWarnings().size()); + assertTrue(reaction instanceof UnknownPositiveInfluenceReaction); + assertFalse(reaction.isReversible()); - Model model2 = serializeModelOverCellDesignerParser(model1); + Model model2 = serializeModelOverCellDesignerParser(model1); - assertEquals(0, mc.compare(model1, model2)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } @Test public void CovalentBondInteractionDashedTest() throws Exception { - try { - String fileName = "testFiles/reactions/interaction_dashed_mim_covalent_bond.gpml"; + String fileName = "testFiles/reactions/interaction_dashed_mim_covalent_bond.gpml"; - Model model1 = new GPMLToModel().getModel(fileName); + Model model1 = new GPMLToModel().getModel(fileName); - assertEquals(1, model1.getReactions().size()); + assertEquals(1, model1.getReactions().size()); - Reaction reaction = model1.getReactions().iterator().next(); + Reaction reaction = model1.getReactions().iterator().next(); - assertEquals(1, getWarnings().size()); - assertTrue(reaction instanceof UnknownTransitionReaction); - assertTrue(reaction.isReversible()); + assertEquals(1, getWarnings().size()); + assertTrue(reaction instanceof UnknownTransitionReaction); + assertTrue(reaction.isReversible()); - Model model2 = serializeModelOverCellDesignerParser(model1); + Model model2 = serializeModelOverCellDesignerParser(model1); - assertEquals(0, mc.compare(model1, model2)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } @Test public void GapInteractionDashedTest() throws Exception { - try { - String fileName = "testFiles/reactions/interaction_dashed_mim_gap.gpml"; + String fileName = "testFiles/reactions/interaction_dashed_mim_gap.gpml"; - Model model1 = new GPMLToModel().getModel(fileName); + Model model1 = new GPMLToModel().getModel(fileName); - assertEquals(1, model1.getReactions().size()); + assertEquals(1, model1.getReactions().size()); - Reaction reaction = model1.getReactions().iterator().next(); + Reaction reaction = model1.getReactions().iterator().next(); - assertEquals(1, getWarnings().size()); - assertTrue(reaction instanceof UnknownTransitionReaction); - assertTrue(reaction.isReversible()); + assertEquals(1, getWarnings().size()); + assertTrue(reaction instanceof UnknownTransitionReaction); + assertTrue(reaction.isReversible()); - Model model2 = serializeModelOverCellDesignerParser(model1); + Model model2 = serializeModelOverCellDesignerParser(model1); - assertEquals(0, mc.compare(model1, model2)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } @Test public void InhibitionInteractionDashedTest() throws Exception { - try { - String fileName = "testFiles/reactions/interaction_dashed_mim_inhibition.gpml"; + String fileName = "testFiles/reactions/interaction_dashed_mim_inhibition.gpml"; - Model model1 = new GPMLToModel().getModel(fileName); + Model model1 = new GPMLToModel().getModel(fileName); - assertEquals(1, model1.getReactions().size()); + assertEquals(1, model1.getReactions().size()); - Reaction reaction = model1.getReactions().iterator().next(); + Reaction reaction = model1.getReactions().iterator().next(); - assertEquals(1, getWarnings().size()); - assertTrue(reaction instanceof UnknownNegativeInfluenceReaction); - assertFalse(reaction.isReversible()); + assertEquals(1, getWarnings().size()); + assertTrue(reaction instanceof UnknownNegativeInfluenceReaction); + assertFalse(reaction.isReversible()); - Model model2 = serializeModelOverCellDesignerParser(model1); + Model model2 = serializeModelOverCellDesignerParser(model1); - assertEquals(0, mc.compare(model1, model2)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } @Test public void ModificationInteractionDashedTest() throws Exception { - try { - String fileName = "testFiles/reactions/interaction_dashed_mim_modification.gpml"; + String fileName = "testFiles/reactions/interaction_dashed_mim_modification.gpml"; - Model model1 = new GPMLToModel().getModel(fileName); + Model model1 = new GPMLToModel().getModel(fileName); - assertEquals(1, model1.getReactions().size()); + assertEquals(1, model1.getReactions().size()); - Reaction reaction = model1.getReactions().iterator().next(); + Reaction reaction = model1.getReactions().iterator().next(); - assertEquals(0, getWarnings().size()); - assertTrue(reaction instanceof UnknownPositiveInfluenceReaction); - assertFalse(reaction.isReversible()); + assertEquals(0, getWarnings().size()); + assertTrue(reaction instanceof UnknownPositiveInfluenceReaction); + assertFalse(reaction.isReversible()); - Model model2 = serializeModelOverCellDesignerParser(model1); + Model model2 = serializeModelOverCellDesignerParser(model1); - assertEquals(0, mc.compare(model1, model2)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } @Test public void NecessaryStimulationInteractionDashedTest() throws Exception { - try { - String fileName = "testFiles/reactions/interaction_dashed_mim_necessary_stimulation.gpml"; + String fileName = "testFiles/reactions/interaction_dashed_mim_necessary_stimulation.gpml"; - Model model1 = new GPMLToModel().getModel(fileName); + Model model1 = new GPMLToModel().getModel(fileName); - assertEquals(1, model1.getReactions().size()); + assertEquals(1, model1.getReactions().size()); - Reaction reaction = model1.getReactions().iterator().next(); + Reaction reaction = model1.getReactions().iterator().next(); - assertEquals(1, getWarnings().size()); - assertTrue(reaction instanceof UnknownPositiveInfluenceReaction); - assertFalse(reaction.isReversible()); + assertEquals(1, getWarnings().size()); + assertTrue(reaction instanceof UnknownPositiveInfluenceReaction); + assertFalse(reaction.isReversible()); - Model model2 = serializeModelOverCellDesignerParser(model1); + Model model2 = serializeModelOverCellDesignerParser(model1); - assertEquals(0, mc.compare(model1, model2)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } @Test public void StimulationInteractionDashedTest() throws Exception { - try { - String fileName = "testFiles/reactions/interaction_dashed_mim_stimulation.gpml"; + String fileName = "testFiles/reactions/interaction_dashed_mim_stimulation.gpml"; - Model model1 = new GPMLToModel().getModel(fileName); + Model model1 = new GPMLToModel().getModel(fileName); - assertEquals(1, model1.getReactions().size()); + assertEquals(1, model1.getReactions().size()); - Reaction reaction = model1.getReactions().iterator().next(); + Reaction reaction = model1.getReactions().iterator().next(); - assertEquals(1, getWarnings().size()); - assertTrue(reaction instanceof UnknownPositiveInfluenceReaction); - assertFalse(reaction.isReversible()); + assertEquals(1, getWarnings().size()); + assertTrue(reaction instanceof UnknownPositiveInfluenceReaction); + assertFalse(reaction.isReversible()); - Model model2 = serializeModelOverCellDesignerParser(model1); + Model model2 = serializeModelOverCellDesignerParser(model1); - assertEquals(0, mc.compare(model1, model2)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } @Test public void TranscriptionTranslationInteractionDashedTest() throws Exception { - try { - String fileName = "testFiles/reactions/interaction_dashed_mim_transcription_translation.gpml"; + String fileName = "testFiles/reactions/interaction_dashed_mim_transcription_translation.gpml"; - Model model1 = new GPMLToModel().getModel(fileName); + Model model1 = new GPMLToModel().getModel(fileName); - assertEquals(1, model1.getReactions().size()); + assertEquals(1, model1.getReactions().size()); - Reaction reaction = model1.getReactions().iterator().next(); + Reaction reaction = model1.getReactions().iterator().next(); - assertEquals(1, getWarnings().size()); - assertTrue(reaction instanceof PositiveInfluenceReaction); - assertFalse(reaction.isReversible()); + assertEquals(1, getWarnings().size()); + assertTrue(reaction instanceof PositiveInfluenceReaction); + assertFalse(reaction.isReversible()); - Model model2 = serializeModelOverCellDesignerParser(model1); + Model model2 = serializeModelOverCellDesignerParser(model1); - assertEquals(0, mc.compare(model1, model2)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } @Test public void TbarTranslationInteractionDashedTest() throws Exception { - try { - String fileName = "testFiles/reactions/interaction_dashed_tbar.gpml"; + String fileName = "testFiles/reactions/interaction_dashed_tbar.gpml"; - Model model1 = new GPMLToModel().getModel(fileName); + Model model1 = new GPMLToModel().getModel(fileName); - assertEquals(1, model1.getReactions().size()); + assertEquals(1, model1.getReactions().size()); - Reaction reaction = model1.getReactions().iterator().next(); + Reaction reaction = model1.getReactions().iterator().next(); - assertEquals(1, getWarnings().size()); - assertTrue(reaction instanceof UnknownNegativeInfluenceReaction); - assertFalse(reaction.isReversible()); + assertEquals(1, getWarnings().size()); + assertTrue(reaction instanceof UnknownNegativeInfluenceReaction); + assertFalse(reaction.isReversible()); - Model model2 = serializeModelOverCellDesignerParser(model1); + Model model2 = serializeModelOverCellDesignerParser(model1); - assertEquals(0, mc.compare(model1, model2)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } @Test public void lineLineCombinedReactionsTest() throws Exception { - try { - String fileName = "testFiles/reactions/line_line_combined_reaction.gpml"; + String fileName = "testFiles/reactions/line_line_combined_reaction.gpml"; - Model model1 = new GPMLToModel().getModel(fileName); + Model model1 = new GPMLToModel().getModel(fileName); - assertEquals(4, model1.getReactions().size()); + assertEquals(4, model1.getReactions().size()); - assertEquals(4, getWarnings().size()); + assertEquals(4, getWarnings().size()); - Model model2 = serializeModelOverCellDesignerParser(model1); + Model model2 = serializeModelOverCellDesignerParser(model1); - assertEquals(0, mc.compare(model1, model2)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(0, mc.compare(model1, model2)); } } diff --git a/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/WikipathwaysTestFunctions.java b/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/WikipathwaysTestFunctions.java index 895ef75883d6459d854edad111bf330c8df23340..fd2df0a77eed6cdca1eca0da03b7fcaf51d1b7b9 100644 --- a/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/WikipathwaysTestFunctions.java +++ b/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/WikipathwaysTestFunctions.java @@ -30,9 +30,7 @@ import javax.xml.transform.stream.StreamResult; import org.apache.logging.log4j.*; import org.apache.logging.log4j.core.LogEvent; - -import org.junit.After; -import org.junit.Before; +import org.junit.*; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; @@ -40,9 +38,7 @@ import org.w3c.dom.NodeList; import org.xml.sax.InputSource; import org.xml.sax.SAXException; -import lcsb.mapviewer.common.Configuration; - -import lcsb.mapviewer.common.MinervaLoggerAppender; +import lcsb.mapviewer.common.*; import lcsb.mapviewer.common.exception.InvalidXmlSchemaException; import lcsb.mapviewer.converter.ConverterParams; import lcsb.mapviewer.converter.InvalidInputDataExecption; @@ -55,6 +51,9 @@ import lcsb.mapviewer.model.map.model.Model; public abstract class WikipathwaysTestFunctions { private Logger logger = LogManager.getLogger(WikipathwaysTestFunctions.class); + @Rule + public UnitTestFailedWatcher unitTestFailedWatcher = new UnitTestFailedWatcher(); + protected static double EPSILON = Configuration.EPSILON; private DocumentBuilder db; diff --git a/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/XML/BiopaxParserTest.java b/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/XML/BiopaxParserTest.java index 401f90c6b3b6905e54b9e808567cf21cceee5fab..2b25b91443bca4bea099d22cffea6bcf7e81c6c5 100644 --- a/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/XML/BiopaxParserTest.java +++ b/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/XML/BiopaxParserTest.java @@ -1,12 +1,8 @@ package lcsb.mapviewer.wikipathway.XML; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.Assert.*; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.w3c.dom.Document; import lcsb.mapviewer.wikipathway.WikipathwaysTestFunctions; @@ -15,48 +11,38 @@ import lcsb.mapviewer.wikipathway.model.biopax.BiopaxPublication; public class BiopaxParserTest extends WikipathwaysTestFunctions { - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testParse() throws Exception { - try { - BiopaxParser parser = new BiopaxParser(); - Document document = getXmlDocumentFromFile("testFiles/biopax/small.xml"); - BiopaxData data = parser.parse(document.getFirstChild()); - assertNotNull(data); - assertEquals(2, data.getPublications().size()); - BiopaxPublication publication = data.getPublicationByReference("cf2"); - assertEquals("23456", publication.getId()); - assertEquals("PubMed", publication.getDb()); - assertEquals("[Radical resection of foci in tuberculosis of the shoulder joint].", publication.getTitle()); - assertEquals("Magy Traumatol Orthop Helyreallito Seb", publication.getSource()); - assertEquals("1977", publication.getYear()); - assertEquals("Udvarhelyi I", publication.getAuthors()); - assertEquals("cf2", publication.getReferenceId()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testIncorrectPumeds() throws Exception { - try { - BiopaxParser parser = new BiopaxParser(); - Document document = getXmlDocumentFromFile("testFiles/biopax/invalid_pubmed_reference.xml"); - BiopaxData data = parser.parse(document.getFirstChild()); - assertNotNull(data); - assertTrue(getWarnings().size() > 0); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testParse() throws Exception { + BiopaxParser parser = new BiopaxParser(); + Document document = getXmlDocumentFromFile("testFiles/biopax/small.xml"); + BiopaxData data = parser.parse(document.getFirstChild()); + assertNotNull(data); + assertEquals(2, data.getPublications().size()); + BiopaxPublication publication = data.getPublicationByReference("cf2"); + assertEquals("23456", publication.getId()); + assertEquals("PubMed", publication.getDb()); + assertEquals("[Radical resection of foci in tuberculosis of the shoulder joint].", publication.getTitle()); + assertEquals("Magy Traumatol Orthop Helyreallito Seb", publication.getSource()); + assertEquals("1977", publication.getYear()); + assertEquals("Udvarhelyi I", publication.getAuthors()); + assertEquals("cf2", publication.getReferenceId()); + } + + @Test + public void testIncorrectPumeds() throws Exception { + BiopaxParser parser = new BiopaxParser(); + Document document = getXmlDocumentFromFile("testFiles/biopax/invalid_pubmed_reference.xml"); + BiopaxData data = parser.parse(document.getFirstChild()); + assertNotNull(data); + assertTrue(getWarnings().size() > 0); + } } diff --git a/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/XML/BugTest.java b/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/XML/BugTest.java index 160443232a3e08103cc17c26ee547fa17935af96..f4036a7d224a90e555036e50959301e4758c1da8 100644 --- a/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/XML/BugTest.java +++ b/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/XML/BugTest.java @@ -1,10 +1,11 @@ package lcsb.mapviewer.wikipathway.XML; -import static org.junit.Assert.assertEquals; +import static org.junit.Assert.*; import java.io.FileInputStream; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.junit.Test; import lcsb.mapviewer.model.map.model.Model; @@ -18,43 +19,32 @@ public class BugTest extends WikipathwaysTestFunctions { @Test public void testBug319() throws Exception { - try { - String fileName = "testFiles/bugs/error_319.gpml"; - FileInputStream fis = new FileInputStream(fileName); - new GpmlParser().createGraph(fis); - assertEquals(1, getWarnings().size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String fileName = "testFiles/bugs/error_319.gpml"; + FileInputStream fis = new FileInputStream(fileName); + new GpmlParser().createGraph(fis); + assertEquals(1, getWarnings().size()); } private ModelComparator mc = new ModelComparator(1.0); @Test public void testBug328() throws Exception { - try { - String filename = "testFiles/bugs/error_328.gpml"; - Model model1 = new GPMLToModel().getModel(filename); + String filename = "testFiles/bugs/error_328.gpml"; + Model model1 = new GPMLToModel().getModel(filename); - assertEquals(7, getWarnings().size()); + assertEquals(7, getWarnings().size()); - int complexes = 0; - for (Element alias : model1.getElements()) { - if (alias instanceof Complex) { - complexes++; - } + int complexes = 0; + for (Element alias : model1.getElements()) { + if (alias instanceof Complex) { + complexes++; } - assertEquals("Invalid number of complexes", 1, complexes); - - Model model2 = serializeModelOverCellDesignerParser(model1); + } + assertEquals("Invalid number of complexes", 1, complexes); - assertEquals("File " + filename + " different after transformation", 0, mc.compare(model1, model2)); + Model model2 = serializeModelOverCellDesignerParser(model1); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals("File " + filename + " different after transformation", 0, mc.compare(model1, model2)); } } diff --git a/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/XML/DataNodeParserTest.java b/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/XML/DataNodeParserTest.java index b9090662b2a9e8875850317304a732b383885fd2..12e619ba5db29888c4e12671be3152c520e7d1e6 100644 --- a/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/XML/DataNodeParserTest.java +++ b/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/XML/DataNodeParserTest.java @@ -1,13 +1,10 @@ package lcsb.mapviewer.wikipathway.XML; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -import org.apache.logging.log4j.*; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import static org.junit.Assert.*; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.junit.*; import org.w3c.dom.Element; import lcsb.mapviewer.model.map.MiriamData; @@ -16,44 +13,38 @@ import lcsb.mapviewer.wikipathway.WikipathwaysTestFunctions; import lcsb.mapviewer.wikipathway.model.DataNode; public class DataNodeParserTest extends WikipathwaysTestFunctions { - Logger logger = LogManager.getLogger(DataNodeParserTest.class); - DataNodeParser parser = new DataNodeParser(); - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testParseGene() throws Exception { - try { - Element node = fileToNode("testFiles/elements/gene.xml"); - DataNode dataNode = parser.parse(node); - - assertNotNull(dataNode); - assertEquals("GeneProduct", dataNode.getTextLabel()); - assertEquals("ab30b", dataNode.getGraphId()); - assertEquals(1, dataNode.getBiopaxReference().size()); - assertEquals("aea", dataNode.getBiopaxReference().get(0)); - assertEquals(1, dataNode.getReferences().size()); - assertEquals(new MiriamData(MiriamType.HGNC_SYMBOL, "SNCA"), dataNode.getReferences().get(0)); - - assertEquals((Integer) 32768, dataNode.getzOrder()); - assertEquals((Double) 10.0, dataNode.getFontSize()); - assertEquals("Middle", dataNode.getvAlign()); - assertEquals("GeneProduct", dataNode.getType()); - assertTrue(dataNode.getComments().contains("comment 1")); - assertTrue(dataNode.getComments().contains("Type your comment here")); - - assertEquals(0, getWarnings().size()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } + Logger logger = LogManager.getLogger(DataNodeParserTest.class); + DataNodeParser parser = new DataNodeParser(); + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testParseGene() throws Exception { + Element node = fileToNode("testFiles/elements/gene.xml"); + DataNode dataNode = parser.parse(node); + + assertNotNull(dataNode); + assertEquals("GeneProduct", dataNode.getTextLabel()); + assertEquals("ab30b", dataNode.getGraphId()); + assertEquals(1, dataNode.getBiopaxReference().size()); + assertEquals("aea", dataNode.getBiopaxReference().get(0)); + assertEquals(1, dataNode.getReferences().size()); + assertEquals(new MiriamData(MiriamType.HGNC_SYMBOL, "SNCA"), dataNode.getReferences().get(0)); + + assertEquals((Integer) 32768, dataNode.getzOrder()); + assertEquals((Double) 10.0, dataNode.getFontSize()); + assertEquals("Middle", dataNode.getvAlign()); + assertEquals("GeneProduct", dataNode.getType()); + assertTrue(dataNode.getComments().contains("comment 1")); + assertTrue(dataNode.getComments().contains("Type your comment here")); + + assertEquals(0, getWarnings().size()); + } } diff --git a/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/XML/EdgeLineParserTest.java b/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/XML/EdgeLineParserTest.java index 51be34fbc8b34fd5a71ca4019e59fb6498bb98ee..3b51b1f8d9f875a581cbd9c5ede41c6708f7ddc7 100644 --- a/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/XML/EdgeLineParserTest.java +++ b/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/XML/EdgeLineParserTest.java @@ -1,14 +1,10 @@ package lcsb.mapviewer.wikipathway.XML; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.Assert.*; import java.awt.geom.Point2D; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.w3c.dom.Element; import lcsb.mapviewer.wikipathway.WikipathwaysTestFunctions; @@ -16,40 +12,34 @@ import lcsb.mapviewer.wikipathway.model.Edge; public class EdgeLineParserTest extends WikipathwaysTestFunctions { - EdgeLineParser parser = new EdgeLineParser(); + EdgeLineParser parser = new EdgeLineParser(); - @Before - public void setUp() throws Exception { - } + @Before + public void setUp() throws Exception { + } - @After - public void tearDown() throws Exception { - } + @After + public void tearDown() throws Exception { + } - @Test - public void testParseLine() throws Exception { - try { - Element node = fileToNode("testFiles/elements/line.xml"); - Edge edge = parser.parse(node); - assertNotNull(edge); + @Test + public void testParseLine() throws Exception { + Element node = fileToNode("testFiles/elements/line.xml"); + Edge edge = parser.parse(node); + assertNotNull(edge); - assertEquals(1, edge.getBiopaxReferences().size()); - assertEquals("c64", edge.getBiopaxReferences().get(0)); + assertEquals(1, edge.getBiopaxReferences().size()); + assertEquals("c64", edge.getBiopaxReferences().get(0)); - assertEquals((Integer) 12288, edge.getzOrder()); - assertEquals(1.0, edge.getLine().getWidth(), EPSILON); - assertTrue(edge.getComments().contains("line comment")); - assertTrue(edge.getComments().contains("Type your comment here")); + assertEquals((Integer) 12288, edge.getzOrder()); + assertEquals(1.0, edge.getLine().getWidth(), EPSILON); + assertTrue(edge.getComments().contains("line comment")); + assertTrue(edge.getComments().contains("Type your comment here")); - assertTrue(new Point2D.Double(730, 265).distance(edge.getLine().getBeginPoint()) < EPSILON); - assertTrue(new Point2D.Double(931.0, 442.0).distance(edge.getLine().getEndPoint()) < EPSILON); + assertTrue(new Point2D.Double(730, 265).distance(edge.getLine().getBeginPoint()) < EPSILON); + assertTrue(new Point2D.Double(931.0, 442.0).distance(edge.getLine().getEndPoint()) < EPSILON); - assertEquals(0, getWarnings().size()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } + assertEquals(0, getWarnings().size()); + } } diff --git a/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/XML/ElementGpmlParserTest.java b/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/XML/ElementGpmlParserTest.java index 8e084cf53e7919721ff45745b7b586563c0f73ab..42428c7f96e4df40d067aed9a752c81f5d2374b2 100644 --- a/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/XML/ElementGpmlParserTest.java +++ b/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/XML/ElementGpmlParserTest.java @@ -1,54 +1,48 @@ package lcsb.mapviewer.wikipathway.XML; -import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.*; import java.awt.Color; import java.util.Collection; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.w3c.dom.Element; import lcsb.mapviewer.common.exception.NotImplementedException; import lcsb.mapviewer.converter.ConverterException; - -public class ElementGpmlParserTest { - - ElementGpmlParser<Object> parser = new ElementGpmlParser<Object>() { - @Override - public String toXml(Collection<Object> list) throws ConverterException { - throw new NotImplementedException(); - } - - @Override - public String toXml(Object object) throws ConverterException { - throw new NotImplementedException(); - } - - @Override - public Object parse(Element node) throws ConverterException { - throw new NotImplementedException(); - } - }; - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testParseTransparentColor() { - try { - Color color = parser.hexStringToColor("Transparent"); - assertNotNull(color); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } +import lcsb.mapviewer.wikipathway.WikipathwaysTestFunctions; + +public class ElementGpmlParserTest extends WikipathwaysTestFunctions { + + ElementGpmlParser<Object> parser = new ElementGpmlParser<Object>() { + @Override + public String toXml(Collection<Object> list) throws ConverterException { + throw new NotImplementedException(); + } + + @Override + public String toXml(Object object) throws ConverterException { + throw new NotImplementedException(); + } + + @Override + public Object parse(Element node) throws ConverterException { + throw new NotImplementedException(); + } + }; + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testParseTransparentColor() { + Color color = parser.hexStringToColor("Transparent"); + assertNotNull(color); + } } diff --git a/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/XML/GpmlParserTest.java b/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/XML/GpmlParserTest.java index 0d3f6e03c54eb80b51140d7eb28149c89a627072..47cd2aaeec2ec2ad475f915046b580908a866784 100644 --- a/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/XML/GpmlParserTest.java +++ b/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/XML/GpmlParserTest.java @@ -1,15 +1,12 @@ package lcsb.mapviewer.wikipathway.XML; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.Assert.*; import java.io.FileInputStream; -import org.apache.logging.log4j.*; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.junit.*; import lcsb.mapviewer.model.graphics.PolylineData; import lcsb.mapviewer.wikipathway.WikipathwaysTestFunctions; @@ -17,134 +14,90 @@ import lcsb.mapviewer.wikipathway.model.Graph; import lcsb.mapviewer.wikipathway.model.Interaction; public class GpmlParserTest extends WikipathwaysTestFunctions { - Logger logger = LogManager.getLogger(GpmlParserTest.class); - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testEdgeAttributes() throws Exception { - try { - - String fileName = "testFiles/small/missing_aliases_in_compartment.gpml"; - FileInputStream fis = new FileInputStream(fileName); - Graph graph = new GpmlParser().createGraph(fis); - assertNotNull(graph); - assertEquals(3, getWarnings().size()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testCycliReactions() throws Exception { - try { - - String fileName = "testFiles/small/cyclic_reactions.gpml"; - FileInputStream fis = new FileInputStream(fileName); - Graph graph = new GpmlParser().createGraph(fis); - assertNotNull(graph); - assertEquals(3, getWarnings().size()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testBiopaxVocabulary() throws Exception { - try { - - String fileName = "testFiles/small/opencontrolledvocabulary.gpml"; - FileInputStream fis = new FileInputStream(fileName); - Graph graph = new GpmlParser().createGraph(fis); - - assertEquals(1, graph.getBiopaxData().getOpenControlledVocabularies().size()); - assertEquals(0, getWarnings().size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testModelAttribute() throws Exception { - try { - - String fileName = "testFiles/small/model_attribute.gpml"; - FileInputStream fis = new FileInputStream(fileName); - Graph graph = new GpmlParser().createGraph(fis); - - assertEquals("428359", graph.getAttributes().get("reactome_id")); - assertEquals(0, getWarnings().size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testModelAnnotations() throws Exception { - try { - - String fileName = "testFiles/small/model_annotations.gpml"; - FileInputStream fis = new FileInputStream(fileName); - Graph graph = new GpmlParser().createGraph(fis); - - assertEquals(6, graph.getBiopaxReferences().size()); - assertEquals(0, getWarnings().size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testModelLines() throws Exception { - try { - - String fileName = "testFiles/small/model_with_line.gpml"; - FileInputStream fis = new FileInputStream(fileName); - Graph graph = new GpmlParser().createGraph(fis); - - assertEquals(1, graph.getLines().size()); - PolylineData pd = graph.getLines().get(0); - assertEquals(3, pd.getPoints().size()); - assertEquals(0, getWarnings().size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testSimpleReaction() throws Exception { - try { - - String fileName = "testFiles/small/simple_reaction.gpml"; - FileInputStream fis = new FileInputStream(fileName); - Graph graph = new GpmlParser().createGraph(fis); - - Interaction interaction = graph.getInteractions().iterator().next(); - PolylineData pd = interaction.getLine(); - assertTrue(pd.getPoints().get(0).distance(476.0, 351.0) < EPSILON); - assertTrue(pd.getPoints().get(1).distance(476.0, 286.0) < EPSILON); - assertTrue(pd.getPoints().get(2).distance(846.0, 287.0) < EPSILON); - assertTrue(pd.getPoints().get(3).distance(846.0, 354.0) < EPSILON); - - assertEquals(0, getWarnings().size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } + Logger logger = LogManager.getLogger(GpmlParserTest.class); + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testEdgeAttributes() throws Exception { + String fileName = "testFiles/small/missing_aliases_in_compartment.gpml"; + FileInputStream fis = new FileInputStream(fileName); + Graph graph = new GpmlParser().createGraph(fis); + assertNotNull(graph); + assertEquals(3, getWarnings().size()); + } + + @Test + public void testCycliReactions() throws Exception { + String fileName = "testFiles/small/cyclic_reactions.gpml"; + FileInputStream fis = new FileInputStream(fileName); + Graph graph = new GpmlParser().createGraph(fis); + assertNotNull(graph); + assertEquals(3, getWarnings().size()); + } + + @Test + public void testBiopaxVocabulary() throws Exception { + String fileName = "testFiles/small/opencontrolledvocabulary.gpml"; + FileInputStream fis = new FileInputStream(fileName); + Graph graph = new GpmlParser().createGraph(fis); + + assertEquals(1, graph.getBiopaxData().getOpenControlledVocabularies().size()); + assertEquals(0, getWarnings().size()); + } + + @Test + public void testModelAttribute() throws Exception { + String fileName = "testFiles/small/model_attribute.gpml"; + FileInputStream fis = new FileInputStream(fileName); + Graph graph = new GpmlParser().createGraph(fis); + + assertEquals("428359", graph.getAttributes().get("reactome_id")); + assertEquals(0, getWarnings().size()); + } + + @Test + public void testModelAnnotations() throws Exception { + String fileName = "testFiles/small/model_annotations.gpml"; + FileInputStream fis = new FileInputStream(fileName); + Graph graph = new GpmlParser().createGraph(fis); + + assertEquals(6, graph.getBiopaxReferences().size()); + assertEquals(0, getWarnings().size()); + } + + @Test + public void testModelLines() throws Exception { + String fileName = "testFiles/small/model_with_line.gpml"; + FileInputStream fis = new FileInputStream(fileName); + Graph graph = new GpmlParser().createGraph(fis); + + assertEquals(1, graph.getLines().size()); + PolylineData pd = graph.getLines().get(0); + assertEquals(3, pd.getPoints().size()); + assertEquals(0, getWarnings().size()); + } + + @Test + public void testSimpleReaction() throws Exception { + String fileName = "testFiles/small/simple_reaction.gpml"; + FileInputStream fis = new FileInputStream(fileName); + Graph graph = new GpmlParser().createGraph(fis); + + Interaction interaction = graph.getInteractions().iterator().next(); + PolylineData pd = interaction.getLine(); + assertTrue(pd.getPoints().get(0).distance(476.0, 351.0) < EPSILON); + assertTrue(pd.getPoints().get(1).distance(476.0, 286.0) < EPSILON); + assertTrue(pd.getPoints().get(2).distance(846.0, 287.0) < EPSILON); + assertTrue(pd.getPoints().get(3).distance(846.0, 354.0) < EPSILON); + + assertEquals(0, getWarnings().size()); + } } diff --git a/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/XML/LabelParserTest.java b/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/XML/LabelParserTest.java index 711fa381ff49587839b8dc25c4745ca1130f6827..2cd7b571ad8226c8ef67a59a18d7044c1004a609 100644 --- a/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/XML/LabelParserTest.java +++ b/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/XML/LabelParserTest.java @@ -1,72 +1,56 @@ package lcsb.mapviewer.wikipathway.XML; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.Assert.*; import java.awt.Color; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.w3c.dom.Element; import lcsb.mapviewer.wikipathway.WikipathwaysTestFunctions; import lcsb.mapviewer.wikipathway.model.Label; public class LabelParserTest extends WikipathwaysTestFunctions { - LabelParser parser = new LabelParser(); - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testParseLabel() throws Exception { - try { - Element node = fileToNode("testFiles/elements/label.xml"); - Label label = parser.parse(node); - assertNotNull(label); - - assertEquals("Label 2", label.getTextLabel()); - assertEquals("edf06", label.getGraphId()); - assertEquals(2, label.getBiopaxReference().size()); - assertEquals("b38", label.getBiopaxReference().get(1)); - - assertEquals((Integer) 28672, label.getzOrder()); - assertEquals((Double) 10.0, label.getFontSize()); - assertEquals("Middle", label.getvAlign()); - assertTrue(label.getComments().contains("comment 2")); - assertEquals(Color.WHITE, label.getFillColor()); - assertEquals(Color.BLACK, label.getColor()); - - assertEquals(0, getWarnings().size()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testParseGraphics() throws Exception { - try { - Element node = fileToNode("testFiles/elements/label_graphics.xml"); - - Label label = new Label("test"); - parser.parseGraphics(node, label); - assertNotNull(label); - - assertEquals(0, getWarnings().size()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } + LabelParser parser = new LabelParser(); + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testParseLabel() throws Exception { + Element node = fileToNode("testFiles/elements/label.xml"); + Label label = parser.parse(node); + assertNotNull(label); + + assertEquals("Label 2", label.getTextLabel()); + assertEquals("edf06", label.getGraphId()); + assertEquals(2, label.getBiopaxReference().size()); + assertEquals("b38", label.getBiopaxReference().get(1)); + + assertEquals((Integer) 28672, label.getzOrder()); + assertEquals((Double) 10.0, label.getFontSize()); + assertEquals("Middle", label.getvAlign()); + assertTrue(label.getComments().contains("comment 2")); + assertEquals(Color.WHITE, label.getFillColor()); + assertEquals(Color.BLACK, label.getColor()); + + assertEquals(0, getWarnings().size()); + } + + @Test + public void testParseGraphics() throws Exception { + Element node = fileToNode("testFiles/elements/label_graphics.xml"); + + Label label = new Label("test"); + parser.parseGraphics(node, label); + assertNotNull(label); + + assertEquals(0, getWarnings().size()); + } } diff --git a/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/XML/ModelContructorTest.java b/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/XML/ModelContructorTest.java index 3306700b7692107abf460099422a3092f2a64a0f..ea147500f961c996cf0d8767e450617520afb333 100644 --- a/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/XML/ModelContructorTest.java +++ b/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/XML/ModelContructorTest.java @@ -1,25 +1,22 @@ package lcsb.mapviewer.wikipathway.XML; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.*; import java.awt.geom.Point2D; import java.io.ByteArrayInputStream; import java.nio.charset.StandardCharsets; -import org.apache.logging.log4j.*; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.junit.*; import lcsb.mapviewer.common.Pair; import lcsb.mapviewer.model.graphics.PolylineData; -import lcsb.mapviewer.model.map.model.Model; -import lcsb.mapviewer.model.map.model.ModelComparator; -import lcsb.mapviewer.model.map.model.ModelFullIndexed; +import lcsb.mapviewer.model.map.model.*; import lcsb.mapviewer.model.map.species.GenericProtein; +import lcsb.mapviewer.wikipathway.WikipathwaysTestFunctions; -public class ModelContructorTest { +public class ModelContructorTest extends WikipathwaysTestFunctions { Logger logger = LogManager.getLogger(ModelContructorTest.class); ModelComparator comparator = new ModelComparator(); @@ -36,39 +33,29 @@ public class ModelContructorTest { @Test public void testSplitPolyline() { - try { - Point2D p1 = new Point2D.Double(1455.5988605049254, 562.0578193221613); - Point2D p2 = new Point2D.Double(1455.5988605049254, 562.0578193221613); - PolylineData pd = new PolylineData(p1, p2); - - ModelContructor mc = new ModelContructor(); - Pair<PolylineData, PolylineData> result = mc.splitPolyline(pd); - assertNotNull(result); - assertNotNull(result.getLeft()); - assertNotNull(result.getRight()); - assertEquals(2, result.getLeft().getPoints().size()); - assertEquals(2, result.getRight().getPoints().size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Point2D p1 = new Point2D.Double(1455.5988605049254, 562.0578193221613); + Point2D p2 = new Point2D.Double(1455.5988605049254, 562.0578193221613); + PolylineData pd = new PolylineData(p1, p2); + + ModelContructor mc = new ModelContructor(); + Pair<PolylineData, PolylineData> result = mc.splitPolyline(pd); + assertNotNull(result); + assertNotNull(result.getLeft()); + assertNotNull(result.getRight()); + assertEquals(2, result.getLeft().getPoints().size()); + assertEquals(2, result.getRight().getPoints().size()); } @Test public void testZIndexForElement() throws Exception { - try { - ModelToGPML parser = new ModelToGPML(); - Model model = createEmptyModel(); - model.addElement(createProtein()); - String xml = parser.getGPML(model); - assertNotNull(xml); - - Model model2 = new GPMLToModel().getModel(new ByteArrayInputStream(xml.getBytes(StandardCharsets.UTF_8))); - assertEquals(0, comparator.compare(model2, model)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + ModelToGPML parser = new ModelToGPML(); + Model model = createEmptyModel(); + model.addElement(createProtein()); + String xml = parser.getGPML(model); + assertNotNull(xml); + + Model model2 = new GPMLToModel().getModel(new ByteArrayInputStream(xml.getBytes(StandardCharsets.UTF_8))); + assertEquals(0, comparator.compare(model2, model)); } private Model createEmptyModel() { diff --git a/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/XML/ModelToGPMLTest.java b/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/XML/ModelToGPMLTest.java index 638d3086200d255c1ead660e0dc26521f2dd5a76..be945f0b5b4667a1cae0de5d5bbb3a79f213df03 100644 --- a/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/XML/ModelToGPMLTest.java +++ b/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/XML/ModelToGPMLTest.java @@ -1,16 +1,13 @@ package lcsb.mapviewer.wikipathway.XML; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.Assert.*; import java.io.ByteArrayInputStream; import java.nio.charset.StandardCharsets; -import org.apache.logging.log4j.*; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.junit.*; import lcsb.mapviewer.converter.ConverterParams; import lcsb.mapviewer.converter.model.celldesigner.CellDesignerXmlParser; @@ -23,69 +20,58 @@ import lcsb.mapviewer.model.map.species.GenericProtein; import lcsb.mapviewer.wikipathway.WikipathwaysTestFunctions; public class ModelToGPMLTest extends WikipathwaysTestFunctions { - Logger logger = LogManager.getLogger(ModelToGPMLTest.class); - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void test() throws Exception { - try { - ModelToGPML parser = new ModelToGPML(); - CellDesignerXmlParser cellDesignerXmlParser = new CellDesignerXmlParser(); - Model model = cellDesignerXmlParser.createModel(new ConverterParams().filename("testFiles/other_full/GSTP1 subnetwork_220214.xml")); - String xml = parser.getGPML(model); - assertNotNull(xml); - assertEquals(10, getWarnings().size()); - - Model model2 = new GPMLToModel().getModel(new ByteArrayInputStream(xml.getBytes(StandardCharsets.UTF_8))); - assertNotNull(model2); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testAnnotations() throws Exception { - try { - ModelToGPML parser = new ModelToGPML(); - - Model model = new ModelFullIndexed(null); - model.setWidth(1000); - model.setHeight(1000); - - GenericProtein alias = createProtein(); - alias.addMiriamData(new MiriamData(MiriamType.HGNC_SYMBOL, "SNCA")); - alias.addMiriamData(new MiriamData(MiriamType.PUBMED, "123")); - alias.addMiriamData(new MiriamData(MiriamType.PUBMED, "1234")); - - model.addElement(alias); - - String xml = parser.getGPML(model); - assertNotNull(xml); - assertEquals(0, getWarnings().size()); - - Model model2 = new GPMLToModel().getModel(new ByteArrayInputStream(xml.getBytes(StandardCharsets.UTF_8))); - - Element p = model2.getElementByElementId("sa"); - - assertEquals(alias.getMiriamData().size(), p.getMiriamData().size()); - for (MiriamData md : p.getMiriamData()) { - assertTrue(alias.getMiriamData().contains(md)); - } - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } + Logger logger = LogManager.getLogger(ModelToGPMLTest.class); + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void test() throws Exception { + ModelToGPML parser = new ModelToGPML(); + CellDesignerXmlParser cellDesignerXmlParser = new CellDesignerXmlParser(); + Model model = cellDesignerXmlParser + .createModel(new ConverterParams().filename("testFiles/other_full/GSTP1 subnetwork_220214.xml")); + String xml = parser.getGPML(model); + assertNotNull(xml); + assertEquals(10, getWarnings().size()); + + Model model2 = new GPMLToModel().getModel(new ByteArrayInputStream(xml.getBytes(StandardCharsets.UTF_8))); + assertNotNull(model2); + } + + @Test + public void testAnnotations() throws Exception { + ModelToGPML parser = new ModelToGPML(); + + Model model = new ModelFullIndexed(null); + model.setWidth(1000); + model.setHeight(1000); + + GenericProtein alias = createProtein(); + alias.addMiriamData(new MiriamData(MiriamType.HGNC_SYMBOL, "SNCA")); + alias.addMiriamData(new MiriamData(MiriamType.PUBMED, "123")); + alias.addMiriamData(new MiriamData(MiriamType.PUBMED, "1234")); + + model.addElement(alias); + + String xml = parser.getGPML(model); + assertNotNull(xml); + assertEquals(0, getWarnings().size()); + + Model model2 = new GPMLToModel().getModel(new ByteArrayInputStream(xml.getBytes(StandardCharsets.UTF_8))); + + Element p = model2.getElementByElementId("sa"); + + assertEquals(alias.getMiriamData().size(), p.getMiriamData().size()); + for (MiriamData md : p.getMiriamData()) { + assertTrue(alias.getMiriamData().contains(md)); + } + } private GenericProtein createProtein() { GenericProtein alias = new GenericProtein("sa"); diff --git a/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/XML/ReferenceParserTest.java b/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/XML/ReferenceParserTest.java index 28ccf7a4454c86d5fa354550d7a7573069e6a02d..0f351c613de0b49fc5a2f2611df9a5ff7f234955 100644 --- a/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/XML/ReferenceParserTest.java +++ b/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/XML/ReferenceParserTest.java @@ -1,12 +1,10 @@ package lcsb.mapviewer.wikipathway.XML; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.*; -import org.apache.logging.log4j.*; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.junit.*; import org.w3c.dom.Element; import org.w3c.dom.Node; @@ -15,144 +13,114 @@ import lcsb.mapviewer.model.map.MiriamType; import lcsb.mapviewer.wikipathway.WikipathwaysTestFunctions; public class ReferenceParserTest extends WikipathwaysTestFunctions { - Logger logger = LogManager.getLogger(ReferenceParserTest.class); - - ReferenceParser mc = new ReferenceParser(); - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testCreateHmdbMiriam() { - MiriamData md = mc.createMiriamData("HMDB03791", "HMDB"); - assertNotNull(md); - } - - @Test - public void testCreateWormBaseMiriam() { - MiriamData md = mc.createMiriamData("WormBase", "WormBase"); - assertNotNull(md); - } - - @Test - public void testSgdMiriam() { - MiriamData md = mc.createMiriamData("S000028457", "SGD"); - assertNotNull(md); - } - - @Test - public void testWikidataMiriam() { - MiriamData md = mc.createMiriamData("Q15623825", "Wikidata"); - assertNotNull(md); - } - - @Test - public void testCreateEnsemblPlantMiriam() { - MiriamData md = mc.createMiriamData("AT3G18550", "Ensembl Plants"); - assertNotNull(md); - } - - @Test - public void testCreateCasMiriam() { - MiriamData md = mc.createMiriamData("657-24-9", "CAS"); - assertNotNull(md); - } - - @Test - public void testCreateGenBankMiriam() { - MiriamData md = mc.createMiriamData("123", "GenBank"); - assertNotNull(md); - } - - @Test - public void testCreatePubchemMiriam() { - MiriamData md = mc.createMiriamData("39484", "pubchem.compound"); - assertNotNull(md); - } - - @Test - public void testCreateWikipediaMiriam() { - MiriamData md = mc.createMiriamData("Reactive_oxygen_species", "Wikipedia"); - assertNotNull(md); - } - - @Test - public void testCreateKeggOrthologyMiriam() throws Exception { - try { - MiriamData md = mc.createMiriamData("K00114", "Kegg ortholog"); - assertNotNull(md); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testChemSpiderMiriam() throws Exception { - try { - MiriamData md = mc.createMiriamData("110354", "Chemspider"); - assertNotNull(md); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testPfamMiriam() throws Exception { - try { - MiriamData md = mc.createMiriamData("PF00071", "Pfam"); - assertNotNull(md); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testMiRBaseMiriam() throws Exception { - try { - MiriamData md = mc.createMiriamData("MI0000750", "miRBase"); - assertNotNull(md); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testParse() throws Exception { - try { - Node node = super.getXmlDocumentFromFile("testFiles/elements/xref.xml"); - MiriamData md = mc.parse((Element) node.getFirstChild()); - assertNotNull(md); - assertEquals(md, new MiriamData(MiriamType.HGNC_SYMBOL, "SNCA")); - assertEquals(0, getWarnings().size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testToXml() throws Exception { - try { - MiriamData md = new MiriamData(MiriamType.CHEBI, "CHEBI:123"); - String xml = mc.toXml(md); - - Node node = super.getNodeFromXmlString(xml); - MiriamData md2 = mc.parse((Element) node); - assertNotNull(md); - assertEquals(md, md2); - assertEquals(0, getWarnings().size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } + Logger logger = LogManager.getLogger(ReferenceParserTest.class); + + ReferenceParser mc = new ReferenceParser(); + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testCreateHmdbMiriam() { + MiriamData md = mc.createMiriamData("HMDB03791", "HMDB"); + assertNotNull(md); + } + + @Test + public void testCreateWormBaseMiriam() { + MiriamData md = mc.createMiriamData("WormBase", "WormBase"); + assertNotNull(md); + } + + @Test + public void testSgdMiriam() { + MiriamData md = mc.createMiriamData("S000028457", "SGD"); + assertNotNull(md); + } + + @Test + public void testWikidataMiriam() { + MiriamData md = mc.createMiriamData("Q15623825", "Wikidata"); + assertNotNull(md); + } + + @Test + public void testCreateEnsemblPlantMiriam() { + MiriamData md = mc.createMiriamData("AT3G18550", "Ensembl Plants"); + assertNotNull(md); + } + + @Test + public void testCreateCasMiriam() { + MiriamData md = mc.createMiriamData("657-24-9", "CAS"); + assertNotNull(md); + } + + @Test + public void testCreateGenBankMiriam() { + MiriamData md = mc.createMiriamData("123", "GenBank"); + assertNotNull(md); + } + + @Test + public void testCreatePubchemMiriam() { + MiriamData md = mc.createMiriamData("39484", "pubchem.compound"); + assertNotNull(md); + } + + @Test + public void testCreateWikipediaMiriam() { + MiriamData md = mc.createMiriamData("Reactive_oxygen_species", "Wikipedia"); + assertNotNull(md); + } + + @Test + public void testCreateKeggOrthologyMiriam() throws Exception { + MiriamData md = mc.createMiriamData("K00114", "Kegg ortholog"); + assertNotNull(md); + } + + @Test + public void testChemSpiderMiriam() throws Exception { + MiriamData md = mc.createMiriamData("110354", "Chemspider"); + assertNotNull(md); + } + + @Test + public void testPfamMiriam() throws Exception { + MiriamData md = mc.createMiriamData("PF00071", "Pfam"); + assertNotNull(md); + } + + @Test + public void testMiRBaseMiriam() throws Exception { + MiriamData md = mc.createMiriamData("MI0000750", "miRBase"); + assertNotNull(md); + } + + @Test + public void testParse() throws Exception { + Node node = super.getXmlDocumentFromFile("testFiles/elements/xref.xml"); + MiriamData md = mc.parse((Element) node.getFirstChild()); + assertNotNull(md); + assertEquals(md, new MiriamData(MiriamType.HGNC_SYMBOL, "SNCA")); + assertEquals(0, getWarnings().size()); + } + + @Test + public void testToXml() throws Exception { + MiriamData md = new MiriamData(MiriamType.CHEBI, "CHEBI:123"); + String xml = mc.toXml(md); + + Node node = super.getNodeFromXmlString(xml); + MiriamData md2 = mc.parse((Element) node); + assertNotNull(md); + assertEquals(md, md2); + assertEquals(0, getWarnings().size()); + } } diff --git a/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/XML/ShapeParserTest.java b/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/XML/ShapeParserTest.java index 20b89ad10a29642bae2986a20667e7461c3f1cb9..85605eee818a09265741f7dbf13982b32d9b6ddf 100644 --- a/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/XML/ShapeParserTest.java +++ b/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/XML/ShapeParserTest.java @@ -1,8 +1,6 @@ package lcsb.mapviewer.wikipathway.XML; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.Assert.*; import java.awt.Color; @@ -16,200 +14,140 @@ import lcsb.mapviewer.wikipathway.WikipathwaysTestFunctions; import lcsb.mapviewer.wikipathway.model.Shape; public class ShapeParserTest extends WikipathwaysTestFunctions { - ShapeParser parser = new ShapeParser(); - - @After - public void tearDown() throws Exception { - } - - @Test - public void testParseArc() throws Exception { - try { - Element node = fileToNode("testFiles/elements/arc.xml"); - Shape shape = parser.parse(node); - assertNotNull(shape); - - assertEquals("arc l", shape.getTextLabel()); - assertEquals("d3af4", shape.getGraphId()); - assertEquals((Integer) 16384, shape.getzOrder()); - assertEquals((Double) 10.0, shape.getFontSize()); - assertEquals("Middle", shape.getvAlign()); - assertEquals("Arc", shape.getShape()); - assertEquals((Double) 0.0, shape.getRotation()); - assertTrue(shape.getComments().contains("arc c")); - assertTrue(shape.getComments().contains("Type your comment here")); - - assertEquals(0, getWarnings().size()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testParseBrace() throws Exception { - try { - Element node = fileToNode("testFiles/elements/brace.xml"); - Shape shape = parser.parse(node); - assertNotNull(shape); - - assertEquals("dfdfs fds ", shape.getTextLabel()); - assertEquals("eb55e", shape.getGraphId()); - assertEquals(1, shape.getBiopaxReference().size()); - assertEquals("d04", shape.getBiopaxReference().get(0)); - - assertEquals((Integer) 16384, shape.getzOrder()); - assertEquals((Double) 10.0, shape.getFontSize()); - assertEquals("Middle", shape.getvAlign()); - assertEquals("Brace", shape.getShape()); - assertEquals((Double) 0.44830711094422787, shape.getRotation(), Configuration.EPSILON); - assertTrue(shape.getComments().contains("1")); - assertTrue(shape.getComments().contains("Type your comment here")); - - assertEquals(0, getWarnings().size()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testParseCompartment() throws Exception { - try { - Element node = fileToNode("testFiles/elements/compartment.xml"); - Shape shape = parser.parse(node); - assertNotNull(shape); - - assertEquals("compartment title", shape.getTextLabel()); - assertEquals("c5869", shape.getGraphId()); - assertEquals(1, shape.getBiopaxReference().size()); - assertEquals("b80", shape.getBiopaxReference().get(0)); - - assertEquals((Integer) 16384, shape.getzOrder()); - assertEquals((Double) 10.0, shape.getFontSize()); - assertEquals((Double) 3.0, shape.getLineThickness()); - assertEquals(LineType.DOUBLE, shape.getLineType()); - assertEquals("Middle", shape.getvAlign()); - assertEquals("RoundedRectangle", shape.getShape()); - assertEquals((Double) 0.0, shape.getRotation(), Configuration.EPSILON); - assertTrue(shape.getComments().contains("compartment comment here")); - assertTrue(shape.getComments().contains("Type your comment here")); - assertTrue(shape.isCompartment()); - assertEquals(Color.LIGHT_GRAY, shape.getColor()); - - assertEquals(0, getWarnings().size()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testParseDegraded() throws Exception { - try { - Element node = fileToNode("testFiles/elements/degraded.xml"); - Shape shape = parser.parse(node); - assertNotNull(shape); - - assertEquals(0, getWarnings().size()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testParseHex() throws Exception { - try { - Element node = fileToNode("testFiles/elements/hex.xml"); - Shape shape = parser.parse(node); - assertNotNull(shape); - - assertEquals(0, getWarnings().size()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testParseOval() throws Exception { - try { - Element node = fileToNode("testFiles/elements/oval.xml"); - Shape shape = parser.parse(node); - assertNotNull(shape); - - assertEquals(0, getWarnings().size()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testParsePent() throws Exception { - try { - Element node = fileToNode("testFiles/elements/pent.xml"); - Shape shape = parser.parse(node); - assertNotNull(shape); - - assertEquals(0, getWarnings().size()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testParseRect() throws Exception { - try { - Element node = fileToNode("testFiles/elements/rect.xml"); - Shape shape = parser.parse(node); - assertNotNull(shape); - - assertEquals(0, getWarnings().size()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testParseRoundedREct() throws Exception { - try { - Element node = fileToNode("testFiles/elements/rounded_rect.xml"); - Shape shape = parser.parse(node); - assertNotNull(shape); - - assertEquals(0, getWarnings().size()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testParseTriangle() throws Exception { - try { - Element node = fileToNode("testFiles/elements/triangle.xml"); - Shape shape = parser.parse(node); - assertNotNull(shape); - - assertEquals(0, getWarnings().size()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } + ShapeParser parser = new ShapeParser(); + + @After + public void tearDown() throws Exception { + } + + @Test + public void testParseArc() throws Exception { + Element node = fileToNode("testFiles/elements/arc.xml"); + Shape shape = parser.parse(node); + assertNotNull(shape); + + assertEquals("arc l", shape.getTextLabel()); + assertEquals("d3af4", shape.getGraphId()); + assertEquals((Integer) 16384, shape.getzOrder()); + assertEquals((Double) 10.0, shape.getFontSize()); + assertEquals("Middle", shape.getvAlign()); + assertEquals("Arc", shape.getShape()); + assertEquals((Double) 0.0, shape.getRotation()); + assertTrue(shape.getComments().contains("arc c")); + assertTrue(shape.getComments().contains("Type your comment here")); + + assertEquals(0, getWarnings().size()); + } + + @Test + public void testParseBrace() throws Exception { + Element node = fileToNode("testFiles/elements/brace.xml"); + Shape shape = parser.parse(node); + assertNotNull(shape); + + assertEquals("dfdfs fds ", shape.getTextLabel()); + assertEquals("eb55e", shape.getGraphId()); + assertEquals(1, shape.getBiopaxReference().size()); + assertEquals("d04", shape.getBiopaxReference().get(0)); + + assertEquals((Integer) 16384, shape.getzOrder()); + assertEquals((Double) 10.0, shape.getFontSize()); + assertEquals("Middle", shape.getvAlign()); + assertEquals("Brace", shape.getShape()); + assertEquals((Double) 0.44830711094422787, shape.getRotation(), Configuration.EPSILON); + assertTrue(shape.getComments().contains("1")); + assertTrue(shape.getComments().contains("Type your comment here")); + + assertEquals(0, getWarnings().size()); + } + + @Test + public void testParseCompartment() throws Exception { + Element node = fileToNode("testFiles/elements/compartment.xml"); + Shape shape = parser.parse(node); + assertNotNull(shape); + + assertEquals("compartment title", shape.getTextLabel()); + assertEquals("c5869", shape.getGraphId()); + assertEquals(1, shape.getBiopaxReference().size()); + assertEquals("b80", shape.getBiopaxReference().get(0)); + + assertEquals((Integer) 16384, shape.getzOrder()); + assertEquals((Double) 10.0, shape.getFontSize()); + assertEquals((Double) 3.0, shape.getLineThickness()); + assertEquals(LineType.DOUBLE, shape.getLineType()); + assertEquals("Middle", shape.getvAlign()); + assertEquals("RoundedRectangle", shape.getShape()); + assertEquals((Double) 0.0, shape.getRotation(), Configuration.EPSILON); + assertTrue(shape.getComments().contains("compartment comment here")); + assertTrue(shape.getComments().contains("Type your comment here")); + assertTrue(shape.isCompartment()); + assertEquals(Color.LIGHT_GRAY, shape.getColor()); + + assertEquals(0, getWarnings().size()); + } + + @Test + public void testParseDegraded() throws Exception { + Element node = fileToNode("testFiles/elements/degraded.xml"); + Shape shape = parser.parse(node); + assertNotNull(shape); + + assertEquals(0, getWarnings().size()); + } + + @Test + public void testParseHex() throws Exception { + Element node = fileToNode("testFiles/elements/hex.xml"); + Shape shape = parser.parse(node); + assertNotNull(shape); + + assertEquals(0, getWarnings().size()); + } + + @Test + public void testParseOval() throws Exception { + Element node = fileToNode("testFiles/elements/oval.xml"); + Shape shape = parser.parse(node); + assertNotNull(shape); + + assertEquals(0, getWarnings().size()); + } + + @Test + public void testParsePent() throws Exception { + Element node = fileToNode("testFiles/elements/pent.xml"); + Shape shape = parser.parse(node); + assertNotNull(shape); + + assertEquals(0, getWarnings().size()); + } + + @Test + public void testParseRect() throws Exception { + Element node = fileToNode("testFiles/elements/rect.xml"); + Shape shape = parser.parse(node); + assertNotNull(shape); + + assertEquals(0, getWarnings().size()); + } + + @Test + public void testParseRoundedREct() throws Exception { + Element node = fileToNode("testFiles/elements/rounded_rect.xml"); + Shape shape = parser.parse(node); + assertNotNull(shape); + + assertEquals(0, getWarnings().size()); + } + + @Test + public void testParseTriangle() throws Exception { + Element node = fileToNode("testFiles/elements/triangle.xml"); + Shape shape = parser.parse(node); + assertNotNull(shape); + + assertEquals(0, getWarnings().size()); + } } diff --git a/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/XML/StateParserTest.java b/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/XML/StateParserTest.java index 7c85b7c6467743ca3e3b3d01e34da5151ad62e20..1446fc6e257b20bb39d47548609e2800f4da38a7 100644 --- a/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/XML/StateParserTest.java +++ b/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/XML/StateParserTest.java @@ -1,7 +1,6 @@ package lcsb.mapviewer.wikipathway.XML; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.*; import org.junit.After; import org.junit.Test; @@ -13,32 +12,26 @@ import lcsb.mapviewer.wikipathway.WikipathwaysTestFunctions; import lcsb.mapviewer.wikipathway.model.State; public class StateParserTest extends WikipathwaysTestFunctions { - StateParser parser = new StateParser(); - - @After - public void tearDown() throws Exception { - } - - @Test - public void testParseState() throws Exception { - try { - Element node = fileToNode("testFiles/elements/state.xml"); - State state = parser.parse(node); - assertNotNull(state); - - assertEquals(ModificationState.PHOSPHORYLATED, state.getType()); - assertEquals("e7637", state.getGraphId()); - assertEquals(1.0, state.getRelX(), Configuration.EPSILON); - assertEquals(-0.9978969505783312, state.getRelY(), Configuration.EPSILON); - assertEquals(15.0, state.getWidth(), Configuration.EPSILON); - assertEquals(15.0, state.getHeight(), Configuration.EPSILON); - assertEquals("Oval", state.getShape()); - assertEquals(0, getWarnings().size()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } + StateParser parser = new StateParser(); + + @After + public void tearDown() throws Exception { + } + + @Test + public void testParseState() throws Exception { + Element node = fileToNode("testFiles/elements/state.xml"); + State state = parser.parse(node); + assertNotNull(state); + + assertEquals(ModificationState.PHOSPHORYLATED, state.getType()); + assertEquals("e7637", state.getGraphId()); + assertEquals(1.0, state.getRelX(), Configuration.EPSILON); + assertEquals(-0.9978969505783312, state.getRelY(), Configuration.EPSILON); + assertEquals(15.0, state.getWidth(), Configuration.EPSILON); + assertEquals(15.0, state.getHeight(), Configuration.EPSILON); + assertEquals("Oval", state.getShape()); + assertEquals(0, getWarnings().size()); + } } diff --git a/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/model/DataNodeTest.java b/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/model/DataNodeTest.java index 473dc07d119a7b6a0f5d232156e4684b274510d5..c767c2bae8505d6fee5426cb9f2d01289a951dee 100644 --- a/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/model/DataNodeTest.java +++ b/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/model/DataNodeTest.java @@ -1,27 +1,23 @@ package lcsb.mapviewer.wikipathway.model; import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; -public class DataNodeTest { +import lcsb.mapviewer.wikipathway.WikipathwaysTestFunctions; - @Before - public void setUp() throws Exception { - } +public class DataNodeTest extends WikipathwaysTestFunctions { - @After - public void tearDown() throws Exception { - } - @Test - public void testSeialization() { - try { - SerializationUtils.serialize(new DataNode()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testSeialization() { + SerializationUtils.serialize(new DataNode()); + } } diff --git a/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/model/EdgeTest.java b/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/model/EdgeTest.java index 4590ce4a2269c56259c93cc7d1470627f0d13d5b..c4c6d8ccd1b5506394f839265f3bb1e1b6e9051e 100644 --- a/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/model/EdgeTest.java +++ b/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/model/EdgeTest.java @@ -1,27 +1,23 @@ package lcsb.mapviewer.wikipathway.model; import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; -public class EdgeTest { +import lcsb.mapviewer.wikipathway.WikipathwaysTestFunctions; - @Before - public void setUp() throws Exception { - } +public class EdgeTest extends WikipathwaysTestFunctions { - @After - public void tearDown() throws Exception { - } - @Test - public void testSeialization() { - try { - SerializationUtils.serialize(new Edge()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testSeialization() { + SerializationUtils.serialize(new Edge()); + } } diff --git a/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/model/GraphTest.java b/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/model/GraphTest.java index 3796974d2551c05d07b35d1aa23292c52e7b991f..e3b7b0d135c29c2bb3247f6e71258b603614b4b1 100644 --- a/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/model/GraphTest.java +++ b/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/model/GraphTest.java @@ -1,28 +1,23 @@ package lcsb.mapviewer.wikipathway.model; import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; -public class GraphTest { +import lcsb.mapviewer.wikipathway.WikipathwaysTestFunctions; - @Before - public void setUp() throws Exception { - } +public class GraphTest extends WikipathwaysTestFunctions { - @After - public void tearDown() throws Exception { - } + @Before + public void setUp() throws Exception { + } - @Test - public void testSeialization() { - try { - SerializationUtils.serialize(new Graph()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } + @After + public void tearDown() throws Exception { + } + + @Test + public void testSeialization() { + SerializationUtils.serialize(new Graph()); + } } diff --git a/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/model/GroupTest.java b/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/model/GroupTest.java index 1bfb56fe8d9a4d9fe342252c401c90af2076fe3e..91e63fb832b4235c4192bea8e333e5437ffe9714 100644 --- a/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/model/GroupTest.java +++ b/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/model/GroupTest.java @@ -1,27 +1,23 @@ package lcsb.mapviewer.wikipathway.model; import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; -public class GroupTest { +import lcsb.mapviewer.wikipathway.WikipathwaysTestFunctions; - @Before - public void setUp() throws Exception { - } +public class GroupTest extends WikipathwaysTestFunctions { - @After - public void tearDown() throws Exception { - } - @Test - public void testSeialization() { - try { - SerializationUtils.serialize(new Group()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testSeialization() { + SerializationUtils.serialize(new Group()); + } } diff --git a/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/model/InteractionTest.java b/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/model/InteractionTest.java index 7ad63cc09952a561de10ed56c40fd675714e2d62..9df25879de5f9d3bab693d73a9fdf451fd42a182 100644 --- a/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/model/InteractionTest.java +++ b/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/model/InteractionTest.java @@ -1,27 +1,23 @@ package lcsb.mapviewer.wikipathway.model; import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; -public class InteractionTest { +import lcsb.mapviewer.wikipathway.WikipathwaysTestFunctions; - @Before - public void setUp() throws Exception { - } +public class InteractionTest extends WikipathwaysTestFunctions { - @After - public void tearDown() throws Exception { - } - @Test - public void testSeialization() { - try { - SerializationUtils.serialize(new Interaction()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testSeialization() { + SerializationUtils.serialize(new Interaction()); + } } diff --git a/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/model/LabelTest.java b/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/model/LabelTest.java index 9bef316064feb32043965f8cffbef28987d48d2e..e11f0585335056dcc18dd021d0db0737c12453ae 100644 --- a/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/model/LabelTest.java +++ b/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/model/LabelTest.java @@ -1,27 +1,23 @@ package lcsb.mapviewer.wikipathway.model; import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; -public class LabelTest { +import lcsb.mapviewer.wikipathway.WikipathwaysTestFunctions; - @Before - public void setUp() throws Exception { - } +public class LabelTest extends WikipathwaysTestFunctions { - @After - public void tearDown() throws Exception { - } - @Test - public void testSeialization() { - try { - SerializationUtils.serialize(new Label()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testSeialization() { + SerializationUtils.serialize(new Label()); + } } diff --git a/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/model/PointDataTest.java b/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/model/PointDataTest.java index f9a69ce69f93f0459a8b359c588ce0e4f04b8f06..b42102350fcda3b28e7684d87e4977a5c71470b3 100644 --- a/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/model/PointDataTest.java +++ b/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/model/PointDataTest.java @@ -1,27 +1,23 @@ package lcsb.mapviewer.wikipathway.model; import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; -public class PointDataTest { +import lcsb.mapviewer.wikipathway.WikipathwaysTestFunctions; - @Before - public void setUp() throws Exception { - } +public class PointDataTest extends WikipathwaysTestFunctions { - @After - public void tearDown() throws Exception { - } - @Test - public void testSeialization() { - try { - SerializationUtils.serialize(new PointData()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testSeialization() { + SerializationUtils.serialize(new PointData()); + } } diff --git a/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/model/ShapeTest.java b/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/model/ShapeTest.java index 7fef931aa3ac23ae50c4f9f5ee880132df8ede83..e10d64b1b41a78c44eaac54e546afaeb204e9b4d 100644 --- a/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/model/ShapeTest.java +++ b/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/model/ShapeTest.java @@ -1,27 +1,23 @@ package lcsb.mapviewer.wikipathway.model; import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; -public class ShapeTest { +import lcsb.mapviewer.wikipathway.WikipathwaysTestFunctions; - @Before - public void setUp() throws Exception { - } +public class ShapeTest extends WikipathwaysTestFunctions { - @After - public void tearDown() throws Exception { - } - @Test - public void testSeialization() { - try { - SerializationUtils.serialize(new Shape()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testSeialization() { + SerializationUtils.serialize(new Shape()); + } } diff --git a/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/model/StateTest.java b/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/model/StateTest.java index bf38be3dc11b932dad53a248bd69f267b95f3a87..745d7f6bfd3cdf27f9700b8c9e07a9ff0ed1cb62 100644 --- a/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/model/StateTest.java +++ b/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/model/StateTest.java @@ -1,27 +1,23 @@ package lcsb.mapviewer.wikipathway.model; import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; -public class StateTest { +import lcsb.mapviewer.wikipathway.WikipathwaysTestFunctions; - @Before - public void setUp() throws Exception { - } +public class StateTest extends WikipathwaysTestFunctions { - @After - public void tearDown() throws Exception { - } - @Test - public void testSeialization() { - try { - SerializationUtils.serialize(new State()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testSeialization() { + SerializationUtils.serialize(new State()); + } } diff --git a/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/model/biopax/BiopaxDataTest.java b/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/model/biopax/BiopaxDataTest.java index e3e3b7bc43fac829ec250a2177bcfa1948f782f1..d19c07d34817b905d8d115415ce0935f7ca94d15 100644 --- a/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/model/biopax/BiopaxDataTest.java +++ b/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/model/biopax/BiopaxDataTest.java @@ -1,28 +1,23 @@ package lcsb.mapviewer.wikipathway.model.biopax; import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; -public class BiopaxDataTest { +import lcsb.mapviewer.wikipathway.WikipathwaysTestFunctions; - @Before - public void setUp() throws Exception { - } +public class BiopaxDataTest extends WikipathwaysTestFunctions { - @After - public void tearDown() throws Exception { - } + @Before + public void setUp() throws Exception { + } - @Test - public void testSeialization() { - try { - SerializationUtils.serialize(new BiopaxData()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } + @After + public void tearDown() throws Exception { + } + + @Test + public void testSeialization() { + SerializationUtils.serialize(new BiopaxData()); + } } diff --git a/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/model/biopax/BiopaxOpenControlledVocabularyTest.java b/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/model/biopax/BiopaxOpenControlledVocabularyTest.java index c8596e88d04fba27acd57f7d705f37d7a0c15aec..4c7c1505d9b335810b092095f9ace1babb55b915 100644 --- a/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/model/biopax/BiopaxOpenControlledVocabularyTest.java +++ b/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/model/biopax/BiopaxOpenControlledVocabularyTest.java @@ -1,28 +1,23 @@ package lcsb.mapviewer.wikipathway.model.biopax; import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; -public class BiopaxOpenControlledVocabularyTest { +import lcsb.mapviewer.wikipathway.WikipathwaysTestFunctions; - @Before - public void setUp() throws Exception { - } +public class BiopaxOpenControlledVocabularyTest extends WikipathwaysTestFunctions { - @After - public void tearDown() throws Exception { - } + @Before + public void setUp() throws Exception { + } - @Test - public void testSeialization() { - try { - SerializationUtils.serialize(new BiopaxOpenControlledVocabulary()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } + @After + public void tearDown() throws Exception { + } + + @Test + public void testSeialization() { + SerializationUtils.serialize(new BiopaxOpenControlledVocabulary()); + } } diff --git a/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/model/biopax/BiopaxPublicationTest.java b/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/model/biopax/BiopaxPublicationTest.java index 044fc1621542f86c91fae65988b7ec116f6b45ef..f5cf6fc357b189d2bf254a7de2fe99a25969cace 100644 --- a/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/model/biopax/BiopaxPublicationTest.java +++ b/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/model/biopax/BiopaxPublicationTest.java @@ -1,28 +1,23 @@ package lcsb.mapviewer.wikipathway.model.biopax; import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; -public class BiopaxPublicationTest { +import lcsb.mapviewer.wikipathway.WikipathwaysTestFunctions; - @Before - public void setUp() throws Exception { - } +public class BiopaxPublicationTest extends WikipathwaysTestFunctions { - @After - public void tearDown() throws Exception { - } + @Before + public void setUp() throws Exception { + } - @Test - public void testSeialization() { - try { - SerializationUtils.serialize(new BiopaxPublication()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } + @After + public void tearDown() throws Exception { + } + + @Test + public void testSeialization() { + SerializationUtils.serialize(new BiopaxPublication()); + } } diff --git a/persist/src/test/java/lcsb/mapviewer/persist/ApplicationContextLoaderTest.java b/persist/src/test/java/lcsb/mapviewer/persist/ApplicationContextLoaderTest.java index 14a9e1e00d7da50b461074a28218ba3a982fa575..a8394a73a6602ea51dcab0395199e08186b3d7c1 100644 --- a/persist/src/test/java/lcsb/mapviewer/persist/ApplicationContextLoaderTest.java +++ b/persist/src/test/java/lcsb/mapviewer/persist/ApplicationContextLoaderTest.java @@ -1,83 +1,74 @@ package lcsb.mapviewer.persist; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.*; import java.lang.reflect.Constructor; -import lcsb.mapviewer.persist.dao.user.UserDao; -import org.apache.logging.log4j.*; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.junit.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; -import org.springframework.security.crypto.password.PasswordEncoder; + +import lcsb.mapviewer.common.UnitTestFailedWatcher; +import lcsb.mapviewer.persist.dao.user.UserDao; public class ApplicationContextLoaderTest { - Logger logger = LogManager.getLogger(ApplicationContextLoaderTest.class); - - ConfigurableApplicationContext originalContext; - - @Before - public void setUp() throws Exception { - originalContext = ApplicationContextLoader.getApplicationContext(); - ApplicationContextLoader.setApplicationContext(null); - } - - @After - public void tearDown() throws Exception { - ApplicationContextLoader.setApplicationContext(originalContext); - } - - @Test - public void testGetters() { - ConfigurableApplicationContext ctx = new AnnotationConfigApplicationContext(SpringPersistTestConfig.class); - ApplicationContextLoader.setApplicationContext(ctx); - assertEquals(ctx, ApplicationContextLoader.getApplicationContext()); - } - - @Test - public void testLoadApplicationContext() { - ConfigurableApplicationContext ctx = new AnnotationConfigApplicationContext(SpringPersistTestConfig.class); - ApplicationContextLoader.setApplicationContext(ctx); - assertNotNull(ApplicationContextLoader.getApplicationContext()); - } - - @Test - public void testInject() { - try { - class Tmp { - @Autowired - private UserDao userDao; - - } - Tmp obj = new Tmp(); - ConfigurableApplicationContext ctx = new AnnotationConfigApplicationContext(SpringPersistTestConfig.class); - ApplicationContextLoader.setApplicationContext(ctx); - ApplicationContextLoader.injectDependencies(obj); - assertNotNull(obj.userDao); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testPrivateConstructor() throws Exception { - - try { - for (Constructor<?> constructor : ApplicationContextLoader.class.getDeclaredConstructors()) { - logger.debug(constructor); - constructor.setAccessible(true); - ApplicationContextLoader obj = (ApplicationContextLoader) constructor.newInstance(new Object[] {}); - assertNotNull(obj); - } - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } + + @Rule + public UnitTestFailedWatcher unitTestFailedWatcher = new UnitTestFailedWatcher(); + + Logger logger = LogManager.getLogger(ApplicationContextLoaderTest.class); + + ConfigurableApplicationContext originalContext; + + @Before + public void setUp() throws Exception { + originalContext = ApplicationContextLoader.getApplicationContext(); + ApplicationContextLoader.setApplicationContext(null); + } + + @After + public void tearDown() throws Exception { + ApplicationContextLoader.setApplicationContext(originalContext); + } + + @Test + public void testGetters() { + ConfigurableApplicationContext ctx = new AnnotationConfigApplicationContext(SpringPersistTestConfig.class); + ApplicationContextLoader.setApplicationContext(ctx); + assertEquals(ctx, ApplicationContextLoader.getApplicationContext()); + } + + @Test + public void testLoadApplicationContext() { + ConfigurableApplicationContext ctx = new AnnotationConfigApplicationContext(SpringPersistTestConfig.class); + ApplicationContextLoader.setApplicationContext(ctx); + assertNotNull(ApplicationContextLoader.getApplicationContext()); + } + + @Test + public void testInject() { + class Tmp { + @Autowired + private UserDao userDao; + + } + Tmp obj = new Tmp(); + ConfigurableApplicationContext ctx = new AnnotationConfigApplicationContext(SpringPersistTestConfig.class); + ApplicationContextLoader.setApplicationContext(ctx); + ApplicationContextLoader.injectDependencies(obj); + assertNotNull(obj.userDao); + } + + @Test + public void testPrivateConstructor() throws Exception { + for (Constructor<?> constructor : ApplicationContextLoader.class.getDeclaredConstructors()) { + constructor.setAccessible(true); + ApplicationContextLoader obj = (ApplicationContextLoader) constructor.newInstance(new Object[] {}); + assertNotNull(obj); + } + } } diff --git a/persist/src/test/java/lcsb/mapviewer/persist/DbUtilsTest.java b/persist/src/test/java/lcsb/mapviewer/persist/DbUtilsTest.java index 1c4cba7474470209144b75c0c4cd8d6cf1c771db..e7144712bff4ba1cce5c17e6b8749f869e4a9dd9 100644 --- a/persist/src/test/java/lcsb/mapviewer/persist/DbUtilsTest.java +++ b/persist/src/test/java/lcsb/mapviewer/persist/DbUtilsTest.java @@ -1,9 +1,6 @@ package lcsb.mapviewer.persist; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -20,45 +17,31 @@ public class DbUtilsTest extends PersistTestFunctions { @Test public void testCreateSession() throws Exception { - try { - assertFalse(dbUtils.isCustomSessionForCurrentThread()); - dbUtils.createSessionForCurrentThread(); - assertTrue(dbUtils.isCustomSessionForCurrentThread()); - assertEquals(1, dbUtils.getSessionCounter()); - dbUtils.closeSessionForCurrentThread(); - assertFalse(dbUtils.isCustomSessionForCurrentThread()); - assertEquals(0, dbUtils.getSessionCounter()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertFalse(dbUtils.isCustomSessionForCurrentThread()); + dbUtils.createSessionForCurrentThread(); + assertTrue(dbUtils.isCustomSessionForCurrentThread()); + assertEquals(1, dbUtils.getSessionCounter()); + dbUtils.closeSessionForCurrentThread(); + assertFalse(dbUtils.isCustomSessionForCurrentThread()); + assertEquals(0, dbUtils.getSessionCounter()); } - @Test + @Test(expected = InvalidStateException.class) public void testCreateInvalidSession() throws Exception { try { dbUtils.createSessionForCurrentThread(); dbUtils.createSessionForCurrentThread(); - fail("Exception expected"); - } catch (InvalidStateException e) { + } finally { dbUtils.closeSessionForCurrentThread(); - } catch (Exception e) { - e.printStackTrace(); - throw e; } } @Test public void testAutoFlush() { - try { - boolean autoflush = dbUtils.isAutoFlush(); - dbUtils.setAutoFlush(false); - assertFalse(dbUtils.isAutoFlush()); - dbUtils.setAutoFlush(autoflush); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + boolean autoflush = dbUtils.isAutoFlush(); + dbUtils.setAutoFlush(false); + assertFalse(dbUtils.isAutoFlush()); + dbUtils.setAutoFlush(autoflush); } } diff --git a/persist/src/test/java/lcsb/mapviewer/persist/PersistTestFunctions.java b/persist/src/test/java/lcsb/mapviewer/persist/PersistTestFunctions.java index 2677d5518d76b70e9da8c0583fd425e26ea28bfe..f49eea32e46783caa579d2bcb2f023f868447466 100644 --- a/persist/src/test/java/lcsb/mapviewer/persist/PersistTestFunctions.java +++ b/persist/src/test/java/lcsb/mapviewer/persist/PersistTestFunctions.java @@ -4,6 +4,7 @@ import java.awt.Color; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; +import org.junit.Rule; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.annotation.Rollback; @@ -11,6 +12,7 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.transaction.annotation.Transactional; +import lcsb.mapviewer.common.UnitTestFailedWatcher; import lcsb.mapviewer.common.geometry.PointTransformation; import lcsb.mapviewer.model.graphics.PolylineData; import lcsb.mapviewer.model.map.compartment.Compartment; @@ -29,6 +31,10 @@ import lcsb.mapviewer.persist.dao.user.UserDao; @ContextConfiguration(classes = SpringPersistTestConfig.class) @RunWith(SpringJUnit4ClassRunner.class) public abstract class PersistTestFunctions { + + @Rule + public UnitTestFailedWatcher unitTestFailedWatcher = new UnitTestFailedWatcher(); + @SuppressWarnings("unused") private Logger logger = LogManager.getLogger(PersistTestFunctions.class); diff --git a/persist/src/test/java/lcsb/mapviewer/persist/dao/ProjectDaoTest.java b/persist/src/test/java/lcsb/mapviewer/persist/dao/ProjectDaoTest.java index 9768cf99823c9add66db0ff38358ac78214560c7..1cdc418437a885153fd88eb19306db5f759dc5bf 100644 --- a/persist/src/test/java/lcsb/mapviewer/persist/dao/ProjectDaoTest.java +++ b/persist/src/test/java/lcsb/mapviewer/persist/dao/ProjectDaoTest.java @@ -1,17 +1,10 @@ package lcsb.mapviewer.persist.dao; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.junit.Assert.*; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.springframework.beans.factory.annotation.Autowired; import lcsb.mapviewer.model.Project; @@ -19,9 +12,7 @@ import lcsb.mapviewer.model.map.OverviewImage; import lcsb.mapviewer.model.map.OverviewModelLink; import lcsb.mapviewer.model.map.layout.DataOverlayImageLayer; import lcsb.mapviewer.model.map.layout.Layout; -import lcsb.mapviewer.model.map.model.Model; -import lcsb.mapviewer.model.map.model.ModelComparator; -import lcsb.mapviewer.model.map.model.ModelFullIndexed; +import lcsb.mapviewer.model.map.model.*; import lcsb.mapviewer.model.map.species.Complex; import lcsb.mapviewer.model.map.species.Species; import lcsb.mapviewer.persist.PersistTestFunctions; @@ -44,122 +35,96 @@ public class ProjectDaoTest extends PersistTestFunctions { @Test public void testGetProjectByName() throws Exception { - try { - Project project = new Project(); - project.setProjectId(projectId); - projectDao.add(project); - projectDao.evict(project); - - Project project2 = projectDao.getProjectByProjectId(projectId); - assertNotNull(project2); - assertFalse(project2.equals(project)); - assertEquals(project.getId(), project2.getId()); - - projectDao.delete(project2); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Project project = new Project(); + project.setProjectId(projectId); + projectDao.add(project); + projectDao.evict(project); + + Project project2 = projectDao.getProjectByProjectId(projectId); + assertNotNull(project2); + assertFalse(project2.equals(project)); + assertEquals(project.getId(), project2.getId()); + + projectDao.delete(project2); } @Test public void testGetProjectForModelId() throws Exception { - try { - Project project = new Project(); - project.setProjectId(projectId); - projectDao.add(project); - Model model = new ModelFullIndexed(null); - project.addModel(model); - modelDao.add(model); - modelDao.evict(model); - projectDao.evict(project); - - Project project2 = projectDao.getProjectForModelId(model.getId()); - assertNotNull(project2); - assertFalse(project2.equals(project)); - assertEquals(project.getId(), project2.getId()); - - modelDao.delete(modelDao.getById(model.getId())); - projectDao.delete(project2); - - assertNull(projectDao.getProjectForModelId(model.getId())); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Project project = new Project(); + project.setProjectId(projectId); + projectDao.add(project); + Model model = new ModelFullIndexed(null); + project.addModel(model); + modelDao.add(model); + modelDao.evict(model); + projectDao.evict(project); + + Project project2 = projectDao.getProjectForModelId(model.getId()); + assertNotNull(project2); + assertFalse(project2.equals(project)); + assertEquals(project.getId(), project2.getId()); + + modelDao.delete(modelDao.getById(model.getId())); + projectDao.delete(project2); + + assertNull(projectDao.getProjectForModelId(model.getId())); } @Test public void testProjectExists() throws Exception { - try { - Project project = new Project(projectId); + Project project = new Project(projectId); - assertFalse(projectDao.isProjectExistsByName(projectId)); + assertFalse(projectDao.isProjectExistsByName(projectId)); - projectDao.add(project); - projectDao.evict(project); + projectDao.add(project); + projectDao.evict(project); - assertTrue(projectDao.isProjectExistsByName(projectId)); + assertTrue(projectDao.isProjectExistsByName(projectId)); - Project project2 = projectDao.getProjectByProjectId(projectId); + Project project2 = projectDao.getProjectByProjectId(projectId); - projectDao.delete(project2); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + projectDao.delete(project2); } @Test public void testCheckEqualityAfterReload() throws Exception { - try { - Project project = new Project(projectId); - projectDao.add(project); - projectDao.flush(); + Project project = new Project(projectId); + projectDao.add(project); + projectDao.flush(); - Model model = createModel(); - project.addModel(model); + Model model = createModel(); + project.addModel(model); - projectDao.update(project); - projectDao.evict(project); + projectDao.update(project); + projectDao.evict(project); - ModelComparator comparator = new ModelComparator(); + ModelComparator comparator = new ModelComparator(); - Model model2 = new ModelFullIndexed(modelDao.getLastModelForProjectIdentifier(projectId, false)); + Model model2 = new ModelFullIndexed(modelDao.getLastModelForProjectIdentifier(projectId, false)); - assertEquals(0, comparator.compare(model, model2)); + assertEquals(0, comparator.compare(model, model2)); - projectDao.delete(projectDao.getById(project.getId())); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + projectDao.delete(projectDao.getById(project.getId())); } @Test public void testCheckEqualityAfterReload2() throws Exception { - try { - Project project = new Project(projectId); - Model model = createModel(); - project.addModel(model); + Project project = new Project(projectId); + Model model = createModel(); + project.addModel(model); - projectDao.add(project); - projectDao.evict(project); + projectDao.add(project); + projectDao.evict(project); - Project project2 = projectDao.getProjectByProjectId(projectId); + Project project2 = projectDao.getProjectByProjectId(projectId); - ModelComparator comparator = new ModelComparator(); + ModelComparator comparator = new ModelComparator(); - Model fullModel1 = new ModelFullIndexed(project.getModels().iterator().next()); - Model fullModel2 = new ModelFullIndexed(project2.getModels().iterator().next()); - assertEquals(0, comparator.compare(fullModel1, fullModel2)); + Model fullModel1 = new ModelFullIndexed(project.getModels().iterator().next()); + Model fullModel2 = new ModelFullIndexed(project2.getModels().iterator().next()); + assertEquals(0, comparator.compare(fullModel1, fullModel2)); - projectDao.delete(project2); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + projectDao.delete(project2); } private Model createModel() { @@ -190,42 +155,37 @@ public class ProjectDaoTest extends PersistTestFunctions { @Test public void testAddGetProjectWithOverviewImage() throws Exception { - try { - Project project = new Project(projectId); - Model model = new ModelFullIndexed(null); - OverviewImage oi = new OverviewImage(); - oi.setFilename("test"); - OverviewModelLink oml = new OverviewModelLink(); - oml.setPolygon("10,10 20,20 20,100"); - oml.setxCoord(1); - oml.setyCoord(2); - oml.setZoomLevel(3); - oml.setLinkedModel(model); - oi.addLink(oml); - project.addOverviewImage(oi); - project.addModel(model); - - projectDao.add(project); - projectDao.evict(project); - - Project project2 = projectDao.getProjectByProjectId(projectId); - assertNotNull(project2); - - OverviewImage oi2 = project2.getOverviewImages().get(0); - OverviewModelLink oml2 = (OverviewModelLink) oi2.getLinks().get(0); - - assertEquals(oi.getFilename(), oi2.getFilename()); - assertEquals(oml.getPolygon(), oml2.getPolygon()); - assertEquals(oml.getxCoord(), oml2.getxCoord()); - assertEquals(oml.getyCoord(), oml2.getyCoord()); - assertEquals(oml.getZoomLevel(), oml2.getZoomLevel()); - assertNotNull(oml2.getPolygonCoordinates()); - - projectDao.delete(project2); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Project project = new Project(projectId); + Model model = new ModelFullIndexed(null); + OverviewImage oi = new OverviewImage(); + oi.setFilename("test"); + OverviewModelLink oml = new OverviewModelLink(); + oml.setPolygon("10,10 20,20 20,100"); + oml.setxCoord(1); + oml.setyCoord(2); + oml.setZoomLevel(3); + oml.setLinkedModel(model); + oi.addLink(oml); + project.addOverviewImage(oi); + project.addModel(model); + + projectDao.add(project); + projectDao.evict(project); + + Project project2 = projectDao.getProjectByProjectId(projectId); + assertNotNull(project2); + + OverviewImage oi2 = project2.getOverviewImages().get(0); + OverviewModelLink oml2 = (OverviewModelLink) oi2.getLinks().get(0); + + assertEquals(oi.getFilename(), oi2.getFilename()); + assertEquals(oml.getPolygon(), oml2.getPolygon()); + assertEquals(oml.getxCoord(), oml2.getxCoord()); + assertEquals(oml.getyCoord(), oml2.getyCoord()); + assertEquals(oml.getZoomLevel(), oml2.getZoomLevel()); + assertNotNull(oml2.getPolygonCoordinates()); + + projectDao.delete(project2); } /** @@ -235,88 +195,67 @@ public class ProjectDaoTest extends PersistTestFunctions { */ @Test public void testCreationWarnings() throws Exception { - try { - Project project = new Project("test_project_id"); - project.addWarning("warning A"); - project.addWarning("warning B"); - assertEquals(2, project.getWarnings().size()); + Project project = new Project("test_project_id"); + project.addWarning("warning A"); + project.addWarning("warning B"); + assertEquals(2, project.getWarnings().size()); - projectDao.add(project); + projectDao.add(project); - projectDao.evict(project); - Project project2 = projectDao.getById(project.getId()); + projectDao.evict(project); + Project project2 = projectDao.getById(project.getId()); - assertEquals(2, project2.getWarnings().size()); + assertEquals(2, project2.getWarnings().size()); - projectDao.delete(project2); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + projectDao.delete(project2); } @Test public void testGetAll() throws Exception { - try { - - long startTime = System.currentTimeMillis(); - double max = 10; - - logger.debug("---"); - for (int i = 0; i < max; i++) { - projectDao.getAll(); - } - long estimatedTime = System.currentTimeMillis() - startTime; - logger.debug(estimatedTime / max); - } catch (Exception e) { - e.printStackTrace(); - throw e; + long startTime = System.currentTimeMillis(); + double max = 10; + + logger.debug("---"); + for (int i = 0; i < max; i++) { + projectDao.getAll(); } + long estimatedTime = System.currentTimeMillis() - startTime; + logger.debug(estimatedTime / max); } @Test public void testLayoutsInProject() throws Exception { - try { - Project project = new Project("test_porject_id"); - Model model = createModel(); - project.addModel(model); - projectDao.add(project); - - Layout layout = new Layout(); - layout.addDataOverlayImageLayer(new DataOverlayImageLayer(model, "tmp")); - layout.setTitle("temporary name"); - project.addLayout(layout); - - modelDao.evict(model); - projectDao.evict(project); - Project project2 = projectDao.getById(project.getId()); - - assertEquals(1, project2.getLayouts().size()); - assertEquals("tmp", - project2.getLayouts().iterator().next().getDataOverlayImageLayers().iterator().next().getDirectory()); - assertEquals("temporary name", project2.getLayouts().iterator().next().getTitle()); - - project = projectDao.getById(project.getId()); - projectDao.delete(project); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Project project = new Project("test_porject_id"); + Model model = createModel(); + project.addModel(model); + projectDao.add(project); + + Layout layout = new Layout(); + layout.addDataOverlayImageLayer(new DataOverlayImageLayer(model, "tmp")); + layout.setTitle("temporary name"); + project.addLayout(layout); + + modelDao.evict(model); + projectDao.evict(project); + Project project2 = projectDao.getById(project.getId()); + + assertEquals(1, project2.getLayouts().size()); + assertEquals("tmp", + project2.getLayouts().iterator().next().getDataOverlayImageLayers().iterator().next().getDirectory()); + assertEquals("temporary name", project2.getLayouts().iterator().next().getTitle()); + + project = projectDao.getById(project.getId()); + projectDao.delete(project); } @Test public void testGetNextId() throws Exception { - try { - long id = projectDao.getNextId(); - Project project = new Project(projectId); - projectDao.add(project); - - long id2 = projectDao.getNextId(); - assertNotEquals(id, id2); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + long id = projectDao.getNextId(); + Project project = new Project(projectId); + projectDao.add(project); + + long id2 = projectDao.getNextId(); + assertNotEquals(id, id2); } } diff --git a/persist/src/test/java/lcsb/mapviewer/persist/dao/cache/BigFileEntryDaoTest.java b/persist/src/test/java/lcsb/mapviewer/persist/dao/cache/BigFileEntryDaoTest.java index 39aad751d664333c46ddc40602814da613db67fd..c0bd4dea7e91da7e9d2c94b97e2b823cc1d2eb1b 100644 --- a/persist/src/test/java/lcsb/mapviewer/persist/dao/cache/BigFileEntryDaoTest.java +++ b/persist/src/test/java/lcsb/mapviewer/persist/dao/cache/BigFileEntryDaoTest.java @@ -1,12 +1,8 @@ package lcsb.mapviewer.persist.dao.cache; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import static org.junit.Assert.*; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.springframework.beans.factory.annotation.Autowired; import lcsb.mapviewer.model.cache.BigFileEntry; @@ -40,41 +36,31 @@ public class BigFileEntryDaoTest extends PersistTestFunctions { @Test public void testAdd() { - try { - BigFileEntry entry = new BigFileEntry(); - long count = bigFileEntryDao.getCount(); - bigFileEntryDao.add(entry); - long count2 = bigFileEntryDao.getCount(); - bigFileEntryDao.delete(entry); - long count3 = bigFileEntryDao.getCount(); - - assertEquals(count + 1, count2); - assertEquals(count2 - 1, count3); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + BigFileEntry entry = new BigFileEntry(); + long count = bigFileEntryDao.getCount(); + bigFileEntryDao.add(entry); + long count2 = bigFileEntryDao.getCount(); + bigFileEntryDao.delete(entry); + long count3 = bigFileEntryDao.getCount(); + + assertEquals(count + 1, count2); + assertEquals(count2 - 1, count3); } @Test public void testGetByUrl() { - try { - String url = "xxx.yyy"; - BigFileEntry entry = new BigFileEntry(); - entry.setUrl(url); - - BigFileEntry result = bigFileEntryDao.getByUrl(url); - assertNull(result); - bigFileEntryDao.add(entry); - - result = bigFileEntryDao.getByUrl(url); - assertEquals(entry, result); - - bigFileEntryDao.delete(entry); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String url = "xxx.yyy"; + BigFileEntry entry = new BigFileEntry(); + entry.setUrl(url); + + BigFileEntry result = bigFileEntryDao.getByUrl(url); + assertNull(result); + bigFileEntryDao.add(entry); + + result = bigFileEntryDao.getByUrl(url); + assertEquals(entry, result); + + bigFileEntryDao.delete(entry); } } diff --git a/persist/src/test/java/lcsb/mapviewer/persist/dao/cache/CacheQueryDaoTest.java b/persist/src/test/java/lcsb/mapviewer/persist/dao/cache/CacheQueryDaoTest.java index f20805be7bd1ac7fabb283deaaa9c80db0f621ce..5cbb5ee9c0947cb3ecc65cd43c03eb48f82b0773 100644 --- a/persist/src/test/java/lcsb/mapviewer/persist/dao/cache/CacheQueryDaoTest.java +++ b/persist/src/test/java/lcsb/mapviewer/persist/dao/cache/CacheQueryDaoTest.java @@ -1,11 +1,8 @@ package lcsb.mapviewer.persist.dao.cache; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import static org.junit.Assert.*; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.springframework.beans.factory.annotation.Autowired; import lcsb.mapviewer.model.cache.CacheQuery; @@ -30,20 +27,15 @@ public class CacheQueryDaoTest extends PersistTestFunctions { @Test public void testGetByQuery() { - try { - CacheType type = cacheTypeDao.getByClassName("lcsb.mapviewer.reactome.utils.ReactomeConnector"); - CacheQuery query = new CacheQuery(); - query.setType(type); - query.setQuery("test"); - cacheQueryDao.add(query); - assertEquals(query, cacheQueryDao.getByQuery("test", type)); - assertNull(cacheQueryDao.getByQuery("another_test_bla", type)); - - cacheQueryDao.delete(query); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + CacheType type = cacheTypeDao.getByClassName("lcsb.mapviewer.reactome.utils.ReactomeConnector"); + CacheQuery query = new CacheQuery(); + query.setType(type); + query.setQuery("test"); + cacheQueryDao.add(query); + assertEquals(query, cacheQueryDao.getByQuery("test", type)); + assertNull(cacheQueryDao.getByQuery("another_test_bla", type)); + + cacheQueryDao.delete(query); } } diff --git a/persist/src/test/java/lcsb/mapviewer/persist/dao/cache/CacheTypeDaoTest.java b/persist/src/test/java/lcsb/mapviewer/persist/dao/cache/CacheTypeDaoTest.java index 27174a0188842e903049330099be0dae9a123539..16986e9689aedb25cd6cc68406ee30f4784d0d08 100644 --- a/persist/src/test/java/lcsb/mapviewer/persist/dao/cache/CacheTypeDaoTest.java +++ b/persist/src/test/java/lcsb/mapviewer/persist/dao/cache/CacheTypeDaoTest.java @@ -1,12 +1,8 @@ package lcsb.mapviewer.persist.dao.cache; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +import static org.junit.Assert.*; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.springframework.beans.factory.annotation.Autowired; import lcsb.mapviewer.model.cache.CacheType; @@ -27,90 +23,50 @@ public class CacheTypeDaoTest extends PersistTestFunctions { @Test public void testReactomeCacheData() throws Exception { - try { - CacheType cacheType = cacheTypeDao.getByClassName("lcsb.mapviewer.reactome.utils.ReactomeConnector"); - assertNotNull(cacheType); - assertEquals(0, cacheType.getId()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + CacheType cacheType = cacheTypeDao.getByClassName("lcsb.mapviewer.reactome.utils.ReactomeConnector"); + assertNotNull(cacheType); + assertEquals(0, cacheType.getId()); } @Test public void testEmpty() throws Exception { - try { - assertNull(cacheTypeDao.getByClassName("blablabla")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertNull(cacheTypeDao.getByClassName("blablabla")); } @Test public void testChemblCacheData() throws Exception { - try { - CacheType cacheType = cacheTypeDao.getByClassName("lcsb.mapviewer.annotation.services.ChEMBLParser"); - assertNotNull(cacheType); - assertEquals(2, cacheType.getId()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + CacheType cacheType = cacheTypeDao.getByClassName("lcsb.mapviewer.annotation.services.ChEMBLParser"); + assertNotNull(cacheType); + assertEquals(2, cacheType.getId()); } @Test public void testArticleCacheData() throws Exception { - try { - CacheType cacheType = cacheTypeDao.getByClassName("lcsb.mapviewer.annotation.services.PubmedParser"); - assertNotNull(cacheType); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + CacheType cacheType = cacheTypeDao.getByClassName("lcsb.mapviewer.annotation.services.PubmedParser"); + assertNotNull(cacheType); } @Test public void testDrugBankCacheData() throws Exception { - try { - CacheType cacheType = cacheTypeDao.getByClassName("lcsb.mapviewer.annotation.services.DrugbankHTMLParser"); - assertNotNull(cacheType); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + CacheType cacheType = cacheTypeDao.getByClassName("lcsb.mapviewer.annotation.services.DrugbankHTMLParser"); + assertNotNull(cacheType); } @Test public void testMockCacheData() throws Exception { - try { - CacheType cacheType = cacheTypeDao.getByClassName("lcsb.mapviewer.annotation.cache.MockCacheInterface"); - assertNotNull(cacheType); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + CacheType cacheType = cacheTypeDao.getByClassName("lcsb.mapviewer.annotation.cache.MockCacheInterface"); + assertNotNull(cacheType); } @Test public void testChebiCacheData() throws Exception { - try { - CacheType cacheType = cacheTypeDao.getByClassName("lcsb.mapviewer.annotation.services.annotators.ChebiAnnotator"); - assertNotNull(cacheType); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + CacheType cacheType = cacheTypeDao.getByClassName("lcsb.mapviewer.annotation.services.annotators.ChebiAnnotator"); + assertNotNull(cacheType); } @Test public void testGoCacheData() throws Exception { - try { - CacheType cacheType = cacheTypeDao.getByClassName("lcsb.mapviewer.annotation.services.annotators.GoAnnotator"); - assertNotNull(cacheType); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + CacheType cacheType = cacheTypeDao.getByClassName("lcsb.mapviewer.annotation.services.annotators.GoAnnotator"); + assertNotNull(cacheType); } } diff --git a/persist/src/test/java/lcsb/mapviewer/persist/dao/cache/UploadedFileEntryDaoTest.java b/persist/src/test/java/lcsb/mapviewer/persist/dao/cache/UploadedFileEntryDaoTest.java index 59ae50401773b6b6a299bb31e1814a8eeb6a8784..77b22f20f1197bcf5e53085836458c8aa582305a 100644 --- a/persist/src/test/java/lcsb/mapviewer/persist/dao/cache/UploadedFileEntryDaoTest.java +++ b/persist/src/test/java/lcsb/mapviewer/persist/dao/cache/UploadedFileEntryDaoTest.java @@ -1,11 +1,8 @@ package lcsb.mapviewer.persist.dao.cache; -import static org.junit.Assert.assertEquals; +import static org.junit.Assert.*; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.springframework.beans.factory.annotation.Autowired; import lcsb.mapviewer.model.cache.UploadedFileEntry; @@ -14,45 +11,40 @@ import lcsb.mapviewer.persist.PersistTestFunctions; public class UploadedFileEntryDaoTest extends PersistTestFunctions { - @Autowired - UploadedFileEntryDao uploadedFileEntryDao; - - @Autowired - DbUtils dbUtils; - - boolean flush; - - @AfterClass - public static void tearDownAfterClass() throws Exception { - } - - @Before - public void setUp() throws Exception { - flush = dbUtils.isAutoFlush(); - dbUtils.setAutoFlush(true); - } - - @After - public void tearDown() throws Exception { - dbUtils.setAutoFlush(flush); - } - - @Test - public void testAdd() { - try { - UploadedFileEntry entry = new UploadedFileEntry(); - long count = uploadedFileEntryDao.getCount(); - uploadedFileEntryDao.add(entry); - long count2 = uploadedFileEntryDao.getCount(); - uploadedFileEntryDao.delete(entry); - long count3 = uploadedFileEntryDao.getCount(); - - assertEquals(count + 1, count2); - assertEquals(count2 - 1, count3); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } + @Autowired + UploadedFileEntryDao uploadedFileEntryDao; + + @Autowired + DbUtils dbUtils; + + boolean flush; + + @AfterClass + public static void tearDownAfterClass() throws Exception { + } + + @Before + public void setUp() throws Exception { + flush = dbUtils.isAutoFlush(); + dbUtils.setAutoFlush(true); + } + + @After + public void tearDown() throws Exception { + dbUtils.setAutoFlush(flush); + } + + @Test + public void testAdd() { + UploadedFileEntry entry = new UploadedFileEntry(); + long count = uploadedFileEntryDao.getCount(); + uploadedFileEntryDao.add(entry); + long count2 = uploadedFileEntryDao.getCount(); + uploadedFileEntryDao.delete(entry); + long count3 = uploadedFileEntryDao.getCount(); + + assertEquals(count + 1, count2); + assertEquals(count2 - 1, count3); + } } diff --git a/persist/src/test/java/lcsb/mapviewer/persist/dao/map/CommentDaoTest.java b/persist/src/test/java/lcsb/mapviewer/persist/dao/map/CommentDaoTest.java index 956fb6ba8acde78688caae8173708d4aeb5aec36..dc2df4e2a10cc03afd43237384b1eb56b9f5bdd5 100644 --- a/persist/src/test/java/lcsb/mapviewer/persist/dao/map/CommentDaoTest.java +++ b/persist/src/test/java/lcsb/mapviewer/persist/dao/map/CommentDaoTest.java @@ -1,27 +1,19 @@ package lcsb.mapviewer.persist.dao.map; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.*; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.springframework.beans.factory.annotation.Autowired; import lcsb.mapviewer.model.Project; -import lcsb.mapviewer.model.map.Comment; -import lcsb.mapviewer.model.map.MiriamData; -import lcsb.mapviewer.model.map.MiriamRelationType; -import lcsb.mapviewer.model.map.MiriamType; +import lcsb.mapviewer.model.map.*; import lcsb.mapviewer.model.map.compartment.Compartment; import lcsb.mapviewer.model.map.layout.graphics.Layer; import lcsb.mapviewer.model.map.layout.graphics.LayerRect; import lcsb.mapviewer.model.map.model.Model; import lcsb.mapviewer.model.map.model.ModelFullIndexed; import lcsb.mapviewer.model.map.reaction.Reaction; -import lcsb.mapviewer.model.map.species.Complex; -import lcsb.mapviewer.model.map.species.GenericProtein; -import lcsb.mapviewer.model.map.species.Species; +import lcsb.mapviewer.model.map.species.*; import lcsb.mapviewer.model.map.species.field.Residue; import lcsb.mapviewer.model.user.User; import lcsb.mapviewer.persist.PersistTestFunctions; @@ -55,70 +47,57 @@ public class CommentDaoTest extends PersistTestFunctions { @Test public void testGetById() throws Exception { - try { - int counter = (int) commentDao.getCount(); - Comment comment = new Comment(); - comment.setUser(user); - commentDao.add(comment); - int counter2 = (int) commentDao.getCount(); - assertEquals(counter + 1, counter2); - Comment comment2 = commentDao.getById(comment.getId()); - assertNotNull(comment2); - commentDao.delete(comment); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + int counter = (int) commentDao.getCount(); + Comment comment = new Comment(); + comment.setUser(user); + commentDao.add(comment); + int counter2 = (int) commentDao.getCount(); + assertEquals(counter + 1, counter2); + Comment comment2 = commentDao.getById(comment.getId()); + assertNotNull(comment2); + commentDao.delete(comment); } @Test public void testGetComments() { - try { - Model model = createModel(); - project.addModel(model); - modelDao.add(model); - projectDao.update(project); - - Comment comment = new Comment(); - comment.setDeleted(true); - comment.setModel(model); - commentDao.add(comment); - - Comment comment2 = new Comment(); - comment2.setPinned(true); - comment2.setModel(model); - commentDao.add(comment2); - - assertEquals(0, commentDao.getCommentByModel(model, true, true).size()); - assertEquals(1, commentDao.getCommentByModel(model, false, true).size()); - assertEquals(1, commentDao.getCommentByModel(model, null, true).size()); - assertEquals(1, commentDao.getCommentByModel(model, true, false).size()); - assertEquals(0, commentDao.getCommentByModel(model, false, false).size()); - assertEquals(1, commentDao.getCommentByModel(model, null, false).size()); - assertEquals(1, commentDao.getCommentByModel(model, true, null).size()); - assertEquals(1, commentDao.getCommentByModel(model, false, null).size()); - assertEquals(2, commentDao.getCommentByModel(model, null, null).size()); - - assertEquals(0, commentDao.getCommentByModel(model.getModelData(), true, true).size()); - assertEquals(1, commentDao.getCommentByModel(model.getModelData(), false, true).size()); - assertEquals(1, commentDao.getCommentByModel(model.getModelData(), null, true).size()); - assertEquals(1, commentDao.getCommentByModel(model.getModelData(), true, false).size()); - assertEquals(0, commentDao.getCommentByModel(model.getModelData(), false, false).size()); - assertEquals(1, commentDao.getCommentByModel(model.getModelData(), null, false).size()); - assertEquals(1, commentDao.getCommentByModel(model.getModelData(), true, null).size()); - assertEquals(1, commentDao.getCommentByModel(model.getModelData(), false, null).size()); - assertEquals(2, commentDao.getCommentByModel(model.getModelData(), null, null).size()); - - commentDao.delete(comment); - commentDao.delete(comment2); - modelDao.delete(model); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - + Model model = createModel(); + project.addModel(model); + modelDao.add(model); + projectDao.update(project); + + Comment comment = new Comment(); + comment.setDeleted(true); + comment.setModel(model); + commentDao.add(comment); + + Comment comment2 = new Comment(); + comment2.setPinned(true); + comment2.setModel(model); + commentDao.add(comment2); + + assertEquals(0, commentDao.getCommentByModel(model, true, true).size()); + assertEquals(1, commentDao.getCommentByModel(model, false, true).size()); + assertEquals(1, commentDao.getCommentByModel(model, null, true).size()); + assertEquals(1, commentDao.getCommentByModel(model, true, false).size()); + assertEquals(0, commentDao.getCommentByModel(model, false, false).size()); + assertEquals(1, commentDao.getCommentByModel(model, null, false).size()); + assertEquals(1, commentDao.getCommentByModel(model, true, null).size()); + assertEquals(1, commentDao.getCommentByModel(model, false, null).size()); + assertEquals(2, commentDao.getCommentByModel(model, null, null).size()); + + assertEquals(0, commentDao.getCommentByModel(model.getModelData(), true, true).size()); + assertEquals(1, commentDao.getCommentByModel(model.getModelData(), false, true).size()); + assertEquals(1, commentDao.getCommentByModel(model.getModelData(), null, true).size()); + assertEquals(1, commentDao.getCommentByModel(model.getModelData(), true, false).size()); + assertEquals(0, commentDao.getCommentByModel(model.getModelData(), false, false).size()); + assertEquals(1, commentDao.getCommentByModel(model.getModelData(), null, false).size()); + assertEquals(1, commentDao.getCommentByModel(model.getModelData(), true, null).size()); + assertEquals(1, commentDao.getCommentByModel(model.getModelData(), false, null).size()); + assertEquals(2, commentDao.getCommentByModel(model.getModelData(), null, null).size()); + + commentDao.delete(comment); + commentDao.delete(comment2); + modelDao.delete(model); } private Model createModel() { diff --git a/persist/src/test/java/lcsb/mapviewer/persist/dao/map/LayoutDaoTest.java b/persist/src/test/java/lcsb/mapviewer/persist/dao/map/LayoutDaoTest.java index 10f28524491da562544450cbc825d36e73685c26..54f3d341f9fe0926e05781cd233ad01b57e75ac3 100644 --- a/persist/src/test/java/lcsb/mapviewer/persist/dao/map/LayoutDaoTest.java +++ b/persist/src/test/java/lcsb/mapviewer/persist/dao/map/LayoutDaoTest.java @@ -1,24 +1,18 @@ package lcsb.mapviewer.persist.dao.map; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +import static org.junit.Assert.*; import java.nio.charset.StandardCharsets; import java.util.List; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.springframework.beans.factory.annotation.Autowired; import lcsb.mapviewer.model.Project; import lcsb.mapviewer.model.cache.UploadedFileEntry; -import lcsb.mapviewer.model.map.MiriamData; -import lcsb.mapviewer.model.map.MiriamRelationType; -import lcsb.mapviewer.model.map.MiriamType; +import lcsb.mapviewer.model.map.*; import lcsb.mapviewer.model.map.compartment.Compartment; import lcsb.mapviewer.model.map.layout.DataOverlayImageLayer; import lcsb.mapviewer.model.map.layout.Layout; @@ -26,9 +20,7 @@ import lcsb.mapviewer.model.map.layout.graphics.Layer; import lcsb.mapviewer.model.map.model.Model; import lcsb.mapviewer.model.map.model.ModelFullIndexed; import lcsb.mapviewer.model.map.reaction.Reaction; -import lcsb.mapviewer.model.map.species.Complex; -import lcsb.mapviewer.model.map.species.Protein; -import lcsb.mapviewer.model.map.species.Species; +import lcsb.mapviewer.model.map.species.*; import lcsb.mapviewer.model.map.species.field.Residue; import lcsb.mapviewer.model.user.User; import lcsb.mapviewer.persist.PersistTestFunctions; @@ -55,40 +47,35 @@ public class LayoutDaoTest extends PersistTestFunctions { */ @Test public void testLayoutsWithData() throws Exception { - try { - Model model = createModel(); + Model model = createModel(); - Project project = new Project("test_project_id"); - project.addModel(model); - projectDao.add(project); + Project project = new Project("test_project_id"); + project.addModel(model); + projectDao.add(project); - modelDao.evict(model); - projectDao.evict(project); + modelDao.evict(model); + projectDao.evict(project); - Layout layout = new Layout(); - layout.addDataOverlayImageLayer(new DataOverlayImageLayer(model, "tmp")); - layout.setTitle("temporary name"); + Layout layout = new Layout(); + layout.addDataOverlayImageLayer(new DataOverlayImageLayer(model, "tmp")); + layout.setTitle("temporary name"); - byte[] data = "test".getBytes(); - UploadedFileEntry fileEntry = new UploadedFileEntry(); - fileEntry.setFileContent(data); + byte[] data = "test".getBytes(); + UploadedFileEntry fileEntry = new UploadedFileEntry(); + fileEntry.setFileContent(data); - layout.setInputData(fileEntry); - project.addLayout(layout); - layoutDao.add(layout); + layout.setInputData(fileEntry); + project.addLayout(layout); + layoutDao.add(layout); - layoutDao.evict(layout); + layoutDao.evict(layout); - layout = layoutDao.getById(layout.getId()); + layout = layoutDao.getById(layout.getId()); - assertEquals("test", new String(layout.getInputData().getFileContent(), StandardCharsets.UTF_8)); + assertEquals("test", new String(layout.getInputData().getFileContent(), StandardCharsets.UTF_8)); - project = projectDao.getById(project.getId()); - projectDao.delete(project); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + project = projectDao.getById(project.getId()); + projectDao.delete(project); } /** @@ -98,48 +85,43 @@ public class LayoutDaoTest extends PersistTestFunctions { */ @Test public void testLayoutsWithoutData() throws Exception { - try { - Model model = createModel(); - String tempName = "temporary name"; + Model model = createModel(); + String tempName = "temporary name"; - User user = createUser(); + User user = createUser(); - Project project = new Project("test_project_id"); - project.addModel(model); + Project project = new Project("test_project_id"); + project.addModel(model); - projectDao.add(project); + projectDao.add(project); - assertEquals(0, layoutDao.getCountByUser(user)); - assertEquals(0, layoutDao.getLayoutsByProject(project).size()); - assertNull(layoutDao.getLayoutByName(project, tempName)); + assertEquals(0, layoutDao.getCountByUser(user)); + assertEquals(0, layoutDao.getLayoutsByProject(project).size()); + assertNull(layoutDao.getLayoutByName(project, tempName)); - Layout layout = new Layout(); - layout.addDataOverlayImageLayer(new DataOverlayImageLayer(model, "tmp")); - layout.setTitle(tempName); - layout.setCreator(user); - project.addLayout(layout); - layoutDao.add(layout); + Layout layout = new Layout(); + layout.addDataOverlayImageLayer(new DataOverlayImageLayer(model, "tmp")); + layout.setTitle(tempName); + layout.setCreator(user); + project.addLayout(layout); + layoutDao.add(layout); - modelDao.evict(model); - projectDao.evict(project); - layoutDao.evict(layout); + modelDao.evict(model); + projectDao.evict(project); + layoutDao.evict(layout); - layout = layoutDao.getById(layout.getId()); + layout = layoutDao.getById(layout.getId()); - assertEquals(1, layoutDao.getLayoutsByProject(project).size()); - assertNotNull(layoutDao.getLayoutByName(project, tempName)); - assertEquals(1, layoutDao.getCountByUser(user)); + assertEquals(1, layoutDao.getLayoutsByProject(project).size()); + assertNotNull(layoutDao.getLayoutByName(project, tempName)); + assertEquals(1, layoutDao.getCountByUser(user)); - assertNull(layout.getInputData()); + assertNull(layout.getInputData()); - project = projectDao.getById(project.getId()); - projectDao.delete(project); + project = projectDao.getById(project.getId()); + projectDao.delete(project); - userDao.delete(user); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + userDao.delete(user); } private Model createModel() { @@ -192,37 +174,32 @@ public class LayoutDaoTest extends PersistTestFunctions { @Test public void testGetLayoutsByProject() throws Exception { - try { - Model model = createModel(); + Model model = createModel(); - Project project = new Project("test_project_id"); - project.addModel(model); - projectDao.add(project); + Project project = new Project("test_project_id"); + project.addModel(model); + projectDao.add(project); - List<Layout> result = layoutDao.getLayoutsByProject(project); - assertEquals(0, result.size()); + List<Layout> result = layoutDao.getLayoutsByProject(project); + assertEquals(0, result.size()); - Layout layout = new Layout(); - layout.addDataOverlayImageLayer(new DataOverlayImageLayer(model, "tmp")); - layout.setTitle("temporary name"); + Layout layout = new Layout(); + layout.addDataOverlayImageLayer(new DataOverlayImageLayer(model, "tmp")); + layout.setTitle("temporary name"); - byte[] data = "test".getBytes(); - UploadedFileEntry fileEntry = new UploadedFileEntry(); - fileEntry.setFileContent(data); + byte[] data = "test".getBytes(); + UploadedFileEntry fileEntry = new UploadedFileEntry(); + fileEntry.setFileContent(data); - layout.setInputData(fileEntry); - project.addLayout(layout); - layoutDao.add(layout); + layout.setInputData(fileEntry); + project.addLayout(layout); + layoutDao.add(layout); - result = layoutDao.getLayoutsByProject(project); - assertEquals(1, result.size()); + result = layoutDao.getLayoutsByProject(project); + assertEquals(1, result.size()); - project = projectDao.getById(project.getId()); - projectDao.delete(project); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + project = projectDao.getById(project.getId()); + projectDao.delete(project); } } diff --git a/persist/src/test/java/lcsb/mapviewer/persist/dao/map/ModelDaoTest.java b/persist/src/test/java/lcsb/mapviewer/persist/dao/map/ModelDaoTest.java index 95bd2ef476ad7fc4931305d20aafe2a393438ccf..f7983dae4b7b5e664571cd99ea546fbaf1d4d831 100644 --- a/persist/src/test/java/lcsb/mapviewer/persist/dao/map/ModelDaoTest.java +++ b/persist/src/test/java/lcsb/mapviewer/persist/dao/map/ModelDaoTest.java @@ -1,43 +1,22 @@ package lcsb.mapviewer.persist.dao.map; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.junit.Assert.*; import java.awt.geom.Point2D; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import lcsb.mapviewer.model.Project; -import lcsb.mapviewer.model.map.MiriamData; -import lcsb.mapviewer.model.map.MiriamRelationType; -import lcsb.mapviewer.model.map.MiriamType; +import lcsb.mapviewer.model.map.*; import lcsb.mapviewer.model.map.compartment.Compartment; -import lcsb.mapviewer.model.map.kinetics.SbmlFunction; -import lcsb.mapviewer.model.map.kinetics.SbmlKinetics; -import lcsb.mapviewer.model.map.kinetics.SbmlParameter; -import lcsb.mapviewer.model.map.kinetics.SbmlUnit; -import lcsb.mapviewer.model.map.kinetics.SbmlUnitType; -import lcsb.mapviewer.model.map.kinetics.SbmlUnitTypeFactor; +import lcsb.mapviewer.model.map.kinetics.*; import lcsb.mapviewer.model.map.layout.graphics.Layer; -import lcsb.mapviewer.model.map.model.Author; -import lcsb.mapviewer.model.map.model.Model; -import lcsb.mapviewer.model.map.model.ModelComparator; -import lcsb.mapviewer.model.map.model.ModelData; -import lcsb.mapviewer.model.map.model.ModelFullIndexed; +import lcsb.mapviewer.model.map.model.*; import lcsb.mapviewer.model.map.reaction.Reaction; import lcsb.mapviewer.model.map.reaction.type.ModulationReaction; -import lcsb.mapviewer.model.map.species.Complex; -import lcsb.mapviewer.model.map.species.Element; -import lcsb.mapviewer.model.map.species.GenericProtein; -import lcsb.mapviewer.model.map.species.Protein; -import lcsb.mapviewer.model.map.species.Species; +import lcsb.mapviewer.model.map.species.*; import lcsb.mapviewer.model.map.species.field.Residue; import lcsb.mapviewer.persist.PersistTestFunctions; @@ -67,214 +46,173 @@ public class ModelDaoTest extends PersistTestFunctions { @Test public void testLoadFromDb() throws Exception { - try { - Model model = createModel(); - project.addModel(model); - modelDao.add(model); - projectDao.update(project); - projectDao.evict(project); - - modelDao.evict(model); - ModelData model2 = modelDao.getById(model.getId()); - assertNotNull(model2); - assertFalse(model2 == model); - - assertEquals(model.getElements().size(), model2.getElements().size()); - assertEquals(model.getLayers().size(), model2.getLayers().size()); - assertEquals(model.getReactions().size(), model2.getReactions().size()); - - ModelComparator comparator = new ModelComparator(); - assertEquals(0, comparator.compare(model, new ModelFullIndexed(model2))); - - modelDao.delete(model2); - model2 = modelDao.getById(model.getId()); - assertNull(model2); - project = projectDao.getById(project.getId()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Model model = createModel(); + project.addModel(model); + modelDao.add(model); + projectDao.update(project); + projectDao.evict(project); + + modelDao.evict(model); + ModelData model2 = modelDao.getById(model.getId()); + assertNotNull(model2); + assertFalse(model2 == model); + + assertEquals(model.getElements().size(), model2.getElements().size()); + assertEquals(model.getLayers().size(), model2.getLayers().size()); + assertEquals(model.getReactions().size(), model2.getReactions().size()); + + ModelComparator comparator = new ModelComparator(); + assertEquals(0, comparator.compare(model, new ModelFullIndexed(model2))); + + modelDao.delete(model2); + model2 = modelDao.getById(model.getId()); + assertNull(model2); + project = projectDao.getById(project.getId()); } @Test public void testModelWithAuthor() throws Exception { - try { - Model model = createModel(); - model.addAuthor(new Author("Piotr", "G")); - project.addModel(model); - modelDao.add(model); - projectDao.update(project); - projectDao.evict(project); - - modelDao.evict(model); - ModelData model2 = modelDao.getById(model.getId()); + Model model = createModel(); + model.addAuthor(new Author("Piotr", "G")); + project.addModel(model); + modelDao.add(model); + projectDao.update(project); + projectDao.evict(project); - ModelComparator comparator = new ModelComparator(); - assertEquals(0, comparator.compare(model, new ModelFullIndexed(model2))); + modelDao.evict(model); + ModelData model2 = modelDao.getById(model.getId()); - project = projectDao.getById(project.getId()); + ModelComparator comparator = new ModelComparator(); + assertEquals(0, comparator.compare(model, new ModelFullIndexed(model2))); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + project = projectDao.getById(project.getId()); } @Test public void testIndexesReload() throws Exception { - try { - Model model = createModel(); - project.addModel(model); - modelDao.add(model); - modelDao.evict(model); - ModelData model2 = modelDao.getById(model.getId()); - Model fullModel = new ModelFullIndexed(model2); - assertNotNull(model2); - - assertEquals(model.getElements().size(), model2.getElements().size()); - assertEquals(model.getLayers().size(), model2.getLayers().size()); - assertEquals(model.getReactions().size(), model2.getReactions().size()); - - // check if we really performed a test - boolean test = false; - - for (Element alias : model.getElements()) { + Model model = createModel(); + project.addModel(model); + modelDao.add(model); + modelDao.evict(model); + ModelData model2 = modelDao.getById(model.getId()); + Model fullModel = new ModelFullIndexed(model2); + assertNotNull(model2); + + assertEquals(model.getElements().size(), model2.getElements().size()); + assertEquals(model.getLayers().size(), model2.getLayers().size()); + assertEquals(model.getReactions().size(), model2.getReactions().size()); + + // check if we really performed a test + boolean test = false; + + for (Element alias : model.getElements()) { + assertNotNull(fullModel.getElementByElementId(alias.getElementId())); + test = true; + } + assertTrue(test); + + test = false; + for (Element alias : model.getElements()) { + if (alias instanceof Compartment) { assertNotNull(fullModel.getElementByElementId(alias.getElementId())); test = true; } - assertTrue(test); - - test = false; - for (Element alias : model.getElements()) { - if (alias instanceof Compartment) { - assertNotNull(fullModel.getElementByElementId(alias.getElementId())); - test = true; - } - } - assertTrue(test); - - model2.setHeight(32); - modelDao.update(model2.getModel()); + } + assertTrue(test); - modelDao.delete(model2); - model2 = modelDao.getById(model.getId()); - assertNull(model2); + model2.setHeight(32); + modelDao.update(model2.getModel()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + modelDao.delete(model2); + model2 = modelDao.getById(model.getId()); + assertNull(model2); } @Test public void testReactionInModelAfterReload() throws Exception { - try { - Model model = createModel(); - Reaction reaction = model.getReactions().iterator().next(); - project.addModel(model); - modelDao.add(model); - projectDao.update(project); - projectDao.evict(project); - modelDao.evict(model); - ModelData model2 = modelDao.getById(model.getId()); - - Reaction reaction2 = null; - for (Reaction r : model2.getReactions()) { - if (r.getIdReaction().equals(reaction.getIdReaction())) { - reaction2 = r; - } + Model model = createModel(); + Reaction reaction = model.getReactions().iterator().next(); + project.addModel(model); + modelDao.add(model); + projectDao.update(project); + projectDao.evict(project); + modelDao.evict(model); + ModelData model2 = modelDao.getById(model.getId()); + + Reaction reaction2 = null; + for (Reaction r : model2.getReactions()) { + if (r.getIdReaction().equals(reaction.getIdReaction())) { + reaction2 = r; } - assertNotNull(reaction2); - assertFalse(reaction.equals(reaction2)); - - assertEquals(reaction.getNodes().size(), reaction2.getNodes().size()); + } + assertNotNull(reaction2); + assertFalse(reaction.equals(reaction2)); - modelDao.delete(model2); - model2 = modelDao.getById(model.getId()); - assertNull(model2); - project = projectDao.getById(project.getId()); + assertEquals(reaction.getNodes().size(), reaction2.getNodes().size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + modelDao.delete(model2); + model2 = modelDao.getById(model.getId()); + assertNull(model2); + project = projectDao.getById(project.getId()); } @Test public void testReactionInWithKinetics() throws Exception { - try { - Model model = createModel(); - Reaction reaction = model.getReactions().iterator().next(); - SbmlKinetics kinetics = new SbmlKinetics(); - kinetics.addElement(reaction.getReactants().get(0).getElement()); - kinetics.addFunction(createFunction()); - model.addFunctions(kinetics.getFunctions()); - kinetics.addParameter(createParameter()); - model.addUnit(kinetics.getParameters().iterator().next().getUnits()); - reaction.setKinetics(kinetics); - project.addModel(model); - modelDao.add(model); - projectDao.update(project); - projectDao.evict(project); - modelDao.evict(model); - ModelData model2 = modelDao.getById(model.getId()); - - assertEquals(0, modelComparator.compare(model, new ModelFullIndexed(model2))); - - project = projectDao.getById(project.getId()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Model model = createModel(); + Reaction reaction = model.getReactions().iterator().next(); + SbmlKinetics kinetics = new SbmlKinetics(); + kinetics.addElement(reaction.getReactants().get(0).getElement()); + kinetics.addFunction(createFunction()); + model.addFunctions(kinetics.getFunctions()); + kinetics.addParameter(createParameter()); + model.addUnit(kinetics.getParameters().iterator().next().getUnits()); + reaction.setKinetics(kinetics); + project.addModel(model); + modelDao.add(model); + projectDao.update(project); + projectDao.evict(project); + modelDao.evict(model); + ModelData model2 = modelDao.getById(model.getId()); + + assertEquals(0, modelComparator.compare(model, new ModelFullIndexed(model2))); + + project = projectDao.getById(project.getId()); } @Test public void testModulationReaction() throws Exception { - try { - Model model = createModel(); - ModulationReaction reaction = createModulationReaction(model.getElementByElementId("sa1117"), model.getElementByElementId("sa2")); - model.addReaction(reaction); - - project.addModel(model); - modelDao.add(model); - projectDao.update(project); - projectDao.evict(project); - modelDao.evict(model); - ModelData model2 = modelDao.getById(model.getId()); + Model model = createModel(); + ModulationReaction reaction = createModulationReaction(model.getElementByElementId("sa1117"), + model.getElementByElementId("sa2")); + model.addReaction(reaction); - assertEquals(0, modelComparator.compare(model, new ModelFullIndexed(model2))); + project.addModel(model); + modelDao.add(model); + projectDao.update(project); + projectDao.evict(project); + modelDao.evict(model); + ModelData model2 = modelDao.getById(model.getId()); - project = projectDao.getById(project.getId()); + assertEquals(0, modelComparator.compare(model, new ModelFullIndexed(model2))); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + project = projectDao.getById(project.getId()); } @Test public void testModelWithParameters() throws Exception { - try { - Model model = createModel(); - model.addParameter(createParameter()); - model.addUnit(model.getParameters().iterator().next().getUnits()); - project.addModel(model); - modelDao.add(model); - projectDao.update(project); - projectDao.evict(project); - modelDao.evict(model); - ModelData model2 = modelDao.getById(model.getId()); - - assertEquals(0, modelComparator.compare(model, new ModelFullIndexed(model2))); - - project = projectDao.getById(project.getId()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Model model = createModel(); + model.addParameter(createParameter()); + model.addUnit(model.getParameters().iterator().next().getUnits()); + project.addModel(model); + modelDao.add(model); + projectDao.update(project); + projectDao.evict(project); + modelDao.evict(model); + ModelData model2 = modelDao.getById(model.getId()); + + assertEquals(0, modelComparator.compare(model, new ModelFullIndexed(model2))); + + project = projectDao.getById(project.getId()); } private SbmlParameter createParameter() { @@ -302,33 +240,27 @@ public class ModelDaoTest extends PersistTestFunctions { @Test public void testGetLastModelForProjectName() throws Exception { - try { - ModelData model3 = modelDao.getLastModelForProjectIdentifier(projectId, false); - assertNull(model3); - - Model model = createModel(); - project.addModel(model); - modelDao.add(model); + ModelData model3 = modelDao.getLastModelForProjectIdentifier(projectId, false); + assertNull(model3); - ModelData newModel = modelDao.getLastModelForProjectIdentifier(projectId, false); - assertNotNull(newModel); - assertEquals(model.getId(), newModel.getId()); + Model model = createModel(); + project.addModel(model); + modelDao.add(model); - Model model2 = createModel(); - project.addModel(model2); - modelDao.add(model2); + ModelData newModel = modelDao.getLastModelForProjectIdentifier(projectId, false); + assertNotNull(newModel); + assertEquals(model.getId(), newModel.getId()); - newModel = modelDao.getLastModelForProjectIdentifier(projectId, false); - assertNotNull(newModel); - assertEquals(model2.getId(), newModel.getId()); + Model model2 = createModel(); + project.addModel(model2); + modelDao.add(model2); - modelDao.delete(model2); - modelDao.delete(model); + newModel = modelDao.getLastModelForProjectIdentifier(projectId, false); + assertNotNull(newModel); + assertEquals(model2.getId(), newModel.getId()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + modelDao.delete(model2); + modelDao.delete(model); } /** @@ -338,28 +270,23 @@ public class ModelDaoTest extends PersistTestFunctions { */ @Test public void testModificationsInProteins() throws Exception { - try { - Model model = createModel(); - Project project = new Project("test_project_id"); - project.addModel(model); - projectDao.add(project); + Model model = createModel(); + Project project = new Project("test_project_id"); + project.addModel(model); + projectDao.add(project); - modelDao.evict(model); - projectDao.evict(project); - Model model2 = new ModelFullIndexed(modelDao.getById(model.getId())); + modelDao.evict(model); + projectDao.evict(project); + Model model2 = new ModelFullIndexed(modelDao.getById(model.getId())); - Protein originalSpecies = (Protein) model.getElementByElementId("pr1"); - Protein fromDbSpecies = (Protein) model2.getElementByElementId("pr1"); + Protein originalSpecies = (Protein) model.getElementByElementId("pr1"); + Protein fromDbSpecies = (Protein) model2.getElementByElementId("pr1"); - assertFalse(originalSpecies.equals(fromDbSpecies)); - assertEquals(originalSpecies.getModificationResidues().size(), fromDbSpecies.getModificationResidues().size()); + assertFalse(originalSpecies.equals(fromDbSpecies)); + assertEquals(originalSpecies.getModificationResidues().size(), fromDbSpecies.getModificationResidues().size()); - project = projectDao.getById(project.getId()); - projectDao.delete(project); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + project = projectDao.getById(project.getId()); + projectDao.delete(project); } /** @@ -369,28 +296,23 @@ public class ModelDaoTest extends PersistTestFunctions { */ @Test public void testMiriamInSpecies() throws Exception { - try { - Model model = createModel(); - Project project = new Project("test_project_id"); - project.addModel(model); - projectDao.add(project); + Model model = createModel(); + Project project = new Project("test_project_id"); + project.addModel(model); + projectDao.add(project); - modelDao.evict(model); - projectDao.evict(project); - Model model2 = new ModelFullIndexed(modelDao.getById(model.getId())); + modelDao.evict(model); + projectDao.evict(project); + Model model2 = new ModelFullIndexed(modelDao.getById(model.getId())); - Protein originalSpecies = (Protein) model.getElementByElementId("pr1"); - Protein fromDbSpecies = (Protein) model2.getElementByElementId("pr1"); + Protein originalSpecies = (Protein) model.getElementByElementId("pr1"); + Protein fromDbSpecies = (Protein) model2.getElementByElementId("pr1"); - assertFalse(originalSpecies.equals(fromDbSpecies)); - assertEquals(originalSpecies.getMiriamData().size(), fromDbSpecies.getMiriamData().size()); + assertFalse(originalSpecies.equals(fromDbSpecies)); + assertEquals(originalSpecies.getMiriamData().size(), fromDbSpecies.getMiriamData().size()); - project = projectDao.getById(project.getId()); - projectDao.delete(project); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + project = projectDao.getById(project.getId()); + projectDao.delete(project); } private Model createModel() { diff --git a/persist/src/test/java/lcsb/mapviewer/persist/dao/map/layout/ReferenceGenomeDaoTest.java b/persist/src/test/java/lcsb/mapviewer/persist/dao/map/layout/ReferenceGenomeDaoTest.java index 8dae9dbe895a8a5e0b7a58962912533c12313fb1..1145263d3c6fdafde0e66884c4eaa4b01bbd4bf4 100644 --- a/persist/src/test/java/lcsb/mapviewer/persist/dao/map/layout/ReferenceGenomeDaoTest.java +++ b/persist/src/test/java/lcsb/mapviewer/persist/dao/map/layout/ReferenceGenomeDaoTest.java @@ -1,10 +1,8 @@ package lcsb.mapviewer.persist.dao.map.layout; -import static org.junit.Assert.assertEquals; +import static org.junit.Assert.*; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.springframework.beans.factory.annotation.Autowired; import lcsb.mapviewer.model.map.MiriamData; @@ -15,57 +13,49 @@ import lcsb.mapviewer.persist.PersistTestFunctions; public class ReferenceGenomeDaoTest extends PersistTestFunctions { - @Autowired - ReferenceGenomeDao referenceGenomeDao; - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void test() { - try { - ReferenceGenome genome = new ReferenceGenome(); - genome.setOrganism(new MiriamData(MiriamType.TAXONOMY, "9606")); - genome.setType(ReferenceGenomeType.UCSC); - genome.setVersion("x"); - long count = referenceGenomeDao.getCount(); - referenceGenomeDao.add(genome); - long count2 = referenceGenomeDao.getCount(); - referenceGenomeDao.delete(genome); - long count3 = referenceGenomeDao.getCount(); - - assertEquals(count + 1, count2); - assertEquals(count, count3); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testGetByType() { - try { - ReferenceGenome genome = new ReferenceGenome(); - genome.setOrganism(new MiriamData(MiriamType.TAXONOMY, "111111")); - genome.setType(ReferenceGenomeType.UCSC); - genome.setVersion("unknown"); - long count = referenceGenomeDao.getByType(ReferenceGenomeType.UCSC).size(); - referenceGenomeDao.add(genome); - long count2 = referenceGenomeDao.getByType(ReferenceGenomeType.UCSC).size();; - referenceGenomeDao.delete(genome); - long count3 = referenceGenomeDao.getByType(ReferenceGenomeType.UCSC).size();; - - assertEquals(count + 1, count2); - assertEquals(count, count3); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } + @Autowired + ReferenceGenomeDao referenceGenomeDao; + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void test() { + ReferenceGenome genome = new ReferenceGenome(); + genome.setOrganism(new MiriamData(MiriamType.TAXONOMY, "9606")); + genome.setType(ReferenceGenomeType.UCSC); + genome.setVersion("x"); + long count = referenceGenomeDao.getCount(); + referenceGenomeDao.add(genome); + long count2 = referenceGenomeDao.getCount(); + referenceGenomeDao.delete(genome); + long count3 = referenceGenomeDao.getCount(); + + assertEquals(count + 1, count2); + assertEquals(count, count3); + } + + @Test + public void testGetByType() { + ReferenceGenome genome = new ReferenceGenome(); + genome.setOrganism(new MiriamData(MiriamType.TAXONOMY, "111111")); + genome.setType(ReferenceGenomeType.UCSC); + genome.setVersion("unknown"); + long count = referenceGenomeDao.getByType(ReferenceGenomeType.UCSC).size(); + referenceGenomeDao.add(genome); + long count2 = referenceGenomeDao.getByType(ReferenceGenomeType.UCSC).size(); + ; + referenceGenomeDao.delete(genome); + long count3 = referenceGenomeDao.getByType(ReferenceGenomeType.UCSC).size(); + ; + + assertEquals(count + 1, count2); + assertEquals(count, count3); + } } diff --git a/persist/src/test/java/lcsb/mapviewer/persist/dao/map/layout/ReferenceGenomeGeneMappingDaoTest.java b/persist/src/test/java/lcsb/mapviewer/persist/dao/map/layout/ReferenceGenomeGeneMappingDaoTest.java index 89cbff108ff22ccd21e5368494feae02669059b7..fb301563a677843280e2962a49d9cd43e70ee405 100644 --- a/persist/src/test/java/lcsb/mapviewer/persist/dao/map/layout/ReferenceGenomeGeneMappingDaoTest.java +++ b/persist/src/test/java/lcsb/mapviewer/persist/dao/map/layout/ReferenceGenomeGeneMappingDaoTest.java @@ -1,62 +1,53 @@ package lcsb.mapviewer.persist.dao.map.layout; -import static org.junit.Assert.assertEquals; +import static org.junit.Assert.*; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.springframework.beans.factory.annotation.Autowired; import lcsb.mapviewer.model.map.MiriamData; import lcsb.mapviewer.model.map.MiriamType; -import lcsb.mapviewer.model.map.layout.ReferenceGenome; -import lcsb.mapviewer.model.map.layout.ReferenceGenomeGeneMapping; -import lcsb.mapviewer.model.map.layout.ReferenceGenomeType; +import lcsb.mapviewer.model.map.layout.*; import lcsb.mapviewer.persist.PersistTestFunctions; public class ReferenceGenomeGeneMappingDaoTest extends PersistTestFunctions { - @Autowired - ReferenceGenomeGeneMappingDao referenceGenomeGeneMappingDao; - - @Autowired - ReferenceGenomeDao referenceGenomeDao; - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void test() { - try { - ReferenceGenome genome = new ReferenceGenome(); - genome.setOrganism(new MiriamData(MiriamType.TAXONOMY, "9606")); - genome.setType(ReferenceGenomeType.UCSC); - genome.setVersion("x"); - referenceGenomeDao.add(genome); - - ReferenceGenomeGeneMapping mapping = new ReferenceGenomeGeneMapping(); - mapping.setName("Xxx"); - mapping.setReferenceGenome(genome); - mapping.setSourceUrl("http://xxx.xx/"); - long count = referenceGenomeGeneMappingDao.getCount(); - referenceGenomeGeneMappingDao.add(mapping); - long count2 = referenceGenomeGeneMappingDao.getCount(); - referenceGenomeGeneMappingDao.delete(mapping); - long count3 = referenceGenomeGeneMappingDao.getCount(); - - referenceGenomeDao.delete(genome); - - assertEquals(count + 1, count2); - assertEquals(count, count3); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } + @Autowired + ReferenceGenomeGeneMappingDao referenceGenomeGeneMappingDao; + + @Autowired + ReferenceGenomeDao referenceGenomeDao; + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void test() { + ReferenceGenome genome = new ReferenceGenome(); + genome.setOrganism(new MiriamData(MiriamType.TAXONOMY, "9606")); + genome.setType(ReferenceGenomeType.UCSC); + genome.setVersion("x"); + referenceGenomeDao.add(genome); + + ReferenceGenomeGeneMapping mapping = new ReferenceGenomeGeneMapping(); + mapping.setName("Xxx"); + mapping.setReferenceGenome(genome); + mapping.setSourceUrl("http://xxx.xx/"); + long count = referenceGenomeGeneMappingDao.getCount(); + referenceGenomeGeneMappingDao.add(mapping); + long count2 = referenceGenomeGeneMappingDao.getCount(); + referenceGenomeGeneMappingDao.delete(mapping); + long count3 = referenceGenomeGeneMappingDao.getCount(); + + referenceGenomeDao.delete(genome); + + assertEquals(count + 1, count2); + assertEquals(count, count3); + } } diff --git a/persist/src/test/java/lcsb/mapviewer/persist/dao/map/layout/alias/AntisenseRnaTest.java b/persist/src/test/java/lcsb/mapviewer/persist/dao/map/layout/alias/AntisenseRnaTest.java index f0096217721090f9e438569c0a7635c61e7e723c..7fdd16735ad8982da8b6518c4cf0bfd0c2bde04d 100644 --- a/persist/src/test/java/lcsb/mapviewer/persist/dao/map/layout/alias/AntisenseRnaTest.java +++ b/persist/src/test/java/lcsb/mapviewer/persist/dao/map/layout/alias/AntisenseRnaTest.java @@ -1,13 +1,10 @@ package lcsb.mapviewer.persist.dao.map.layout.alias; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; - -import org.apache.logging.log4j.*; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import static org.junit.Assert.*; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.junit.*; import org.springframework.test.annotation.Rollback; import lcsb.mapviewer.model.Project; @@ -39,36 +36,31 @@ public class AntisenseRnaTest extends PersistTestFunctions { @Test public void testAntisenseRnaRegionInDb() throws Exception { - try { - Project project = new Project(); - project.setProjectId(projectId); + Project project = new Project(); + project.setProjectId(projectId); - Model model = createModel(); + Model model = createModel(); - project.addModel(model); - projectDao.add(project); - projectDao.evict(project); + project.addModel(model); + projectDao.add(project); + projectDao.evict(project); - Project project2 = projectDao.getProjectByProjectId(projectId); - assertNotNull(project2); - assertFalse(project2.equals(project)); - assertEquals(project.getId(), project2.getId()); + Project project2 = projectDao.getProjectByProjectId(projectId); + assertNotNull(project2); + assertFalse(project2.equals(project)); + assertEquals(project.getId(), project2.getId()); - Model model2 = new ModelFullIndexed(project2.getModels().iterator().next()); + Model model2 = new ModelFullIndexed(project2.getModels().iterator().next()); - Element sp = model.getElements().iterator().next(); - AntisenseRna ar = (AntisenseRna) sp; + Element sp = model.getElements().iterator().next(); + AntisenseRna ar = (AntisenseRna) sp; - Element sp2 = model2.getElements().iterator().next(); - AntisenseRna ar2 = (AntisenseRna) sp2; + Element sp2 = model2.getElements().iterator().next(); + AntisenseRna ar2 = (AntisenseRna) sp2; - projectDao.delete(project2); + projectDao.delete(project2); - assertEquals(ar.getRegions().size(), ar2.getRegions().size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(ar.getRegions().size(), ar2.getRegions().size()); } private Model createModel() { diff --git a/persist/src/test/java/lcsb/mapviewer/persist/dao/map/layout/alias/ElementDaoTest.java b/persist/src/test/java/lcsb/mapviewer/persist/dao/map/layout/alias/ElementDaoTest.java index a707fe25108c75f9a73aaa3241c71023a2d172a2..447421cdd11c864917e0d615ee72c495a44fefb5 100644 --- a/persist/src/test/java/lcsb/mapviewer/persist/dao/map/layout/alias/ElementDaoTest.java +++ b/persist/src/test/java/lcsb/mapviewer/persist/dao/map/layout/alias/ElementDaoTest.java @@ -1,8 +1,6 @@ package lcsb.mapviewer.persist.dao.map.layout.alias; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +import static org.junit.Assert.*; import java.awt.geom.Point2D; import java.util.ArrayList; @@ -10,36 +8,15 @@ import java.util.List; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.springframework.beans.factory.annotation.Autowired; import lcsb.mapviewer.model.Project; -import lcsb.mapviewer.model.map.MiriamData; -import lcsb.mapviewer.model.map.MiriamRelationType; -import lcsb.mapviewer.model.map.MiriamType; -import lcsb.mapviewer.model.map.SearchIndex; +import lcsb.mapviewer.model.map.*; import lcsb.mapviewer.model.map.compartment.Compartment; -import lcsb.mapviewer.model.map.model.ElementSubmodelConnection; -import lcsb.mapviewer.model.map.model.Model; -import lcsb.mapviewer.model.map.model.ModelFullIndexed; -import lcsb.mapviewer.model.map.model.SubmodelType; -import lcsb.mapviewer.model.map.species.AntisenseRna; -import lcsb.mapviewer.model.map.species.Chemical; -import lcsb.mapviewer.model.map.species.Complex; -import lcsb.mapviewer.model.map.species.Element; -import lcsb.mapviewer.model.map.species.GenericProtein; -import lcsb.mapviewer.model.map.species.Ion; -import lcsb.mapviewer.model.map.species.Phenotype; -import lcsb.mapviewer.model.map.species.Protein; -import lcsb.mapviewer.model.map.species.Rna; -import lcsb.mapviewer.model.map.species.Species; -import lcsb.mapviewer.model.map.species.field.ModificationSite; -import lcsb.mapviewer.model.map.species.field.ModificationState; -import lcsb.mapviewer.model.map.species.field.Residue; -import lcsb.mapviewer.model.map.species.field.Structure; -import lcsb.mapviewer.model.map.species.field.UniprotRecord; +import lcsb.mapviewer.model.map.model.*; +import lcsb.mapviewer.model.map.species.*; +import lcsb.mapviewer.model.map.species.field.*; import lcsb.mapviewer.persist.PersistTestFunctions; import lcsb.mapviewer.persist.dao.map.species.ElementDao; @@ -79,27 +56,22 @@ public class ElementDaoTest extends PersistTestFunctions { @Test public void anotherSaveDaoTest() throws Exception { - try { - Model model = createModel(); - project.addModel(model); + Model model = createModel(); + project.addModel(model); - Element element = model.getElementByElementId("sa2"); + Element element = model.getElementByElementId("sa2"); - element.getSearchIndexes().add(new SearchIndex("blabla")); + element.getSearchIndexes().add(new SearchIndex("blabla")); - modelDao.add(model); + modelDao.add(model); - Model model2 = new ModelFullIndexed(modelDao.getById(model.getId())); + Model model2 = new ModelFullIndexed(modelDao.getById(model.getId())); - Element element2 = elementDao.getById(model2.getElementByElementId("sa2").getId()); + Element element2 = elementDao.getById(model2.getElementByElementId("sa2").getId()); - assertEquals(1, element2.getSearchIndexes().size()); + assertEquals(1, element2.getSearchIndexes().size()); - modelDao.delete(model); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + modelDao.delete(model); } private Model createModel() { @@ -129,302 +101,247 @@ public class ElementDaoTest extends PersistTestFunctions { @Test public void saveAliasWithSubmodelTest() throws Exception { - try { - long count = modelDao.getCount(); - Model model = createModel(); - Model model1 = createModel(); - Element element = model.getElementByElementId("sa2"); - ElementSubmodelConnection submodel = new ElementSubmodelConnection(model1, SubmodelType.UNKNOWN); - element.setSubmodel(submodel); - project.addModel(model); - - projectDao.add(project); - projectDao.flush(); - - long count2 = modelDao.getCount(); - assertEquals(count + 2, count2); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + long count = modelDao.getCount(); + Model model = createModel(); + Model model1 = createModel(); + Element element = model.getElementByElementId("sa2"); + ElementSubmodelConnection submodel = new ElementSubmodelConnection(model1, SubmodelType.UNKNOWN); + element.setSubmodel(submodel); + project.addModel(model); + + projectDao.add(project); + projectDao.flush(); + + long count2 = modelDao.getCount(); + assertEquals(count + 2, count2); } @Test public void saveWithUniprotData() throws Exception { - try { - Model model = createModel(); - project.addModel(model); - - Species element = model.getElementByElementId("sa2"); - UniprotRecord uniprotRecord = new UniprotRecord(); - Structure s = new Structure(); - s.setPdbId("x"); - s.setChainId("y"); - List<Structure> list = new ArrayList<>(); - list.add(s); - s.setUniprot(uniprotRecord); - uniprotRecord.addStructures(list); - uniprotRecord.setSpecies(element); - element.getUniprots().add(uniprotRecord); - - modelDao.add(model); - modelDao.delete(model); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Model model = createModel(); + project.addModel(model); + + Species element = model.getElementByElementId("sa2"); + UniprotRecord uniprotRecord = new UniprotRecord(); + Structure s = new Structure(); + s.setPdbId("x"); + s.setChainId("y"); + List<Structure> list = new ArrayList<>(); + list.add(s); + s.setUniprot(uniprotRecord); + uniprotRecord.addStructures(list); + uniprotRecord.setSpecies(element); + element.getUniprots().add(uniprotRecord); + + modelDao.add(model); + modelDao.delete(model); } @Test public void testAdd() throws Exception { - try { - - GenericProtein sp = createProtein(testIdAlias); - sp.setCharge(testChargeVal); - sp.setInitialAmount(testInitialAmount); - sp.setInitialConcentration(testInitialConcentration); - sp.setName(testName); - sp.setNotes(testNotes); - sp.setOnlySubstanceUnits(testOnlySubstanceunits); - - Compartment parent = createCompartment("comp id"); - sp.setCompartment(parent); - - MiriamData md = new MiriamData(MiriamRelationType.BQ_BIOL_IS_DESCRIBED_BY, MiriamType.UNKNOWN, "c"); - sp.addMiriamData(md); - - elementDao.add(sp); - - Species sp2 = (Species) elementDao.getById(sp.getId()); - assertNotNull(sp2); - assertEquals(sp.getCharge(), sp2.getCharge()); - assertEquals(sp.getElementId(), sp2.getElementId()); - assertEquals(sp.getInitialAmount(), sp2.getInitialAmount()); - assertEquals(sp.getInitialConcentration(), sp2.getInitialConcentration()); - assertEquals(sp.getName(), sp2.getName()); - assertEquals(sp.getNotes(), sp2.getNotes()); - assertEquals(sp.hasOnlySubstanceUnits(), sp2.hasOnlySubstanceUnits()); - - Compartment parent2 = sp2.getCompartment(); - assertNotNull(parent2); - assertEquals("comp id", parent2.getElementId()); - - assertNotNull(sp2.getMiriamData()); - - MiriamData md2 = sp2.getMiriamData().iterator().next(); - assertNotNull(md2); - assertEquals(md.getDataType(), md2.getDataType()); - assertEquals(md.getRelationType(), md2.getRelationType()); - assertEquals(md.getResource(), md2.getResource()); - - elementDao.delete(sp); - sp2 = (Species) elementDao.getById(sp.getId()); - assertNull(sp2); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + GenericProtein sp = createProtein(testIdAlias); + sp.setCharge(testChargeVal); + sp.setInitialAmount(testInitialAmount); + sp.setInitialConcentration(testInitialConcentration); + sp.setName(testName); + sp.setNotes(testNotes); + sp.setOnlySubstanceUnits(testOnlySubstanceunits); + + Compartment parent = createCompartment("comp id"); + sp.setCompartment(parent); + + MiriamData md = new MiriamData(MiriamRelationType.BQ_BIOL_IS_DESCRIBED_BY, MiriamType.UNKNOWN, "c"); + sp.addMiriamData(md); + + elementDao.add(sp); + + Species sp2 = (Species) elementDao.getById(sp.getId()); + assertNotNull(sp2); + assertEquals(sp.getCharge(), sp2.getCharge()); + assertEquals(sp.getElementId(), sp2.getElementId()); + assertEquals(sp.getInitialAmount(), sp2.getInitialAmount()); + assertEquals(sp.getInitialConcentration(), sp2.getInitialConcentration()); + assertEquals(sp.getName(), sp2.getName()); + assertEquals(sp.getNotes(), sp2.getNotes()); + assertEquals(sp.hasOnlySubstanceUnits(), sp2.hasOnlySubstanceUnits()); + + Compartment parent2 = sp2.getCompartment(); + assertNotNull(parent2); + assertEquals("comp id", parent2.getElementId()); + + assertNotNull(sp2.getMiriamData()); + + MiriamData md2 = sp2.getMiriamData().iterator().next(); + assertNotNull(md2); + assertEquals(md.getDataType(), md2.getDataType()); + assertEquals(md.getRelationType(), md2.getRelationType()); + assertEquals(md.getResource(), md2.getResource()); + + elementDao.delete(sp); + sp2 = (Species) elementDao.getById(sp.getId()); + assertNull(sp2); } @Test public void testProtein() throws Exception { - try { - - Protein protein = createProtein(testIdAlias); - Residue mr = new Residue(); - mr.setPosition(new Point2D.Double(10, 20)); - mr.setName("name"); - mr.setState(ModificationState.GLYCOSYLATED); - protein.addResidue(mr); - - elementDao.add(protein); - - Protein sp2 = (Protein) elementDao.getById(protein.getId()); - assertNotNull(sp2); - assertEquals(protein.getElementId(), sp2.getElementId()); - - assertNotNull(sp2.getModificationResidues()); - assertEquals(1, sp2.getModificationResidues().size()); - - Residue copy = (Residue) sp2.getModificationResidues().get(0); - assertEquals(copy.getPosition(), mr.getPosition()); - assertEquals(copy.getIdModificationResidue(), mr.getIdModificationResidue()); - assertEquals(copy.getName(), mr.getName()); - assertEquals(copy.getState(), mr.getState()); - - elementDao.delete(sp2); - sp2 = (Protein) elementDao.getById(protein.getId()); - assertNull(sp2); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Protein protein = createProtein(testIdAlias); + Residue mr = new Residue(); + mr.setPosition(new Point2D.Double(10, 20)); + mr.setName("name"); + mr.setState(ModificationState.GLYCOSYLATED); + protein.addResidue(mr); + + elementDao.add(protein); + + Protein sp2 = (Protein) elementDao.getById(protein.getId()); + assertNotNull(sp2); + assertEquals(protein.getElementId(), sp2.getElementId()); + + assertNotNull(sp2.getModificationResidues()); + assertEquals(1, sp2.getModificationResidues().size()); + + Residue copy = (Residue) sp2.getModificationResidues().get(0); + assertEquals(copy.getPosition(), mr.getPosition()); + assertEquals(copy.getIdModificationResidue(), mr.getIdModificationResidue()); + assertEquals(copy.getName(), mr.getName()); + assertEquals(copy.getState(), mr.getState()); + + elementDao.delete(sp2); + sp2 = (Protein) elementDao.getById(protein.getId()); + assertNull(sp2); } @Test public void testRna() throws Exception { - try { - Rna sp = createRna(testIdAlias); - ModificationSite mr = new ModificationSite(); - mr.setName("name"); - mr.setState(ModificationState.DONT_CARE); - sp.addModificationSite(mr); - - elementDao.add(sp); - elementDao.evict(sp); - - Rna sp2 = (Rna) elementDao.getById(sp.getId()); - assertNotNull(sp2); - assertEquals(sp.getElementId(), sp2.getElementId()); - - assertNotNull(sp2.getRegions()); - assertEquals(1, sp2.getRegions().size()); - - ModificationSite copy = (ModificationSite) sp2.getRegions().get(0); - assertEquals(copy.getId(), mr.getId()); - assertEquals(copy.getName(), mr.getName()); - assertEquals(copy.getState(), mr.getState()); - - elementDao.delete(sp2); - sp2 = (Rna) elementDao.getById(sp.getId()); - assertNull(sp2); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Rna sp = createRna(testIdAlias); + ModificationSite mr = new ModificationSite(); + mr.setName("name"); + mr.setState(ModificationState.DONT_CARE); + sp.addModificationSite(mr); + + elementDao.add(sp); + elementDao.evict(sp); + + Rna sp2 = (Rna) elementDao.getById(sp.getId()); + assertNotNull(sp2); + assertEquals(sp.getElementId(), sp2.getElementId()); + + assertNotNull(sp2.getRegions()); + assertEquals(1, sp2.getRegions().size()); + + ModificationSite copy = (ModificationSite) sp2.getRegions().get(0); + assertEquals(copy.getId(), mr.getId()); + assertEquals(copy.getName(), mr.getName()); + assertEquals(copy.getState(), mr.getState()); + + elementDao.delete(sp2); + sp2 = (Rna) elementDao.getById(sp.getId()); + assertNull(sp2); } @Test public void testAntisenseRna() throws Exception { - try { - - AntisenseRna sp = createAntisenseRna(testIdAlias); - - ModificationSite mr = new ModificationSite(); - mr.setName("name"); - sp.addModificationSite(mr); + AntisenseRna sp = createAntisenseRna(testIdAlias); - elementDao.add(sp); - elementDao.evict(sp); + ModificationSite mr = new ModificationSite(); + mr.setName("name"); + sp.addModificationSite(mr); - AntisenseRna sp2 = (AntisenseRna) elementDao.getById(sp.getId()); - assertNotNull(sp2); - assertEquals(sp.getElementId(), sp2.getElementId()); + elementDao.add(sp); + elementDao.evict(sp); - assertNotNull(sp2.getRegions()); - assertEquals(1, sp2.getRegions().size()); + AntisenseRna sp2 = (AntisenseRna) elementDao.getById(sp.getId()); + assertNotNull(sp2); + assertEquals(sp.getElementId(), sp2.getElementId()); - assertEquals(sp2.getRegions().get(0).getIdModificationResidue(), mr.getIdModificationResidue()); - assertEquals(sp2.getRegions().get(0).getName(), mr.getName()); + assertNotNull(sp2.getRegions()); + assertEquals(1, sp2.getRegions().size()); - elementDao.delete(sp2); - sp2 = (AntisenseRna) elementDao.getById(sp.getId()); - assertNull(sp2); + assertEquals(sp2.getRegions().get(0).getIdModificationResidue(), mr.getIdModificationResidue()); + assertEquals(sp2.getRegions().get(0).getName(), mr.getName()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + elementDao.delete(sp2); + sp2 = (AntisenseRna) elementDao.getById(sp.getId()); + assertNull(sp2); } @Test public void testSynonymsInAlias() throws Exception { - try { - Protein protein = createProtein(testIdAlias); - protein.addSynonym("Synonym"); - protein.addSynonym("Synonym A"); - protein.addSynonym("A"); - - protein.addFormerSymbol("Sym"); - protein.addFormerSymbol("Sym A"); - protein.addFormerSymbol("DD"); - - elementDao.add(protein); - elementDao.flush(); + Protein protein = createProtein(testIdAlias); + protein.addSynonym("Synonym"); + protein.addSynonym("Synonym A"); + protein.addSynonym("A"); - elementDao.evict(protein); - Protein sp2 = (Protein) elementDao.getById(protein.getId()); + protein.addFormerSymbol("Sym"); + protein.addFormerSymbol("Sym A"); + protein.addFormerSymbol("DD"); - assertNotNull(sp2.getSynonyms()); - assertEquals(protein.getSynonyms().size(), sp2.getSynonyms().size()); + elementDao.add(protein); + elementDao.flush(); - for (int i = 0; i < protein.getSynonyms().size(); i++) { - assertEquals(protein.getSynonyms().get(i), sp2.getSynonyms().get(i)); - } + elementDao.evict(protein); + Protein sp2 = (Protein) elementDao.getById(protein.getId()); - assertNotNull(sp2.getFormerSymbols()); - assertEquals(protein.getFormerSymbols().size(), sp2.getFormerSymbols().size()); + assertNotNull(sp2.getSynonyms()); + assertEquals(protein.getSynonyms().size(), sp2.getSynonyms().size()); - for (int i = 0; i < protein.getFormerSymbols().size(); i++) { - assertEquals(protein.getFormerSymbols().get(i), sp2.getFormerSymbols().get(i)); - } + for (int i = 0; i < protein.getSynonyms().size(); i++) { + assertEquals(protein.getSynonyms().get(i), sp2.getSynonyms().get(i)); + } - elementDao.delete(sp2); - sp2 = (Protein) elementDao.getById(protein.getId()); - assertNull(sp2); + assertNotNull(sp2.getFormerSymbols()); + assertEquals(protein.getFormerSymbols().size(), sp2.getFormerSymbols().size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; + for (int i = 0; i < protein.getFormerSymbols().size(); i++) { + assertEquals(protein.getFormerSymbols().get(i), sp2.getFormerSymbols().get(i)); } + + elementDao.delete(sp2); + sp2 = (Protein) elementDao.getById(protein.getId()); + assertNull(sp2); } @Test public void testChemicals() throws Exception { - try { - Chemical ion = createIon(testIdAlias); - ion.setInChI("come inchi"); - ion.setInChIKey("keyyy"); - ion.setSmiles("smile"); - - elementDao.add(ion); - elementDao.flush(); + Chemical ion = createIon(testIdAlias); + ion.setInChI("come inchi"); + ion.setInChIKey("keyyy"); + ion.setSmiles("smile"); - elementDao.evict(ion); - Ion sp2 = (Ion) elementDao.getById(ion.getId()); + elementDao.add(ion); + elementDao.flush(); - assertNotNull(sp2.getSynonyms()); - assertEquals(ion.getSynonyms().size(), sp2.getSynonyms().size()); + elementDao.evict(ion); + Ion sp2 = (Ion) elementDao.getById(ion.getId()); - assertEquals(ion.getSmiles(), sp2.getSmiles()); - assertEquals(ion.getInChIKey(), sp2.getInChIKey()); - assertEquals(ion.getInChI(), sp2.getInChI()); + assertNotNull(sp2.getSynonyms()); + assertEquals(ion.getSynonyms().size(), sp2.getSynonyms().size()); - elementDao.delete(sp2); - sp2 = (Ion) elementDao.getById(ion.getId()); - assertNull(sp2); + assertEquals(ion.getSmiles(), sp2.getSmiles()); + assertEquals(ion.getInChIKey(), sp2.getInChIKey()); + assertEquals(ion.getInChI(), sp2.getInChI()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + elementDao.delete(sp2); + sp2 = (Ion) elementDao.getById(ion.getId()); + assertNull(sp2); } @Test public void testPhenotype() throws Exception { - try { - Phenotype phenotype = createPhenotype(testIdAlias); - - elementDao.add(phenotype); - elementDao.flush(); + Phenotype phenotype = createPhenotype(testIdAlias); - elementDao.evict(phenotype); - Phenotype sp2 = (Phenotype) elementDao.getById(phenotype.getId()); + elementDao.add(phenotype); + elementDao.flush(); - assertNotNull(sp2.getSynonyms()); - assertEquals(phenotype.getSynonyms().size(), phenotype.getSynonyms().size()); + elementDao.evict(phenotype); + Phenotype sp2 = (Phenotype) elementDao.getById(phenotype.getId()); - elementDao.delete(sp2); - sp2 = (Phenotype) elementDao.getById(phenotype.getId()); - assertNull(sp2); + assertNotNull(sp2.getSynonyms()); + assertEquals(phenotype.getSynonyms().size(), phenotype.getSynonyms().size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + elementDao.delete(sp2); + sp2 = (Phenotype) elementDao.getById(phenotype.getId()); + assertNull(sp2); } } diff --git a/persist/src/test/java/lcsb/mapviewer/persist/dao/map/layout/alias/RnaTest.java b/persist/src/test/java/lcsb/mapviewer/persist/dao/map/layout/alias/RnaTest.java index 1b7fe00af08253541dc248baec58969df26d998a..8dfd99d80de149c4e5a01bcec0bfa5bf42cb73be 100644 --- a/persist/src/test/java/lcsb/mapviewer/persist/dao/map/layout/alias/RnaTest.java +++ b/persist/src/test/java/lcsb/mapviewer/persist/dao/map/layout/alias/RnaTest.java @@ -1,13 +1,10 @@ package lcsb.mapviewer.persist.dao.map.layout.alias; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.*; -import org.apache.logging.log4j.*; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.junit.*; import lcsb.mapviewer.model.Project; import lcsb.mapviewer.model.map.model.Model; @@ -38,36 +35,31 @@ public class RnaTest extends PersistTestFunctions { @Test public void testRnaRegionInDb() throws Exception { - try { - Project project = new Project(); - project.setProjectId(projectId); + Project project = new Project(); + project.setProjectId(projectId); - Model model = createModel(); + Model model = createModel(); - project.addModel(model); - projectDao.add(project); - projectDao.evict(project); + project.addModel(model); + projectDao.add(project); + projectDao.evict(project); - Project project2 = projectDao.getProjectByProjectId(projectId); - assertNotNull(project2); - assertFalse(project2.equals(project)); - assertEquals(project.getId(), project2.getId()); + Project project2 = projectDao.getProjectByProjectId(projectId); + assertNotNull(project2); + assertFalse(project2.equals(project)); + assertEquals(project.getId(), project2.getId()); - Model model2 = new ModelFullIndexed(project2.getModels().iterator().next()); + Model model2 = new ModelFullIndexed(project2.getModels().iterator().next()); - Element sp = model.getElements().iterator().next(); - Rna ar = (Rna) sp; + Element sp = model.getElements().iterator().next(); + Rna ar = (Rna) sp; - Element sp2 = model2.getElements().iterator().next(); - Rna ar2 = (Rna) sp2; + Element sp2 = model2.getElements().iterator().next(); + Rna ar2 = (Rna) sp2; - projectDao.delete(project2); + projectDao.delete(project2); - assertEquals(ar.getRegions().size(), ar2.getRegions().size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(ar.getRegions().size(), ar2.getRegions().size()); } private Model createModel() { diff --git a/persist/src/test/java/lcsb/mapviewer/persist/dao/map/statistics/SearchHistoryDaoTest.java b/persist/src/test/java/lcsb/mapviewer/persist/dao/map/statistics/SearchHistoryDaoTest.java index 08221a076f705b406f7e7dc8735696e4fa3f28fc..d788a1c1e38468b1d74b6f583c60473312a3d48d 100644 --- a/persist/src/test/java/lcsb/mapviewer/persist/dao/map/statistics/SearchHistoryDaoTest.java +++ b/persist/src/test/java/lcsb/mapviewer/persist/dao/map/statistics/SearchHistoryDaoTest.java @@ -1,11 +1,8 @@ package lcsb.mapviewer.persist.dao.map.statistics; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.springframework.beans.factory.annotation.Autowired; import lcsb.mapviewer.model.map.statistics.SearchHistory; @@ -27,19 +24,14 @@ public class SearchHistoryDaoTest extends PersistTestFunctions { @Test public void test() { - try { - SearchHistory searchHistory = new SearchHistory(); - long count = searchHistoryDao.getCount(); - searchHistory.setIpAddress("0.0.0.0"); - searchHistory.setQuery("query ..."); - searchHistory.setType(SearchType.GENERAL); - searchHistoryDao.add(searchHistory); - long count1 = searchHistoryDao.getCount(); - assertEquals(count + 1, count1); - } catch (Exception e) { - e.printStackTrace(); - fail("Exception occurred"); - } + SearchHistory searchHistory = new SearchHistory(); + long count = searchHistoryDao.getCount(); + searchHistory.setIpAddress("0.0.0.0"); + searchHistory.setQuery("query ..."); + searchHistory.setType(SearchType.GENERAL); + searchHistoryDao.add(searchHistory); + long count1 = searchHistoryDao.getCount(); + assertEquals(count + 1, count1); } } diff --git a/rest-api/src/main/java/lcsb/mapviewer/api/projects/comments/CommentRestImpl.java b/rest-api/src/main/java/lcsb/mapviewer/api/projects/comments/CommentRestImpl.java index 4f5a8265f1b36b96c5a1efeb8e2f38072a56ff31..5527253a14d4d328ddd33a5ac23ca4757427958a 100644 --- a/rest-api/src/main/java/lcsb/mapviewer/api/projects/comments/CommentRestImpl.java +++ b/rest-api/src/main/java/lcsb/mapviewer/api/projects/comments/CommentRestImpl.java @@ -4,15 +4,14 @@ import java.awt.geom.Line2D; import java.awt.geom.Point2D; import java.util.*; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; -import lcsb.mapviewer.api.BaseRestImpl; -import lcsb.mapviewer.api.ElementIdentifierType; -import lcsb.mapviewer.api.ObjectNotFoundException; -import lcsb.mapviewer.api.QueryException; +import lcsb.mapviewer.api.*; +import lcsb.mapviewer.common.Configuration; import lcsb.mapviewer.common.geometry.PointTransformation; import lcsb.mapviewer.model.Project; import lcsb.mapviewer.model.map.Comment; @@ -22,7 +21,6 @@ import lcsb.mapviewer.model.map.species.Element; import lcsb.mapviewer.persist.dao.map.ReactionDao; import lcsb.mapviewer.persist.dao.map.species.ElementDao; import lcsb.mapviewer.services.interfaces.ICommentService; -import lcsb.mapviewer.services.overlay.IconManager; @Transactional @Service @@ -38,7 +36,7 @@ public class CommentRestImpl extends BaseRestImpl { private ReactionDao reactionDao; private ElementDao elementDao; - + private PointTransformation pt = new PointTransformation(); @Autowired @@ -101,48 +99,48 @@ public class CommentRestImpl extends BaseRestImpl { String column = string.toLowerCase(); Object value; switch (column) { - case "id": - case "idobject": - value = comment.getId(); - break; - case "elementid": - value = getId(comment); - break; - case "modelid": - value = comment.getSubmodelData().getId(); - break; - case "title": - value = getTitle(comment); - break; - case "pinned": - value = comment.isPinned(); - break; - case "content": - value = comment.getContent(); - break; - case "removed": - value = comment.isDeleted(); - break; - case "coord": - value = getCoordinates(comment); - break; - case "removereason": - value = comment.getRemoveReason(); - break; - case "type": - value = getType(comment); - break; - case "icon": - value = IconManager.getInstance().getCommentIcon(); - break; - case "author": - value = comment.getName(); - break; - case "email": - value = comment.getEmail(); - break; - default: - value = "Unknown column"; + case "id": + case "idobject": + value = comment.getId(); + break; + case "elementid": + value = getId(comment); + break; + case "modelid": + value = comment.getSubmodelData().getId(); + break; + case "title": + value = getTitle(comment); + break; + case "pinned": + value = comment.isPinned(); + break; + case "content": + value = comment.getContent(); + break; + case "removed": + value = comment.isDeleted(); + break; + case "coord": + value = getCoordinates(comment); + break; + case "removereason": + value = comment.getRemoveReason(); + break; + case "type": + value = getType(comment); + break; + case "icon": + value = "icons/comment.png?v=" + Configuration.getSystemBuildVersion(null); + break; + case "author": + value = comment.getName(); + break; + case "email": + value = comment.getEmail(); + break; + default: + value = "Unknown column"; } result.put(string, value); } @@ -247,7 +245,7 @@ public class CommentRestImpl extends BaseRestImpl { } public Map<String, Object> addComment(String projectId, String elementType, String elementId, - String name, String email, String content, boolean pinned, Point2D pointCoordinates, String submodelId) + String name, String email, String content, boolean pinned, Point2D pointCoordinates, String submodelId) throws QueryException { Model model = getModelService().getLastModelByProjectId(projectId); if (model == null) { diff --git a/rest-api/src/test/java/lcsb/mapviewer/api/BaseRestImplTest.java b/rest-api/src/test/java/lcsb/mapviewer/api/BaseRestImplTest.java index 96f751f9e0cade74be49a6d8cdd51604f78948ad..b8956aa19140f860e651f893ce1b50bd557cfe79 100644 --- a/rest-api/src/test/java/lcsb/mapviewer/api/BaseRestImplTest.java +++ b/rest-api/src/test/java/lcsb/mapviewer/api/BaseRestImplTest.java @@ -1,16 +1,13 @@ package lcsb.mapviewer.api; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.CALLS_REAL_METHODS; +import static org.junit.Assert.*; +import static org.mockito.Mockito.*; import java.util.List; import java.util.Map; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.junit.Test; import org.mockito.Mockito; import org.springframework.beans.factory.annotation.Autowired; @@ -72,16 +69,10 @@ public class BaseRestImplTest extends RestTestFunctions { @Test public void testPrepareAnnotatorsParams() throws Exception { BaseRestImpl controller = Mockito.mock(BaseRestImpl.class, CALLS_REAL_METHODS); - try { - for (ElementAnnotator annotator : annotators) { - AnnotatorData annotatorData = annotator.createAnnotatorData(); - List<Map<String, Object>> data = controller.prepareAnnotatorsParams(annotatorData.getAnnotatorParams()); - assertEquals(annotatorData.getAnnotatorParams().size(), data.size()); - } - - } catch (Exception e) { - e.printStackTrace(); - throw e; + for (ElementAnnotator annotator : annotators) { + AnnotatorData annotatorData = annotator.createAnnotatorData(); + List<Map<String, Object>> data = controller.prepareAnnotatorsParams(annotatorData.getAnnotatorParams()); + assertEquals(annotatorData.getAnnotatorParams().size(), data.size()); } } @@ -102,12 +93,14 @@ public class BaseRestImplTest extends RestTestFunctions { Map<String, Object> response = controller.createAnnotation(new MiriamData(MiriamType.PUBMED, "")); assertNotNull(response); } + @Test public void testParseIntegerFromDouble() throws Exception { BaseRestImpl controller = Mockito.mock(BaseRestImpl.class, CALLS_REAL_METHODS); Integer x = controller.parseInteger(12.3); - assertEquals((Integer)12, x); + assertEquals((Integer) 12, x); } + @Test public void testParseIntegerFromNull() throws Exception { BaseRestImpl controller = Mockito.mock(BaseRestImpl.class, CALLS_REAL_METHODS); diff --git a/rest-api/src/test/java/lcsb/mapviewer/api/RestTestFunctions.java b/rest-api/src/test/java/lcsb/mapviewer/api/RestTestFunctions.java index e9de4d3b364f4d7a5435a912200b4b18ab46763b..819a8d1da9d91748a29745d2613f8153d42bc9dc 100644 --- a/rest-api/src/test/java/lcsb/mapviewer/api/RestTestFunctions.java +++ b/rest-api/src/test/java/lcsb/mapviewer/api/RestTestFunctions.java @@ -15,8 +15,7 @@ import javax.xml.transform.stream.StreamResult; import org.apache.commons.io.FileUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import org.junit.After; -import org.junit.Before; +import org.junit.*; import org.junit.runner.RunWith; import org.mockito.Mockito; import org.springframework.beans.factory.annotation.Autowired; @@ -30,6 +29,7 @@ import org.w3c.dom.*; import org.xml.sax.InputSource; import org.xml.sax.SAXException; +import lcsb.mapviewer.common.UnitTestFailedWatcher; import lcsb.mapviewer.common.exception.InvalidXmlSchemaException; import lcsb.mapviewer.converter.*; import lcsb.mapviewer.converter.model.celldesigner.CellDesignerXmlParser; @@ -46,6 +46,10 @@ import lcsb.mapviewer.services.interfaces.*; @WebAppConfiguration @RunWith(SpringJUnit4ClassRunner.class) public abstract class RestTestFunctions { + + @Rule + public UnitTestFailedWatcher unitTestFailedWatcher = new UnitTestFailedWatcher(); + private Logger logger = LogManager.getLogger(RestTestFunctions.class); public double EPSILON = 1e-6; diff --git a/rest-api/src/test/java/lcsb/mapviewer/api/configuration/ConfigurationRestImplTest.java b/rest-api/src/test/java/lcsb/mapviewer/api/configuration/ConfigurationRestImplTest.java index f9781c4205de4b5621e715eadf212d3ee2d02a40..5fb67137f015319fc6edd0f6a1543cf5f6615b32 100644 --- a/rest-api/src/test/java/lcsb/mapviewer/api/configuration/ConfigurationRestImplTest.java +++ b/rest-api/src/test/java/lcsb/mapviewer/api/configuration/ConfigurationRestImplTest.java @@ -1,20 +1,12 @@ package lcsb.mapviewer.api.configuration; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.apache.logging.log4j.*; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.Test; +import static org.junit.Assert.*; + +import java.util.*; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.junit.*; import org.springframework.beans.factory.annotation.Autowired; import lcsb.mapviewer.api.QueryException; @@ -47,117 +39,70 @@ public class ConfigurationRestImplTest extends RestTestFunctions { @Test public void testGetAllParams() throws Exception { - try { - List<Map<String, Object>> list = configurationRestImpl.getAllValues(); - assertTrue(list.size() > 0); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + List<Map<String, Object>> list = configurationRestImpl.getAllValues(); + assertTrue(list.size() > 0); } - @Test + @Test(expected = QueryException.class) public void testSetSmtpPortToInvalid() throws Exception { - try { - Map<String, Object> data = new HashMap<>(); - data.put("value", "not a number"); - configurationRestImpl.updateOption(ConfigurationElementType.EMAIL_SMTP_PORT.name(), data); - fail("Exception expected"); - } catch (QueryException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Map<String, Object> data = new HashMap<>(); + data.put("value", "not a number"); + configurationRestImpl.updateOption(ConfigurationElementType.EMAIL_SMTP_PORT.name(), data); } @Test public void testSetSmtpPortToValid() throws Exception { - try { - Map<String, Object> data = new HashMap<>(); - data.put("value", "255"); - Map<String, Object> result = configurationRestImpl.updateOption( - ConfigurationElementType.EMAIL_SMTP_PORT.name(), data); - assertNotNull(result); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Map<String, Object> data = new HashMap<>(); + data.put("value", "255"); + Map<String, Object> result = configurationRestImpl.updateOption( + ConfigurationElementType.EMAIL_SMTP_PORT.name(), data); + assertNotNull(result); } @Test public void testImageFormats() throws Exception { - try { - List<Map<String, Object>> list = configurationRestImpl.getImageFormats(); - assertTrue(list.size() > 0); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + List<Map<String, Object>> list = configurationRestImpl.getImageFormats(); + assertTrue(list.size() > 0); } @Test public void testModelFormats() throws Exception { - try { - List<Map<String, Object>> list = configurationRestImpl.getModelFormats(); - assertTrue(list.size() > 0); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + List<Map<String, Object>> list = configurationRestImpl.getModelFormats(); + assertTrue(list.size() > 0); } @Test public void testGetElementTypes() throws Exception { - try { - Set<Map<String, String>> list = configurationRestImpl.getElementTypes(); - GenericProtein protein = new GenericProtein("id"); - boolean contains = false; - for (Map<String, String> object : list) { - contains |= (object.get("name").equals(protein.getStringType())); - } - assertTrue(contains); - } catch (Exception e) { - e.printStackTrace(); - throw e; + Set<Map<String, String>> list = configurationRestImpl.getElementTypes(); + GenericProtein protein = new GenericProtein("id"); + boolean contains = false; + for (Map<String, String> object : list) { + contains |= (object.get("name").equals(protein.getStringType())); } + assertTrue(contains); } @Test public void testGetReactionTypes() throws Exception { - try { - Set<Map<String, String>> list = configurationRestImpl.getReactionTypes(); - StateTransitionReaction reaction = new StateTransitionReaction(); - boolean contains = false; - for (Map<String, String> object : list) { - contains |= (object.get("name").equals(reaction.getStringType())); - } - assertTrue(contains); - } catch (Exception e) { - e.printStackTrace(); - throw e; + Set<Map<String, String>> list = configurationRestImpl.getReactionTypes(); + StateTransitionReaction reaction = new StateTransitionReaction(); + boolean contains = false; + for (Map<String, String> object : list) { + contains |= (object.get("name").equals(reaction.getStringType())); } + assertTrue(contains); } @Test public void testGetMiriamTypes() throws Exception { - try { - Map<?, ?> list = configurationRestImpl.getMiriamTypes(); - assertNotNull(list.get(MiriamType.PUBMED.name())); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Map<?, ?> list = configurationRestImpl.getMiriamTypes(); + assertNotNull(list.get(MiriamType.PUBMED.name())); } @Test public void testGetBioEntityFields() throws Exception { - try { - List<?> list = configurationRestImpl.getBioEntityFields(); - assertEquals(BioEntityField.values().length, list.size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + List<?> list = configurationRestImpl.getBioEntityFields(); + assertEquals(BioEntityField.values().length, list.size()); } } diff --git a/rest-api/src/test/java/lcsb/mapviewer/api/convert/ConvertRestImplTest.java b/rest-api/src/test/java/lcsb/mapviewer/api/convert/ConvertRestImplTest.java index aca2fb4fcaee33c62fc0b859b0e446a5b114897a..b94871d6fbc04742100f5a8a0f76fc92bd4a3605 100644 --- a/rest-api/src/test/java/lcsb/mapviewer/api/convert/ConvertRestImplTest.java +++ b/rest-api/src/test/java/lcsb/mapviewer/api/convert/ConvertRestImplTest.java @@ -45,226 +45,123 @@ public class ConvertRestImplTest extends RestTestFunctions { @SuppressWarnings("unchecked") @Test public void testGetInformation() throws Exception { - try { - Map<String, Object> result = convertRestImpl.getInformationImage(); - assertTrue(result.keySet().size() == 2); - assertNotNull(result.get("inputs")); - assertNotNull(result.get("outputs")); + Map<String, Object> result = convertRestImpl.getInformationImage(); + assertTrue(result.keySet().size() == 2); + assertNotNull(result.get("inputs")); + assertNotNull(result.get("outputs")); - List<Object> inputs = (List<Object>) result.get("inputs"); - List<Object> outputs = (List<Object>) result.get("outputs"); + List<Object> inputs = (List<Object>) result.get("inputs"); + List<Object> outputs = (List<Object>) result.get("outputs"); - assertTrue(inputs.size() > 0); - assertTrue(outputs.size() > 0); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertTrue(inputs.size() > 0); + assertTrue(outputs.size() > 0); } @SuppressWarnings("unchecked") @Test public void testGetInformationImage() throws Exception { - try { - Map<String, Object> result = convertRestImpl.getInformationImage(); - assertTrue(result.keySet().size() == 2); - assertNotNull(result.get("inputs")); - assertNotNull(result.get("outputs")); + Map<String, Object> result = convertRestImpl.getInformationImage(); + assertTrue(result.keySet().size() == 2); + assertNotNull(result.get("inputs")); + assertNotNull(result.get("outputs")); - List<Object> inputs = (List<Object>) result.get("inputs"); - List<Object> outputs = (List<Object>) result.get("outputs"); + List<Object> inputs = (List<Object>) result.get("inputs"); + List<Object> outputs = (List<Object>) result.get("outputs"); - assertTrue(inputs.size() > 0); - assertTrue(outputs.size() > 0); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertTrue(inputs.size() > 0); + assertTrue(outputs.size() > 0); } @Test public void testCelDesigner2Sbml1() throws Exception { - try { - String content = readFile("testFiles/convert/sample-cd.xml"); - String result = convertRestImpl.convert( - "lcsb.mapviewer.converter.model.celldesigner.CellDesignerXmlParser", - "lcsb.mapviewer.converter.model.sbml.SbmlParser", content); - assertTrue(result.length() > 0); - assertTrue(result.contains("</layout:speciesReferenceGlyph>")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String content = readFile("testFiles/convert/sample-cd.xml"); + String result = convertRestImpl.convert( + "lcsb.mapviewer.converter.model.celldesigner.CellDesignerXmlParser", + "lcsb.mapviewer.converter.model.sbml.SbmlParser", content); + assertTrue(result.length() > 0); + assertTrue(result.contains("</layout:speciesReferenceGlyph>")); } - /* - * this test does not work because the generator is not deterministic - * - * @Test public void testCelDesigner2Sbml2() throws Exception { try { File file - * = new File("testFiles/convert/sample-cd.xml"); String content = - * FileUtils.readFileToString(file); String result = - * convertRestImpl.convert(token, "CellDesigner_SBML", "SBML", content); - * //String result2 = convertRestImpl.convert(token, "CellDesigner_SBML", - * "SBML", content); String result2 = convertRestImpl.convert(token, - * "lcsb.mapviewer.converter.model.celldesigner.CellDesignerXmlParser", - * "lcsb.mapviewer.converter.model.sbml.SbmlParser", content); - * - * assertTrue(result.equals(result2)); - * - * } catch (Exception e) { e.printStackTrace(); throw e; } } - */ - @Test public void testCelDesigner2Svg() throws Exception { - try { - String content = readFile("testFiles/convert/sample-cd.xml"); - String result = convertRestImpl.converToImage("CellDesigner_SBML", "svg", content).toString(); - - // FileOutputStream outputStream = new FileOutputStream("sample-cd.png"); - // outputStream.write(convertRestImpl.converToImage(token, "CellDesigner_SBML", - // "png", content).toByteArray()); - // outputStream.close(); - - assertTrue(result.contains("<rect")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String content = readFile("testFiles/convert/sample-cd.xml"); + String result = convertRestImpl.converToImage("CellDesigner_SBML", "svg", content).toString(); + + assertTrue(result.contains("<rect")); } @Test public void testCellDesigner2Sbml2Svg() throws Exception { - try { - String content = readFile("testFiles/convert/neuron_cd.xml"); - String resultSbml = convertRestImpl.convert("CellDesigner_SBML", "SBML", content).toString(); - String resultSvg = convertRestImpl.converToImage("SBML", "svg", resultSbml).toString(); - - // FileOutputStream outputStream = new FileOutputStream("sample-cd.png"); - // outputStream.write(convertRestImpl.converToImage(token, "CellDesigner_SBML", - // "png", content).toByteArray()); - // outputStream.close(); - - assertTrue(resultSvg.contains("<rect")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String content = readFile("testFiles/convert/neuron_cd.xml"); + String resultSbml = convertRestImpl.convert("CellDesigner_SBML", "SBML", content).toString(); + String resultSvg = convertRestImpl.converToImage("SBML", "svg", resultSbml).toString(); + + assertTrue(resultSvg.contains("<rect")); } @Test public void testCellDesigner2Sbml2CellDesignerSvg() throws Exception { - try { - String content = readFile("testFiles/convert/neuron_cd.xml"); - String resultSbml = convertRestImpl.convert("CellDesigner_SBML", "SBML", content).toString(); - String resultCellDesignerSbml = convertRestImpl.convert("SBML", "CellDesigner_SBML", resultSbml) - .toString(); - String resultSvg = convertRestImpl.converToImage("CellDesigner_SBML", "svg", resultCellDesignerSbml) - .toString(); - - // FileOutputStream outputStream = new FileOutputStream("sample-cd.png"); - // outputStream.write(convertRestImpl.converToImage(token, "CellDesigner_SBML", - // "png", content).toByteArray()); - // outputStream.close(); - - assertTrue(resultSvg.contains("<rect")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String content = readFile("testFiles/convert/neuron_cd.xml"); + String resultSbml = convertRestImpl.convert("CellDesigner_SBML", "SBML", content).toString(); + String resultCellDesignerSbml = convertRestImpl.convert("SBML", "CellDesigner_SBML", resultSbml) + .toString(); + String resultSvg = convertRestImpl.converToImage("CellDesigner_SBML", "svg", resultCellDesignerSbml) + .toString(); + + assertTrue(resultSvg.contains("<rect")); } @Test public void testScaling() throws Exception { - try { - String content = readFile("testFiles/convert/sample-cd.xml"); - String result1 = convertRestImpl.converToImage("CellDesigner_SBML", "svg", content, 50.0, 50.0).toString(); - String result2 = convertRestImpl.converToImage("CellDesigner_SBML", "svg", content, 100.0, 100.0) - .toString(); - - Pattern pattern = Pattern.compile(".*scale\\(([0-9]+\\.[0-9]+),([0-9]+\\.[0-9]+)\\).*"); - Matcher matcher1 = pattern.matcher(result1); - Matcher matcher2 = pattern.matcher(result2); + String content = readFile("testFiles/convert/sample-cd.xml"); + String result1 = convertRestImpl.converToImage("CellDesigner_SBML", "svg", content, 50.0, 50.0).toString(); + String result2 = convertRestImpl.converToImage("CellDesigner_SBML", "svg", content, 100.0, 100.0) + .toString(); - assertTrue(matcher1.find()); - assertTrue(matcher2.find()); + Pattern pattern = Pattern.compile(".*scale\\(([0-9]+\\.[0-9]+),([0-9]+\\.[0-9]+)\\).*"); + Matcher matcher1 = pattern.matcher(result1); + Matcher matcher2 = pattern.matcher(result2); - assertFalse(matcher1.group(1).toString().equals(matcher2.group(1).toString())); + assertTrue(matcher1.find()); + assertTrue(matcher2.find()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertFalse(matcher1.group(1).toString().equals(matcher2.group(1).toString())); } @Test public void test1() throws Exception { - try { - String content = readFile("testFiles/convert/glycolysis2.xml"); + String content = readFile("testFiles/convert/glycolysis2.xml"); - String result = convertRestImpl.convert("CellDesigner_SBML", "SBML", content); - ByteArrayOutputStream result1 = convertRestImpl.converToImage("SBML", "svg", result); + String result = convertRestImpl.convert("CellDesigner_SBML", "SBML", content); + ByteArrayOutputStream result1 = convertRestImpl.converToImage("SBML", "svg", result); - File output = new File("testFiles/convert/glycolysis2.svg"); + File output = new File("testFiles/convert/glycolysis2.svg"); - FileOutputStream outputStream = new FileOutputStream(output); - outputStream.write(result1.toByteArray()); - outputStream.close(); - assertTrue(output.exists()); - output.delete(); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + FileOutputStream outputStream = new FileOutputStream(output); + outputStream.write(result1.toByteArray()); + outputStream.close(); + assertTrue(output.exists()); + output.delete(); } @Test public void test2() throws Exception { - try { - String content = readFile("testFiles/convert/glycolysis2.xml"); + String content = readFile("testFiles/convert/glycolysis2.xml"); - String result = convertRestImpl.convert("CellDesigner_SBML", "SBML", content); - String result1 = convertRestImpl.convert("SBML", "CellDesigner_SBML", result); + String result = convertRestImpl.convert("CellDesigner_SBML", "SBML", content); + String result1 = convertRestImpl.convert("SBML", "CellDesigner_SBML", result); - assertNotNull(result); - assertNotNull(result1); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertNotNull(result); + assertNotNull(result1); } @Test public void testCelDesigner2Sbgn() throws Exception { - try { - String content = readFile("testFiles/convert/sample-cd.xml"); - String result = convertRestImpl.convert("CellDesigner_SBML", "SBGN-ML", content).toString(); - assertTrue(result.contains("glyph class=\"complex\"")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String content = readFile("testFiles/convert/sample-cd.xml"); + String result = convertRestImpl.convert("CellDesigner_SBML", "SBGN-ML", content).toString(); + assertTrue(result.contains("glyph class=\"complex\"")); } - /* - * this test does not work because the generator is not deterministic - * - * @Test public void testCelDesigner2Svg2() throws Exception { try { File file = - * new File("testFiles/convert/sample-cd.xml"); String content = - * FileUtils.readFileToString(file); String result = - * convertRestImpl.converToImage(token, "CellDesigner_SBML", "svg", - * content).toString(); String result2 = convertRestImpl.converToImage(token, - * "CellDesigner_SBML", "lcsb.mapviewer.converter.graphics.SvgImageGenerator", - * content).toString(); - * - * assertTrue(result.equals(result2)); - * - * } catch (Exception e) { e.printStackTrace(); throw e; } } - */ - @SuppressWarnings("unchecked") private List<String> extractIdsFromOutputs(Map<String, Object> infoObject) { List<String> ids = new ArrayList<>(); @@ -299,41 +196,20 @@ public class ConvertRestImplTest extends RestTestFunctions { @Test public void testCelDesigner2All() throws Exception { - - try { - String content = readFile("testFiles/convert/sample-cd.xml"); - test2All(content, "CellDesigner_SBML"); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String content = readFile("testFiles/convert/sample-cd.xml"); + test2All(content, "CellDesigner_SBML"); } @Test public void testSbml2All() throws Exception { - - try { - String content = readFile("testFiles/convert/sample-sbml.xml"); - test2All(content, "SBML"); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String content = readFile("testFiles/convert/sample-sbml.xml"); + test2All(content, "SBML"); } @Test public void testSbgn2All() throws Exception { - - try { - String content = readFile("testFiles/convert/sample.sbgn"); - test2All(content, "SBGN-ML"); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String content = readFile("testFiles/convert/sample.sbgn"); + test2All(content, "SBGN-ML"); } } diff --git a/rest-api/src/test/java/lcsb/mapviewer/api/genomics/ReferenceGenomeControllerTest.java b/rest-api/src/test/java/lcsb/mapviewer/api/genomics/ReferenceGenomeControllerTest.java index 337e26d216330b88a86ea40f5118b0f755c311c7..3caee1b2fe79448f13a0e0c82ec3f4a2205c9f40 100644 --- a/rest-api/src/test/java/lcsb/mapviewer/api/genomics/ReferenceGenomeControllerTest.java +++ b/rest-api/src/test/java/lcsb/mapviewer/api/genomics/ReferenceGenomeControllerTest.java @@ -1,20 +1,15 @@ package lcsb.mapviewer.api.genomics; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import java.util.List; import java.util.Map; -import org.apache.logging.log4j.*; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.Test; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.junit.*; import org.springframework.beans.factory.annotation.Autowired; -import lcsb.mapviewer.api.ObjectNotFoundException; import lcsb.mapviewer.api.QueryException; import lcsb.mapviewer.api.RestTestFunctions; @@ -36,78 +31,42 @@ public class ReferenceGenomeControllerTest extends RestTestFunctions { public void tearDown() throws Exception { } - @Test + @Test(expected = QueryException.class) public void testGetForNonExistingType() throws Exception { - try { - referenceGenomeRestImpl.getReferenceGenome("9606", "type", "ver"); - fail("Exception expected"); - } catch (QueryException e2) { - assertTrue(e2.getMessage().contains("Cannot find type")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + referenceGenomeRestImpl.getReferenceGenome("9606", "type", "ver"); } - @Test + @Test(expected = QueryException.class) public void testGetForNonExistingOrganism() throws Exception { - try { - referenceGenomeRestImpl.getReferenceGenome("960000", "UCSC", "ver"); - fail("Exception expected"); - } catch (ObjectNotFoundException e2) { - assertTrue(e2.getMessage().contains("Cannot find requested reference genome")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + referenceGenomeRestImpl.getReferenceGenome("960000", "UCSC", "ver"); } @Test public void testGetReferenceGenomeTaxonomies() throws Exception { - try { - List<Map<String, Object>> result = referenceGenomeRestImpl.getReferenceGenomeTaxonomies(); - assertNotNull(result); - assertTrue(result.size() > 0); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + List<Map<String, Object>> result = referenceGenomeRestImpl.getReferenceGenomeTaxonomies(); + assertNotNull(result); + assertTrue(result.size() > 0); } @Test public void testGetReferenceGenomeTypes() throws Exception { - try { - List<Map<String, Object>> result = referenceGenomeRestImpl.getReferenceGenomeTypes("9606"); - assertNotNull(result); - assertTrue(result.size() > 0); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + List<Map<String, Object>> result = referenceGenomeRestImpl.getReferenceGenomeTypes("9606"); + assertNotNull(result); + assertTrue(result.size() > 0); } @Test public void testGetReferenceGenomeVersions() throws Exception { - try { - List<Map<String, Object>> result = referenceGenomeRestImpl.getReferenceGenomeVersions("9606","UCSC"); - assertNotNull(result); - assertTrue(result.size() > 0); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + List<Map<String, Object>> result = referenceGenomeRestImpl.getReferenceGenomeVersions("9606", "UCSC"); + assertNotNull(result); + assertTrue(result.size() > 0); } @Test public void testGetRemoteUrls() throws Exception { - try { - List<Map<String, Object>> result = referenceGenomeRestImpl.getRemoteUrls("9606", "UCSC", "hg18"); - assertNotNull(result); - assertTrue(result.size() > 0); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + List<Map<String, Object>> result = referenceGenomeRestImpl.getRemoteUrls("9606", "UCSC", "hg18"); + assertNotNull(result); + assertTrue(result.size() > 0); } } diff --git a/rest-api/src/test/java/lcsb/mapviewer/api/plugins/PluginRestImplTest.java b/rest-api/src/test/java/lcsb/mapviewer/api/plugins/PluginRestImplTest.java index f741affc0b955ce60ed237dc1fd0a7cddd181cb1..6f486f9d732572ae125f40ec145b3a991d3169e5 100644 --- a/rest-api/src/test/java/lcsb/mapviewer/api/plugins/PluginRestImplTest.java +++ b/rest-api/src/test/java/lcsb/mapviewer/api/plugins/PluginRestImplTest.java @@ -12,23 +12,13 @@ public class PluginRestImplTest extends RestTestFunctions { @Test public void testCreatePlugin() throws Exception { - try { - pluginRestImpl.createPlugin("x", "x", "x", "x", true); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + pluginRestImpl.createPlugin("x", "x", "x", "x", true); } @Test public void testRemovePlugin() throws Exception { - try { - pluginRestImpl.createPlugin("x", "x", "x", "x", true); - pluginRestImpl.removePlugin("x"); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + pluginRestImpl.createPlugin("x", "x", "x", "x", true); + pluginRestImpl.removePlugin("x"); } } diff --git a/rest-api/src/test/java/lcsb/mapviewer/api/projects/ProjectRestImplTest.java b/rest-api/src/test/java/lcsb/mapviewer/api/projects/ProjectRestImplTest.java index 121d7990a34fef91c482988cc1024ffe0fb1d759..1e03f78932db687cfcc3723eb9824fc4a0e99758 100644 --- a/rest-api/src/test/java/lcsb/mapviewer/api/projects/ProjectRestImplTest.java +++ b/rest-api/src/test/java/lcsb/mapviewer/api/projects/ProjectRestImplTest.java @@ -1,20 +1,13 @@ package lcsb.mapviewer.api.projects; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.Mockito.times; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; - -import org.apache.logging.log4j.*; +import static org.junit.Assert.*; +import static org.mockito.ArgumentMatchers.*; +import static org.mockito.Mockito.*; + +import java.util.*; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; @@ -24,13 +17,8 @@ import org.springframework.util.MultiValueMap; import com.google.gson.Gson; -import lcsb.mapviewer.api.ObjectNotFoundException; -import lcsb.mapviewer.api.QueryException; -import lcsb.mapviewer.api.RestTestFunctions; -import lcsb.mapviewer.converter.zip.ImageZipEntryFile; -import lcsb.mapviewer.converter.zip.LayoutZipEntryFile; -import lcsb.mapviewer.converter.zip.ModelZipEntryFile; -import lcsb.mapviewer.converter.zip.ZipEntryFile; +import lcsb.mapviewer.api.*; +import lcsb.mapviewer.converter.zip.*; import lcsb.mapviewer.model.Project; import lcsb.mapviewer.model.map.MiriamType; import lcsb.mapviewer.model.map.model.Model; @@ -61,40 +49,25 @@ public class ProjectRestImplTest extends RestTestFunctions { @Test public void testGetModelDataDependencies() throws Exception { - try { - ProjectRestImpl projectRest = createMockProjectRest("testFiles/model/sample.xml"); - Map<String, Object> result = projectRest.getProject("sample"); - Gson gson = new Gson(); - assertNotNull(gson.toJson(result)); - Mockito.verify(projectRest.getModelService(), times(0)).getLastModelByProjectId(anyString()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + ProjectRestImpl projectRest = createMockProjectRest("testFiles/model/sample.xml"); + Map<String, Object> result = projectRest.getProject("sample"); + Gson gson = new Gson(); + assertNotNull(gson.toJson(result)); + Mockito.verify(projectRest.getModelService(), times(0)).getLastModelByProjectId(anyString()); } @Test(expected = ObjectNotFoundException.class) public void testRemoveNonExistentProject() throws Exception { - try { - _projectRestImpl.removeProject("blabla", null); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + _projectRestImpl.removeProject("blabla", null); } @Test public void testRemoveProject() throws Exception { - try { - String projectId = "test"; - Project project = new Project(); - project.setProjectId(projectId); - projectDao.add(project); - _projectRestImpl.removeProject(projectId, null); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String projectId = "test"; + Project project = new Project(); + project.setProjectId(projectId); + projectDao.add(project); + _projectRestImpl.removeProject(projectId, null); } @Test(expected = ObjectNotFoundException.class) @@ -105,164 +78,115 @@ public class ProjectRestImplTest extends RestTestFunctions { @Test public void testGetProject() throws Exception { - try { - ProjectRestImpl projectRest = createMockProjectRest("testFiles/model/sample.xml"); - Map<String, Object> result = projectRest.getProject("sample"); - Gson gson = new Gson(); - assertNotNull(gson.toJson(result)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + ProjectRestImpl projectRest = createMockProjectRest("testFiles/model/sample.xml"); + Map<String, Object> result = projectRest.getProject("sample"); + Gson gson = new Gson(); + assertNotNull(gson.toJson(result)); } @Test public void testUpdateProject() throws Exception { - try { - ProjectRestImpl projectRest = createMockProjectRest("testFiles/model/sample.xml"); - Map<String, String> disease = new HashMap<>(); - disease.put("type", MiriamType.MESH_2012.name()); - disease.put("resource", "D010300"); - Map<String, Object> data = new HashMap<>(); - data.put("version", "1"); - data.put("name", "test"); - data.put("organism", null); - data.put("disease", disease); - data.put("projectId", "sample"); - data.put("id", "0"); - projectRest.updateProject("sample", data); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + ProjectRestImpl projectRest = createMockProjectRest("testFiles/model/sample.xml"); + Map<String, String> disease = new HashMap<>(); + disease.put("type", MiriamType.MESH_2012.name()); + disease.put("resource", "D010300"); + Map<String, Object> data = new HashMap<>(); + data.put("version", "1"); + data.put("name", "test"); + data.put("organism", null); + data.put("disease", disease); + data.put("projectId", "sample"); + data.put("id", "0"); + projectRest.updateProject("sample", data); } @Test public void testComputePathForProject() throws Exception { - try { - String projectId = "Some_id"; - String directory1 = _projectRestImpl.computePathForProject(projectId, "."); - Project project = new Project(projectId); - projectDao.add(project); - projectDao.delete(project); - String directory2 = _projectRestImpl.computePathForProject(projectId, "."); - - assertFalse(directory1.equals(directory2)); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String projectId = "Some_id"; + String directory1 = _projectRestImpl.computePathForProject(projectId, "."); + Project project = new Project(projectId); + projectDao.add(project); + projectDao.delete(project); + String directory2 = _projectRestImpl.computePathForProject(projectId, "."); + + assertFalse(directory1.equals(directory2)); } @Test public void testGetProjects() throws Exception { - try { - ProjectRestImpl projectRest = createMockProjectRest("testFiles/model/sample.xml"); - List<Map<String, Object>> result = projectRest.getProjects(); - Gson gson = new Gson(); - assertNotNull(gson.toJson(result)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + ProjectRestImpl projectRest = createMockProjectRest("testFiles/model/sample.xml"); + List<Map<String, Object>> result = projectRest.getProjects(); + Gson gson = new Gson(); + assertNotNull(gson.toJson(result)); } @Test public void testGetStatistics() throws Exception { - try { - ProjectRestImpl projectRest = createMockProjectRest("testFiles/model/sample.xml"); - Map<String, Object> result = projectRest.getStatistics("sample"); - Gson gson = new Gson(); - assertNotNull(gson.toJson(result)); - - Map<?, ?> elementAnnotations = (Map<?, ?>) result.get("elementAnnotations"); - assertEquals(elementAnnotations.get(MiriamType.CAS), 0); - assertTrue((Integer) elementAnnotations.get(MiriamType.ENTREZ) > 0); - - Map<?, ?> reactionAnnotations = (Map<?, ?>) result.get("reactionAnnotations"); - assertEquals(reactionAnnotations.get(MiriamType.ENTREZ), 0); - assertEquals(reactionAnnotations.get(MiriamType.PUBMED), 1); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + ProjectRestImpl projectRest = createMockProjectRest("testFiles/model/sample.xml"); + Map<String, Object> result = projectRest.getStatistics("sample"); + Gson gson = new Gson(); + assertNotNull(gson.toJson(result)); + + Map<?, ?> elementAnnotations = (Map<?, ?>) result.get("elementAnnotations"); + assertEquals(elementAnnotations.get(MiriamType.CAS), 0); + assertTrue((Integer) elementAnnotations.get(MiriamType.ENTREZ) > 0); + + Map<?, ?> reactionAnnotations = (Map<?, ?>) result.get("reactionAnnotations"); + assertEquals(reactionAnnotations.get(MiriamType.ENTREZ), 0); + assertEquals(reactionAnnotations.get(MiriamType.PUBMED), 1); } @Test public void testGetMetaDataForComplexWithImages() throws Exception { - try { - ProjectRestImpl projectRest = createMockProjectRest("testFiles/model/complex_model_with_submaps.zip"); - Map<String, Object> result = projectRest.getProject("sample"); - Gson gson = new Gson(); - assertNotNull(gson.toJson(result)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + ProjectRestImpl projectRest = createMockProjectRest("testFiles/model/complex_model_with_submaps.zip"); + Map<String, Object> result = projectRest.getProject("sample"); + Gson gson = new Gson(); + assertNotNull(gson.toJson(result)); } @Test public void testExtractZipEntries() throws Exception { - try { - MultiValueMap<String, Object> data = new LinkedMultiValueMap<>(); - data.put("zip-entries[0][_type]", createLinkedList("MAP")); - data.put("zip-entries[0][_filename]", createLinkedList("main.xml")); - data.put("zip-entries[0][_data][root]", createLinkedList("true")); - data.put("zip-entries[0][_data][name]", createLinkedList("main")); - data.put("zip-entries[0][_data][type][id]", createLinkedList("UNKNOWN")); - data.put("zip-entries[0][_data][type][name]", createLinkedList("Unknown")); - data.put("zip-entries[1][_type]", createLinkedList("OVERLAY")); - data.put("zip-entries[1][_filename]", createLinkedList("layouts/goodschema.txt")); - data.put("zip-entries[1][_data][name]", createLinkedList("example name")); - data.put("zip-entries[1][_data][description]", createLinkedList("layout description")); - data.put("zip-entries[2][_type]", createLinkedList("IMAGE")); - data.put("zip-entries[2][_filename]", createLinkedList("images/test.png")); - List<ZipEntryFile> result = _projectRestImpl.extractZipEntries(data); - assertNotNull(result); - assertEquals(3, result.size()); - assertTrue(result.get(0) instanceof ModelZipEntryFile); - assertTrue(result.get(1) instanceof LayoutZipEntryFile); - assertTrue(result.get(2) instanceof ImageZipEntryFile); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + MultiValueMap<String, Object> data = new LinkedMultiValueMap<>(); + data.put("zip-entries[0][_type]", createLinkedList("MAP")); + data.put("zip-entries[0][_filename]", createLinkedList("main.xml")); + data.put("zip-entries[0][_data][root]", createLinkedList("true")); + data.put("zip-entries[0][_data][name]", createLinkedList("main")); + data.put("zip-entries[0][_data][type][id]", createLinkedList("UNKNOWN")); + data.put("zip-entries[0][_data][type][name]", createLinkedList("Unknown")); + data.put("zip-entries[1][_type]", createLinkedList("OVERLAY")); + data.put("zip-entries[1][_filename]", createLinkedList("layouts/goodschema.txt")); + data.put("zip-entries[1][_data][name]", createLinkedList("example name")); + data.put("zip-entries[1][_data][description]", createLinkedList("layout description")); + data.put("zip-entries[2][_type]", createLinkedList("IMAGE")); + data.put("zip-entries[2][_filename]", createLinkedList("images/test.png")); + List<ZipEntryFile> result = _projectRestImpl.extractZipEntries(data); + assertNotNull(result); + assertEquals(3, result.size()); + assertTrue(result.get(0) instanceof ModelZipEntryFile); + assertTrue(result.get(1) instanceof LayoutZipEntryFile); + assertTrue(result.get(2) instanceof ImageZipEntryFile); + } @Test(expected = QueryException.class) public void testExtractZipEntriesWithInvalidType() throws Exception { - try { - MultiValueMap<String, Object> data = new LinkedMultiValueMap<>(); - data.put("zip-entries[0][_type]", createLinkedList("MAPX")); - data.put("zip-entries[0][_filename]", createLinkedList("main.xml")); - _projectRestImpl.extractZipEntries(data); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + MultiValueMap<String, Object> data = new LinkedMultiValueMap<>(); + data.put("zip-entries[0][_type]", createLinkedList("MAPX")); + data.put("zip-entries[0][_filename]", createLinkedList("main.xml")); + _projectRestImpl.extractZipEntries(data); } @Test public void testExtractZipEntriesWithNoMapType() throws Exception { - try { - MultiValueMap<String, Object> data = new LinkedMultiValueMap<>(); - data.put("zip-entries[0][_type]", createLinkedList("MAP")); - data.put("zip-entries[0][_filename]", createLinkedList("main.xml")); - data.put("zip-entries[0][_data][root]", createLinkedList("true")); - data.put("zip-entries[0][_data][name]", createLinkedList("main")); - List<ZipEntryFile> result = _projectRestImpl.extractZipEntries(data); - assertNotNull(result); - assertEquals(1, result.size()); - assertTrue(result.get(0) instanceof ModelZipEntryFile); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + MultiValueMap<String, Object> data = new LinkedMultiValueMap<>(); + data.put("zip-entries[0][_type]", createLinkedList("MAP")); + data.put("zip-entries[0][_filename]", createLinkedList("main.xml")); + data.put("zip-entries[0][_data][root]", createLinkedList("true")); + data.put("zip-entries[0][_data][name]", createLinkedList("main")); + List<ZipEntryFile> result = _projectRestImpl.extractZipEntries(data); + assertNotNull(result); + assertEquals(1, result.size()); + assertTrue(result.get(0) instanceof ModelZipEntryFile); } private LinkedList<Object> createLinkedList(Object string) { @@ -297,16 +221,11 @@ public class ProjectRestImplTest extends RestTestFunctions { @Test public void testGetLogs() throws Exception { - try { - ProjectRestImpl projectRest = createMockProjectRest("testFiles/model/sample.xml"); - Map<String, Object> result = projectRest.getLogs("sample", "", "0", 10, "id", "asc", ""); - assertNotNull(result); - Gson gson = new Gson(); - assertNotNull(gson.toJson(result)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + ProjectRestImpl projectRest = createMockProjectRest("testFiles/model/sample.xml"); + Map<String, Object> result = projectRest.getLogs("sample", "", "0", 10, "id", "asc", ""); + assertNotNull(result); + Gson gson = new Gson(); + assertNotNull(gson.toJson(result)); } } diff --git a/rest-api/src/test/java/lcsb/mapviewer/api/projects/chemicals/ChemicalRestImplTest.java b/rest-api/src/test/java/lcsb/mapviewer/api/projects/chemicals/ChemicalRestImplTest.java index ffb0abb42a1aed93096272c930570302614b5909..a89809ec7d632c919a886e0a277ea2a96116a4f3 100644 --- a/rest-api/src/test/java/lcsb/mapviewer/api/projects/chemicals/ChemicalRestImplTest.java +++ b/rest-api/src/test/java/lcsb/mapviewer/api/projects/chemicals/ChemicalRestImplTest.java @@ -1,17 +1,14 @@ package lcsb.mapviewer.api.projects.chemicals; -import static org.junit.Assert.assertNotNull; -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.anyString; +import static org.junit.Assert.*; +import static org.mockito.ArgumentMatchers.*; import java.util.ArrayList; import java.util.Map; -import org.apache.logging.log4j.*; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.Test; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.junit.*; import org.mockito.Mockito; import org.springframework.beans.factory.annotation.Autowired; @@ -42,32 +39,21 @@ public class ChemicalRestImplTest extends RestTestFunctions { @Test public void testPrepareChemical() throws Exception { - try { - Chemical chemical = new Chemical(); - chemical.setChemicalId(new MiriamData(MiriamType.MESH_2012, "D010300")); - Map<String, Object> result = _drugRestImpl.prepareChemical(chemical, _drugRestImpl.createChemicalColumnSet(""), - new ArrayList<>()); - assertNotNull(result); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Chemical chemical = new Chemical(); + chemical.setChemicalId(new MiriamData(MiriamType.MESH_2012, "D010300")); + Map<String, Object> result = _drugRestImpl.prepareChemical(chemical, _drugRestImpl.createChemicalColumnSet(""), + new ArrayList<>()); + assertNotNull(result); } @Test public void testPrepareChemicalWithProblematicMesh() throws Exception { - try { + Chemical chemical = new Chemical(); + chemical.setChemicalId(new MiriamData(MiriamType.MESH_2012, "invalidID")); - Chemical chemical = new Chemical(); - chemical.setChemicalId(new MiriamData(MiriamType.MESH_2012, "invalidID")); - - Map<String, Object> result = _drugRestImpl.prepareChemical(chemical, _drugRestImpl.createChemicalColumnSet(""), - new ArrayList<>()); - assertNotNull(result); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Map<String, Object> result = _drugRestImpl.prepareChemical(chemical, _drugRestImpl.createChemicalColumnSet(""), + new ArrayList<>()); + assertNotNull(result); } protected ChemicalRestImpl createMockChemicalRest(String string) throws Exception { diff --git a/rest-api/src/test/java/lcsb/mapviewer/api/projects/comments/CommentRestImplTest.java b/rest-api/src/test/java/lcsb/mapviewer/api/projects/comments/CommentRestImplTest.java index 37e5293754fca193adf2f003c228b2b69fdf373d..56729f273ba20ce074d33a05ec41d623fbca8d8f 100644 --- a/rest-api/src/test/java/lcsb/mapviewer/api/projects/comments/CommentRestImplTest.java +++ b/rest-api/src/test/java/lcsb/mapviewer/api/projects/comments/CommentRestImplTest.java @@ -1,19 +1,12 @@ package lcsb.mapviewer.api.projects.comments; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.anyString; -import static org.mockito.Matchers.eq; -import static org.mockito.Mockito.times; +import static org.mockito.ArgumentMatchers.*; +import static org.mockito.Mockito.*; import java.util.ArrayList; import java.util.List; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.mockito.Mockito; import org.springframework.beans.factory.annotation.Autowired; @@ -41,29 +34,16 @@ public class CommentRestImplTest extends RestTestFunctions { public void tearDown() throws Exception { } - @Test + @Test(expected = QueryException.class) public void testGetForNonExisting() throws Exception { - try { - _commentRestImpl.getCommentList("unk", "", "", "", ""); - fail("Exception expected"); - } catch (QueryException e2) { - assertTrue(e2.getMessage().contains("Project with given id doesn't exist")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + _commentRestImpl.getCommentList("unk", "", "", "", ""); } @Test public void testGetCommentsDependencies() throws Exception { - try { - CommentRestImpl commentRestImpl = createMockProjectRest("testFiles/model/sample.xml"); - commentRestImpl.getCommentList("sample", "", "", "", ""); - Mockito.verify(commentRestImpl.getModelService(), times(0)).getLastModelByProjectId(anyString()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + CommentRestImpl commentRestImpl = createMockProjectRest("testFiles/model/sample.xml"); + commentRestImpl.getCommentList("sample", "", "", "", ""); + Mockito.verify(commentRestImpl.getModelService(), times(0)).getLastModelByProjectId(anyString()); } private CommentRestImpl createMockProjectRest(String string) throws Exception { diff --git a/rest-api/src/test/java/lcsb/mapviewer/api/projects/drugs/DrugRestImplTest.java b/rest-api/src/test/java/lcsb/mapviewer/api/projects/drugs/DrugRestImplTest.java index e87f9863c2666684dfbaf34ae94796280c307435..94c82b5e78b5f02e1437436e57bc9c216559edd1 100644 --- a/rest-api/src/test/java/lcsb/mapviewer/api/projects/drugs/DrugRestImplTest.java +++ b/rest-api/src/test/java/lcsb/mapviewer/api/projects/drugs/DrugRestImplTest.java @@ -1,16 +1,13 @@ package lcsb.mapviewer.api.projects.drugs; -import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.*; import java.util.List; import java.util.Map; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.springframework.beans.factory.annotation.Autowired; import lcsb.mapviewer.api.RestTestFunctions; @@ -38,30 +35,18 @@ public class DrugRestImplTest extends RestTestFunctions { @Test @SuppressWarnings("unchecked") public void testGetDrugsByQuery() throws Exception { - try { - DrugRestImpl drugRestImpl = createMockProjectRest("testFiles/model/drug_target.xml"); - Map<String, Object> result = drugRestImpl.getDrugsByQuery("drug_target", "", "Selisistat").get(0); - List<Map<String, Object>> references = (List<Map<String, Object>>) result.get("references"); - Map<String, Object> reference = references.get(0); - assertNotNull(reference.get("type")); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + DrugRestImpl drugRestImpl = createMockProjectRest("testFiles/model/drug_target.xml"); + Map<String, Object> result = drugRestImpl.getDrugsByQuery("drug_target", "", "Selisistat").get(0); + List<Map<String, Object>> references = (List<Map<String, Object>>) result.get("references"); + Map<String, Object> reference = references.get(0); + assertNotNull(reference.get("type")); } @Test public void testTargetWithEmptyMechanism() throws Exception { - try { - DrugRestImpl drugRestImpl = createMockProjectRest("testFiles/model/sample.xml"); - Map<String, Object> result = drugRestImpl.getDrugsByQuery("sample", "", "Picato").get(0); - assertNotNull(result); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + DrugRestImpl drugRestImpl = createMockProjectRest("testFiles/model/sample.xml"); + Map<String, Object> result = drugRestImpl.getDrugsByQuery("sample", "", "Picato").get(0); + assertNotNull(result); } private DrugRestImpl createMockProjectRest(String string) throws Exception { diff --git a/rest-api/src/test/java/lcsb/mapviewer/api/projects/mirnas/MiRnaRestImplTest.java b/rest-api/src/test/java/lcsb/mapviewer/api/projects/mirnas/MiRnaRestImplTest.java index c2e47c2aea8b7a86a9461880cfe0b9d16bcf6682..0cc98a4983c41d4c57b1bc1b1e3168a395692a9a 100644 --- a/rest-api/src/test/java/lcsb/mapviewer/api/projects/mirnas/MiRnaRestImplTest.java +++ b/rest-api/src/test/java/lcsb/mapviewer/api/projects/mirnas/MiRnaRestImplTest.java @@ -1,17 +1,12 @@ package lcsb.mapviewer.api.projects.mirnas; -import static org.junit.Assert.assertFalse; - -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.apache.logging.log4j.*; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.Test; +import static org.junit.Assert.*; + +import java.util.*; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.junit.*; import org.springframework.beans.factory.annotation.Autowired; import lcsb.mapviewer.api.RestTestFunctions; @@ -37,18 +32,12 @@ public class MiRnaRestImplTest extends RestTestFunctions { @Test public void testGetMiRnasByTarget() throws Exception { - try { - MiRnaRestImpl miRnaRestImpl = createMockProjectRest("testFiles/model/mi_rna_target.xml"); - List<Map<String, Object>> result = miRnaRestImpl.getMiRnasByTarget("mi_rna_target", "ALIAS", "0", ""); - Set<String> names = new HashSet<>(); - for (Map<String, Object> miRna : result) { - assertFalse("Duplicate miRna found: " + miRna.get("name"), names.contains(miRna.get("name"))); - names.add((String) miRna.get("name")); - } - - } catch (Exception e) { - e.printStackTrace(); - throw e; + MiRnaRestImpl miRnaRestImpl = createMockProjectRest("testFiles/model/mi_rna_target.xml"); + List<Map<String, Object>> result = miRnaRestImpl.getMiRnasByTarget("mi_rna_target", "ALIAS", "0", ""); + Set<String> names = new HashSet<>(); + for (Map<String, Object> miRna : result) { + assertFalse("Duplicate miRna found: " + miRna.get("name"), names.contains(miRna.get("name"))); + names.add((String) miRna.get("name")); } } diff --git a/rest-api/src/test/java/lcsb/mapviewer/api/projects/models/ModelRestImplTest.java b/rest-api/src/test/java/lcsb/mapviewer/api/projects/models/ModelRestImplTest.java index 9b8d4621d7a79c4b372628e9d407fe698f85f809..e61b549aa1056f06d7a8e247d235154dccd1aa8c 100644 --- a/rest-api/src/test/java/lcsb/mapviewer/api/projects/models/ModelRestImplTest.java +++ b/rest-api/src/test/java/lcsb/mapviewer/api/projects/models/ModelRestImplTest.java @@ -1,19 +1,11 @@ package lcsb.mapviewer.api.projects.models; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.nullable; -import static org.mockito.ArgumentMatchers.refEq; - -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import static org.junit.Assert.*; +import static org.mockito.ArgumentMatchers.*; + +import java.util.*; + +import org.junit.*; import org.mockito.Mockito; import org.springframework.beans.factory.annotation.Autowired; @@ -51,26 +43,16 @@ public class ModelRestImplTest extends RestTestFunctions { @Test public void testModels() throws Exception { - try { - ModelRestImpl modelRest = createMockProjectRest("testFiles/model/sample.xml"); - List<Map<String, Object>> result = modelRest.getModels("sample"); - assertEquals(1, result.size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + ModelRestImpl modelRest = createMockProjectRest("testFiles/model/sample.xml"); + List<Map<String, Object>> result = modelRest.getModels("sample"); + assertEquals(1, result.size()); } @Test public void testGetEmptyModels() throws Exception { - try { - ModelRestImpl modelRest = createEmptyProjectRest("test"); - List<Map<String, Object>> result = modelRest.getModels("test"); - assertEquals(0, result.size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + ModelRestImpl modelRest = createEmptyProjectRest("test"); + List<Map<String, Object>> result = modelRest.getModels("test"); + assertEquals(0, result.size()); } private ModelRestImpl createEmptyProjectRest(String string) throws Exception { @@ -101,101 +83,56 @@ public class ModelRestImplTest extends RestTestFunctions { return _modelRestImpl; } - @Test + @Test(expected = InvalidArgumentException.class) public void testGetModelAsImageForInvalidConverter() throws Exception { - try { - ModelRestImpl modelRest = createMockProjectRest("testFiles/model/sample.xml"); - modelRest.getModelAsImage("sample", "0", "", "", "", "", "", null); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + ModelRestImpl modelRest = createMockProjectRest("testFiles/model/sample.xml"); + modelRest.getModelAsImage("sample", "0", "", "", "", "", "", null); } @Test public void testGetModelAsImage() throws Exception { - try { - ModelRestImpl modelRest = createMockProjectRest("testFiles/model/sample.xml"); - FileEntry result = modelRest.getModelAsImage("sample", "0", PdfImageGenerator.class.getCanonicalName(), "", - "", "", "", null); - assertNotNull(result); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + ModelRestImpl modelRest = createMockProjectRest("testFiles/model/sample.xml"); + FileEntry result = modelRest.getModelAsImage("sample", "0", PdfImageGenerator.class.getCanonicalName(), "", + "", "", "", null); + assertNotNull(result); } @Test public void testGetModelAsImage2() throws Exception { - try { - ModelRestImpl modelRest = createMockProjectRest("testFiles/model/sample.xml"); - modelRest.getModelAsImage("sample", "0", PdfImageGenerator.class.getCanonicalName(), "", "", "", "", null); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + ModelRestImpl modelRest = createMockProjectRest("testFiles/model/sample.xml"); + modelRest.getModelAsImage("sample", "0", PdfImageGenerator.class.getCanonicalName(), "", "", "", "", null); } - @Test + @Test(expected = QueryException.class) public void testGetModelAsFileModel() throws Exception { - try { - ModelRestImpl modelRest = createMockProjectRest("testFiles/model/sample.xml"); - modelRest.getModelAsModelFile("sample", "0", "", "", "", null, null, null); - fail("Exception expected"); - } catch (QueryException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + ModelRestImpl modelRest = createMockProjectRest("testFiles/model/sample.xml"); + modelRest.getModelAsModelFile("sample", "0", "", "", "", null, null, null); } @Test public void testGetModelAsFileModel2() throws Exception { - try { - ModelRestImpl modelRest = createMockProjectRest("testFiles/model/sample.xml"); - modelRest.getModelAsModelFile("sample", "0", CellDesignerXmlParser.class.getCanonicalName(), "", - "0,0;90,0;90,90;90,0", null, null, null); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + ModelRestImpl modelRest = createMockProjectRest("testFiles/model/sample.xml"); + modelRest.getModelAsModelFile("sample", "0", CellDesignerXmlParser.class.getCanonicalName(), "", + "0,0;90,0;90,90;90,0", null, null, null); } - @Test + @Test(expected = QueryException.class) public void testGetModelAsFileModel3() throws Exception { - try { - ModelRestImpl modelRest = createMockProjectRest("testFiles/model/sample.xml"); - modelRest.getModelAsModelFile("sample", "0", "", "", "0,0;90,0;90,90;90,0", null, null, null); - fail("Exception expected"); - } catch (QueryException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + ModelRestImpl modelRest = createMockProjectRest("testFiles/model/sample.xml"); + modelRest.getModelAsModelFile("sample", "0", "", "", "0,0;90,0;90,90;90,0", null, null, null); } @Test public void testEmptyStringListToIntegerList() throws Exception { - try { - Set<Integer> ids = _modelRestImpl.stringListToIntegerSet(""); - assertNotNull(ids); - assertEquals(0, ids.size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Set<Integer> ids = _modelRestImpl.stringListToIntegerSet(""); + assertNotNull(ids); + assertEquals(0, ids.size()); } + @Test public void testStringListToIntegerArray() throws Exception { - try { - Set<Integer> ids = _modelRestImpl.stringListToIntegerSet("12,3"); - assertNotNull(ids); - assertEquals(2, ids.size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Set<Integer> ids = _modelRestImpl.stringListToIntegerSet("12,3"); + assertNotNull(ids); + assertEquals(2, ids.size()); } } diff --git a/rest-api/src/test/java/lcsb/mapviewer/api/projects/models/bioEntities/BioEntitiesControllerTest.java b/rest-api/src/test/java/lcsb/mapviewer/api/projects/models/bioEntities/BioEntitiesControllerTest.java index 9880ac19551ac1e7d33d918664b95a47acc0ce75..9483cb1af59089a461f6117a26e85cad1097984a 100644 --- a/rest-api/src/test/java/lcsb/mapviewer/api/projects/models/bioEntities/BioEntitiesControllerTest.java +++ b/rest-api/src/test/java/lcsb/mapviewer/api/projects/models/bioEntities/BioEntitiesControllerTest.java @@ -1,19 +1,15 @@ package lcsb.mapviewer.api.projects.models.bioEntities; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyString; +import static org.junit.Assert.*; +import static org.mockito.ArgumentMatchers.*; import java.awt.geom.Point2D; import java.util.List; import java.util.Map; -import org.apache.logging.log4j.*; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.Test; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.junit.*; import org.mockito.Mockito; import org.springframework.beans.factory.annotation.Autowired; @@ -45,19 +41,14 @@ public class BioEntitiesControllerTest extends RestTestFunctions { @Test public void testGetClosestElementsByCoordinates() throws Exception { - try { - BioEntitiesRestImpl projectRest = createMockProjectRest("testFiles/model/sample.xml"); - int count = 3; - List<Map<String, Object>> result = projectRest.getClosestElementsByCoordinates("sample", "0", - new Point2D.Double(1, 2), count, "false", ""); - assertEquals(count, result.size()); - - String json = mapper.writeValueAsString(result); - assertNotNull(json); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + BioEntitiesRestImpl projectRest = createMockProjectRest("testFiles/model/sample.xml"); + int count = 3; + List<Map<String, Object>> result = projectRest.getClosestElementsByCoordinates("sample", "0", + new Point2D.Double(1, 2), count, "false", ""); + assertEquals(count, result.size()); + + String json = mapper.writeValueAsString(result); + assertNotNull(json); } private BioEntitiesRestImpl createMockProjectRest(String string) throws Exception { diff --git a/rest-api/src/test/java/lcsb/mapviewer/api/projects/models/bioEntities/elements/ElementRestImplTest.java b/rest-api/src/test/java/lcsb/mapviewer/api/projects/models/bioEntities/elements/ElementRestImplTest.java index 84e71d57e48ff3696d0929ff6317bb0349d9ce4c..bf4ffea57d5f9fe95a7b20479af088ca727907b5 100644 --- a/rest-api/src/test/java/lcsb/mapviewer/api/projects/models/bioEntities/elements/ElementRestImplTest.java +++ b/rest-api/src/test/java/lcsb/mapviewer/api/projects/models/bioEntities/elements/ElementRestImplTest.java @@ -1,20 +1,14 @@ package lcsb.mapviewer.api.projects.models.bioEntities.elements; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.anyString; +import static org.junit.Assert.*; +import static org.mockito.ArgumentMatchers.*; import java.util.List; import java.util.Map; -import org.apache.logging.log4j.*; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.Test; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.junit.*; import org.mockito.Mockito; import org.springframework.beans.factory.annotation.Autowired; @@ -23,13 +17,8 @@ import com.fasterxml.jackson.databind.ObjectMapper; import lcsb.mapviewer.annotation.services.annotators.PdbAnnotator; import lcsb.mapviewer.api.RestTestFunctions; import lcsb.mapviewer.model.map.model.Model; -import lcsb.mapviewer.model.map.species.AntisenseRna; -import lcsb.mapviewer.model.map.species.GenericProtein; -import lcsb.mapviewer.model.map.species.Protein; -import lcsb.mapviewer.model.map.species.Rna; -import lcsb.mapviewer.model.map.species.field.ModificationSite; -import lcsb.mapviewer.model.map.species.field.ModificationState; -import lcsb.mapviewer.model.map.species.field.Residue; +import lcsb.mapviewer.model.map.species.*; +import lcsb.mapviewer.model.map.species.field.*; import lcsb.mapviewer.services.interfaces.IModelService; public class ElementRestImplTest extends RestTestFunctions { @@ -57,120 +46,87 @@ public class ElementRestImplTest extends RestTestFunctions { @Test public void testGetElementsProcessAllColumns() throws Exception { - try { - ElementsRestImpl projectRest = createMockElementRest("testFiles/model/sample.xml", true); - List<Map<String, Object>> result = projectRest.getElements("sample", "", "", "*", "", "", ""); - for (Map<String, Object> element : result) { - for (String paramName : element.keySet()) { - Object val = element.get(paramName); - String paramValue = ""; - if (val != null) { - paramValue = val.toString(); - } - assertFalse("Improper handler for column name: " + paramName, paramValue.contains("Unknown column")); + ElementsRestImpl projectRest = createMockElementRest("testFiles/model/sample.xml", true); + List<Map<String, Object>> result = projectRest.getElements("sample", "", "", "*", "", "", ""); + for (Map<String, Object> element : result) { + for (String paramName : element.keySet()) { + Object val = element.get(paramName); + String paramValue = ""; + if (val != null) { + paramValue = val.toString(); } + assertFalse("Improper handler for column name: " + paramName, paramValue.contains("Unknown column")); } - String json = mapper.writeValueAsString(result); - assertNotNull(json); - - } catch (Exception e) { - e.printStackTrace(); - throw e; } + String json = mapper.writeValueAsString(result); + assertNotNull(json); } @Test public void testGetElementsByType() throws Exception { - try { - String proteinType = new GenericProtein("1").getStringType(); - ElementsRestImpl projectRest = createMockElementRest("testFiles/model/sample.xml", false); - List<Map<String, Object>> result = projectRest.getElements("sample", "", "", "*", proteinType, "", ""); - assertEquals(12, result.size()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String proteinType = new GenericProtein("1").getStringType(); + ElementsRestImpl projectRest = createMockElementRest("testFiles/model/sample.xml", false); + List<Map<String, Object>> result = projectRest.getElements("sample", "", "", "*", proteinType, "", ""); + assertEquals(12, result.size()); } @Test public void testGetElementsVisibility() throws Exception { - try { - ElementsRestImpl elementRest = createMockElementRest("testFiles/model/sample.xml"); - List<Map<String, Object>> result = elementRest.getElements("sample", "", "", "*", "", "", ""); - for (Map<String, Object> map : result) { - assertTrue(map.get("hierarchyVisibilityLevel") instanceof String); - } - - } catch (Exception e) { - e.printStackTrace(); - throw e; + ElementsRestImpl elementRest = createMockElementRest("testFiles/model/sample.xml"); + List<Map<String, Object>> result = elementRest.getElements("sample", "", "", "*", "", "", ""); + for (Map<String, Object> map : result) { + assertTrue(map.get("hierarchyVisibilityLevel") instanceof String); } } @SuppressWarnings("unchecked") @Test public void testGetModificationsForProtein() throws Exception { - try { - String state = "asd"; - GenericProtein protein = new GenericProtein("s1"); - Residue mr = new Residue(); - mr.setState(ModificationState.ACETYLATED); - mr.setName("S250"); - protein.addResidue(mr); - protein.setStructuralState(state); - Map<String, Object> result = _elementsRestImpl.getOthersForElement(protein); - assertNotNull(result.get("modifications")); - assertEquals(state, result.get("structuralState")); - List<Map<String, Object>> modifications = (List<Map<String, Object>>) result.get("modifications"); - assertEquals(1, modifications.size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String state = "asd"; + GenericProtein protein = new GenericProtein("s1"); + Residue mr = new Residue(); + mr.setState(ModificationState.ACETYLATED); + mr.setName("S250"); + protein.addResidue(mr); + protein.setStructuralState(state); + Map<String, Object> result = _elementsRestImpl.getOthersForElement(protein); + assertNotNull(result.get("modifications")); + assertEquals(state, result.get("structuralState")); + List<Map<String, Object>> modifications = (List<Map<String, Object>>) result.get("modifications"); + assertEquals(1, modifications.size()); } @SuppressWarnings("unchecked") @Test public void testGetModificationsForRna() throws Exception { - try { - String state = "asd"; - Rna rna = new Rna("s1"); - ModificationSite mr = new ModificationSite(); - mr.setState(ModificationState.ACETYLATED); - mr.setName("S250"); - rna.addModificationSite(mr); - rna.setState(state); - Map<String, Object> result = _elementsRestImpl.getOthersForElement(rna); - assertNotNull(result.get("modifications")); - assertEquals(state, result.get("structuralState")); - List<Map<String, Object>> modifications = (List<Map<String, Object>>) result.get("modifications"); - assertEquals(1, modifications.size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String state = "asd"; + Rna rna = new Rna("s1"); + ModificationSite mr = new ModificationSite(); + mr.setState(ModificationState.ACETYLATED); + mr.setName("S250"); + rna.addModificationSite(mr); + rna.setState(state); + Map<String, Object> result = _elementsRestImpl.getOthersForElement(rna); + assertNotNull(result.get("modifications")); + assertEquals(state, result.get("structuralState")); + List<Map<String, Object>> modifications = (List<Map<String, Object>>) result.get("modifications"); + assertEquals(1, modifications.size()); } @SuppressWarnings("unchecked") @Test public void testGetModificationsForAntisenseRna() throws Exception { - try { - String state = "asd"; - AntisenseRna antisenseRna = new AntisenseRna("s1"); - ModificationSite mr = new ModificationSite(); - mr.setName("S250"); - antisenseRna.addModificationSite(mr); - antisenseRna.setState(state); - Map<String, Object> result = _elementsRestImpl.getOthersForElement(antisenseRna); - assertNotNull(result.get("modifications")); - assertEquals(state, result.get("structuralState")); - List<Map<String, Object>> modifications = (List<Map<String, Object>>) result.get("modifications"); - assertEquals(1, modifications.size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String state = "asd"; + AntisenseRna antisenseRna = new AntisenseRna("s1"); + ModificationSite mr = new ModificationSite(); + mr.setName("S250"); + antisenseRna.addModificationSite(mr); + antisenseRna.setState(state); + Map<String, Object> result = _elementsRestImpl.getOthersForElement(antisenseRna); + assertNotNull(result.get("modifications")); + assertEquals(state, result.get("structuralState")); + List<Map<String, Object>> modifications = (List<Map<String, Object>>) result.get("modifications"); + assertEquals(1, modifications.size()); } private ElementsRestImpl createMockElementRest(String string) throws Exception { diff --git a/rest-api/src/test/java/lcsb/mapviewer/api/projects/models/parameters/ParametersRestImplTest.java b/rest-api/src/test/java/lcsb/mapviewer/api/projects/models/parameters/ParametersRestImplTest.java index c3189f1b1b727b3bf695c6edea080ac048de3a9c..30a62541b25342a22fe932b48daca70eb8cdeba9 100644 --- a/rest-api/src/test/java/lcsb/mapviewer/api/projects/models/parameters/ParametersRestImplTest.java +++ b/rest-api/src/test/java/lcsb/mapviewer/api/projects/models/parameters/ParametersRestImplTest.java @@ -1,8 +1,5 @@ package lcsb.mapviewer.api.projects.models.parameters; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; @@ -24,47 +21,23 @@ public class ParametersRestImplTest extends RestTestFunctions { @Autowired IProjectService projectService; - @Test + @Test(expected = ObjectNotFoundException.class) public void testGetParameterForNonExistingProject() throws Exception { - try { - parametersRestImpl.getParameter("non-existing", "-1", "-1"); - fail("Exception expected"); - } catch (ObjectNotFoundException e) { - assertTrue(e.getMessage().contains("Project")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + parametersRestImpl.getParameter("non-existing", "-1", "-1"); } - @Test + @Test(expected = ObjectNotFoundException.class) public void testGetParameterForNonExistingModel() throws Exception { - try { - parametersRestImpl.getParameter(configurationService.getConfigurationValue(ConfigurationElementType.DEFAULT_MAP), - "-1", "-1"); - fail("Exception expected"); - } catch (ObjectNotFoundException e) { - assertTrue(e.getMessage().contains("Model")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + parametersRestImpl.getParameter(configurationService.getConfigurationValue(ConfigurationElementType.DEFAULT_MAP), + "-1", "-1"); } - @Test + @Test(expected = ObjectNotFoundException.class) public void testGetNonExistingParameter() throws Exception { - try { - Project project = projectService.getProjectByProjectId( - configurationService.getConfigurationValue(ConfigurationElementType.DEFAULT_MAP)); - parametersRestImpl.getParameter(project.getProjectId(), - "" + project.getModels().iterator().next().getId(), "-1"); - fail("Exception expected"); - } catch (ObjectNotFoundException e) { - assertTrue(e.getMessage().contains("Parameter")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Project project = projectService.getProjectByProjectId( + configurationService.getConfigurationValue(ConfigurationElementType.DEFAULT_MAP)); + parametersRestImpl.getParameter(project.getProjectId(), + "" + project.getModels().iterator().next().getId(), "-1"); } } diff --git a/rest-api/src/test/java/lcsb/mapviewer/api/projects/models/publications/PublicationsRestImplTest.java b/rest-api/src/test/java/lcsb/mapviewer/api/projects/models/publications/PublicationsRestImplTest.java index d6bfcd8df9d14c9a6ba3b2238e13b48620955672..738a8cbabc9182024d85fe822fd894f8b2197b1d 100644 --- a/rest-api/src/test/java/lcsb/mapviewer/api/projects/models/publications/PublicationsRestImplTest.java +++ b/rest-api/src/test/java/lcsb/mapviewer/api/projects/models/publications/PublicationsRestImplTest.java @@ -1,32 +1,21 @@ package lcsb.mapviewer.api.projects.models.publications; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyString; - -import java.util.ArrayList; -import java.util.Comparator; -import java.util.List; -import java.util.Map; +import static org.junit.Assert.*; +import static org.mockito.ArgumentMatchers.*; + +import java.util.*; import java.util.Map.Entry; -import org.apache.logging.log4j.*; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.Test; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.junit.*; import org.mockito.Mockito; import org.springframework.beans.factory.annotation.Autowired; import lcsb.mapviewer.api.QueryException; import lcsb.mapviewer.api.RestTestFunctions; import lcsb.mapviewer.api.projects.models.publications.PublicationsRestImpl.SortColumn; -import lcsb.mapviewer.model.map.BioEntity; -import lcsb.mapviewer.model.map.MiriamData; -import lcsb.mapviewer.model.map.MiriamType; +import lcsb.mapviewer.model.map.*; import lcsb.mapviewer.model.map.model.Model; import lcsb.mapviewer.services.interfaces.IModelService; @@ -50,78 +39,56 @@ public class PublicationsRestImplTest extends RestTestFunctions { @Test public void testPublications() throws Exception { - try { - PublicationsRestImpl projectRest = createMockProjectRest("testFiles/model/sample.xml"); - Map<String, Object> result = projectRest.getPublications("sample", "*", "0", 20, "", "", ""); - assertEquals(1, result.get("totalSize")); - assertEquals(0, result.get("start")); - assertEquals(1, ((List<?>) result.get("data")).size()); - - result = projectRest.getPublications("sample", "*", "1", 20, "", "", ""); - assertEquals(1, result.get("totalSize")); - assertEquals(1, result.get("start")); - assertEquals(0, ((List<?>) result.get("data")).size()); - - result = projectRest.getPublications("sample", "*", "0", 00, "", "", ""); - assertEquals(1, result.get("totalSize")); - assertEquals(0, result.get("start")); - assertEquals(0, ((List<?>) result.get("data")).size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + PublicationsRestImpl projectRest = createMockProjectRest("testFiles/model/sample.xml"); + Map<String, Object> result = projectRest.getPublications("sample", "*", "0", 20, "", "", ""); + assertEquals(1, result.get("totalSize")); + assertEquals(0, result.get("start")); + assertEquals(1, ((List<?>) result.get("data")).size()); + + result = projectRest.getPublications("sample", "*", "1", 20, "", "", ""); + assertEquals(1, result.get("totalSize")); + assertEquals(1, result.get("start")); + assertEquals(0, ((List<?>) result.get("data")).size()); + + result = projectRest.getPublications("sample", "*", "0", 00, "", "", ""); + assertEquals(1, result.get("totalSize")); + assertEquals(0, result.get("start")); + assertEquals(0, ((List<?>) result.get("data")).size()); } @Test public void testPublicationsFiltering() throws Exception { - try { - PublicationsRestImpl projectRest = createMockProjectRest("testFiles/model/sample.xml"); - Map<String, Object> result = projectRest.getPublications("sample", "*", "0", 20, "pubmedId", "asc", "123"); - assertEquals(1, result.get("totalSize")); - assertEquals(0, result.get("start")); - assertEquals(1, ((List<?>) result.get("data")).size()); - - result = projectRest.getPublications("sample", "*", "0", 20, "pubmedId", "asc", "1234"); - assertEquals(1, result.get("totalSize")); - assertEquals(0, result.get("start")); - assertEquals(0, ((List<?>) result.get("data")).size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + PublicationsRestImpl projectRest = createMockProjectRest("testFiles/model/sample.xml"); + Map<String, Object> result = projectRest.getPublications("sample", "*", "0", 20, "pubmedId", "asc", "123"); + assertEquals(1, result.get("totalSize")); + assertEquals(0, result.get("start")); + assertEquals(1, ((List<?>) result.get("data")).size()); + + result = projectRest.getPublications("sample", "*", "0", 20, "pubmedId", "asc", "1234"); + assertEquals(1, result.get("totalSize")); + assertEquals(0, result.get("start")); + assertEquals(0, ((List<?>) result.get("data")).size()); } @Test public void testPublicationsFilteringByModelName() throws Exception { - try { - PublicationsRestImpl projectRest = createMockProjectRest("testFiles/model/sample.xml"); - Map<String, Object> result = projectRest.getPublications("sample", "*", "0", 20, "pubmedId", "asc", - "sample"); - assertEquals(1, result.get("totalSize")); - assertEquals(0, result.get("start")); - assertTrue(((List<?>) result.get("data")).size() > 0); - - result = projectRest.getPublications("sample", "*", "0", 20, "pubmedId", "asc", "sampleX"); - assertEquals(1, result.get("totalSize")); - assertEquals(0, result.get("start")); - assertEquals(0, ((List<?>) result.get("data")).size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + PublicationsRestImpl projectRest = createMockProjectRest("testFiles/model/sample.xml"); + Map<String, Object> result = projectRest.getPublications("sample", "*", "0", 20, "pubmedId", "asc", + "sample"); + assertEquals(1, result.get("totalSize")); + assertEquals(0, result.get("start")); + assertTrue(((List<?>) result.get("data")).size() > 0); + + result = projectRest.getPublications("sample", "*", "0", 20, "pubmedId", "asc", "sampleX"); + assertEquals(1, result.get("totalSize")); + assertEquals(0, result.get("start")); + assertEquals(0, ((List<?>) result.get("data")).size()); } - @Test + @Test(expected = QueryException.class) public void testPublicationsInvalidSortingFiltering() throws Exception { - try { - PublicationsRestImpl projectRest = createMockProjectRest("testFiles/model/sample.xml"); - projectRest.getPublications("sample", "*", "0", 20, "xxx", "asc", "123"); - fail("Exception expected"); - } catch (QueryException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + PublicationsRestImpl projectRest = createMockProjectRest("testFiles/model/sample.xml"); + projectRest.getPublications("sample", "*", "0", 20, "xxx", "asc", "123"); } private PublicationsRestImpl createMockProjectRest(String string) throws Exception { @@ -135,34 +102,34 @@ public class PublicationsRestImplTest extends RestTestFunctions { @Test public void testComparatorForColumnWithInvalidData() { Entry<MiriamData, List<BioEntity>> valid = new Entry<MiriamData, List<BioEntity>>() { - + @Override public List<BioEntity> setValue(List<BioEntity> value) { return null; } - + @Override public List<BioEntity> getValue() { return new ArrayList<>(); } - + @Override public MiriamData getKey() { return new MiriamData(MiriamType.PUBMED, "12345"); } }; Entry<MiriamData, List<BioEntity>> invalid = new Entry<MiriamData, List<BioEntity>>() { - + @Override public List<BioEntity> setValue(List<BioEntity> value) { return null; } - + @Override public List<BioEntity> getValue() { return new ArrayList<>(); } - + @Override public MiriamData getKey() { return new MiriamData(MiriamType.PUBMED, ""); @@ -172,7 +139,7 @@ public class PublicationsRestImplTest extends RestTestFunctions { Comparator<Entry<MiriamData, List<BioEntity>>> comparator = _projectRestImpl.getComparatorForColumn(sortColumn, "desc"); assertNotNull(comparator.compare(valid, invalid)); - + } } diff --git a/rest-api/src/test/java/lcsb/mapviewer/api/projects/overlays/OverlayRestImplTest.java b/rest-api/src/test/java/lcsb/mapviewer/api/projects/overlays/OverlayRestImplTest.java index a7e4c47115630f6ef384b08328b6a897b424e92c..219f1f7fc1daa9fc6b6b30303ecbb3881ec71bd2 100644 --- a/rest-api/src/test/java/lcsb/mapviewer/api/projects/overlays/OverlayRestImplTest.java +++ b/rest-api/src/test/java/lcsb/mapviewer/api/projects/overlays/OverlayRestImplTest.java @@ -1,6 +1,6 @@ package lcsb.mapviewer.api.projects.overlays; -import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.*; import java.util.HashMap; import java.util.Map; @@ -36,15 +36,12 @@ public class OverlayRestImplTest extends RestTestFunctions { public void testAddDataOverlay() throws Exception { try { User admin = userService.getUserByLogin("admin"); - Project project = createProject("testFiles/model/sample.xml", projectId); + createProject("testFiles/model/sample.xml", projectId); Map<String, Object> result = overlayRest.addOverlay(projectId, "x", "desc", "s1", null, null, ColorSchemaType.GENERIC.name(), "true", admin); Gson gson = new Gson(); assertNotNull(gson.toJson(result)); - } catch (Exception e) { - e.printStackTrace(); - throw e; } finally { projectService.removeProject(projectDao.getProjectByProjectId(projectId), null, false); } @@ -53,19 +50,9 @@ public class OverlayRestImplTest extends RestTestFunctions { @Test(expected = QueryException.class) public void testAddDataOverlayWithInvalidName() throws Exception { try { - User admin = userService.getUserByLogin("admin"); - Project project = createProject("testFiles/model/sample.xml", projectId); - - overlayRest.addOverlay(projectId, - " ", - "desc", - "s1", - null, - null, - ColorSchemaType.GENERIC.name(), - "true", - null - ); + createProject("testFiles/model/sample.xml", projectId); + + overlayRest.addOverlay(projectId, " ", "desc", "s1", null, null, ColorSchemaType.GENERIC.name(), "true", null); } finally { projectService.removeProject(projectDao.getProjectByProjectId(projectId), null, false); } @@ -74,29 +61,16 @@ public class OverlayRestImplTest extends RestTestFunctions { @Test public void testUpdateDataOverlay() throws Exception { try { - User admin = userService.getUserByLogin("admin"); - Project project = createProject("testFiles/model/sample.xml", projectId); - - Map<String, Object> result = overlayRest.addOverlay( - projectId, - "x", - "desc", - "s1", - null, - null, - ColorSchemaType.GENERIC.name(), - "true", - null - ); + createProject("testFiles/model/sample.xml", projectId); + + Map<String, Object> result = overlayRest.addOverlay(projectId, "x", "desc", "s1", null, null, + ColorSchemaType.GENERIC.name(), "true", null); String id = result.get("idObject").toString(); Map<String, Object> data = new HashMap<>(); data.put("name", "xyz"); result = overlayRest.updateOverlay(id, data); assertNotNull(result); - } catch (Exception e) { - e.printStackTrace(); - throw e; } finally { projectService.removeProject(projectDao.getProjectByProjectId(projectId), null, false); } @@ -105,18 +79,10 @@ public class OverlayRestImplTest extends RestTestFunctions { @Test(expected = QueryException.class) public void testUpdateDataOverlayWithInvalidName() throws Exception { try { - User admin = userService.getUserByLogin("admin"); - Project project = createProject("testFiles/model/sample.xml", projectId); - - Map<String, Object> result = overlayRest.addOverlay(projectId, - "x", - "desc", - "s1", - null, - null, - ColorSchemaType.GENERIC.name(), - "true", - null); + createProject("testFiles/model/sample.xml", projectId); + + Map<String, Object> result = overlayRest.addOverlay(projectId, "x", "desc", "s1", null, null, + ColorSchemaType.GENERIC.name(), "true", null); String id = result.get("idObject").toString(); Map<String, Object> data = new HashMap<>(); diff --git a/rest-api/src/test/java/lcsb/mapviewer/api/users/UserRestImplTest.java b/rest-api/src/test/java/lcsb/mapviewer/api/users/UserRestImplTest.java index a5b889920a17eaa3af7974e4d1b22c29c26ce38f..6a6d678f9ddf71f329f134925454eb3dbd3a33b9 100644 --- a/rest-api/src/test/java/lcsb/mapviewer/api/users/UserRestImplTest.java +++ b/rest-api/src/test/java/lcsb/mapviewer/api/users/UserRestImplTest.java @@ -1,19 +1,10 @@ package lcsb.mapviewer.api.users; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import java.io.IOException; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; +import java.util.*; -import lcsb.mapviewer.model.user.User; -import lcsb.mapviewer.services.interfaces.IUserService; -import org.apache.logging.log4j.*; import org.junit.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.util.LinkedMultiValueMap; @@ -26,15 +17,10 @@ import com.google.gson.Gson; import lcsb.mapviewer.api.ObjectExistsException; import lcsb.mapviewer.api.RestTestFunctions; -import lcsb.mapviewer.common.Configuration; import lcsb.mapviewer.model.map.MiriamType; -import lcsb.mapviewer.model.user.AnnotatorParamDefinition; -import lcsb.mapviewer.model.user.UserGuiPreference; -import lcsb.mapviewer.model.user.annotator.AnnotatorConfigParameter; -import lcsb.mapviewer.model.user.annotator.AnnotatorInputParameter; -import lcsb.mapviewer.model.user.annotator.AnnotatorOutputParameter; -import lcsb.mapviewer.model.user.annotator.AnnotatorParameter; -import lcsb.mapviewer.model.user.annotator.BioEntityField; +import lcsb.mapviewer.model.user.*; +import lcsb.mapviewer.model.user.annotator.*; +import lcsb.mapviewer.services.interfaces.IUserService; public class UserRestImplTest extends RestTestFunctions { @@ -58,20 +44,13 @@ public class UserRestImplTest extends RestTestFunctions { public void tearDown() throws Exception { } - @Test + @Test(expected = ObjectExistsException.class) public void testAddExistingUser() throws Exception { - try { - User user = new User(); - user.setLogin(TEST_LOGIN); - user.setCryptedPassword("c"); - userService.addUser(user); - userRestImpl.addUser(TEST_LOGIN, new LinkedMultiValueMap<>()); - fail("Exception expected"); - } catch (ObjectExistsException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + User user = new User(); + user.setLogin(TEST_LOGIN); + user.setCryptedPassword(""); + userService.addUser(user); + userRestImpl.addUser(TEST_LOGIN, new LinkedMultiValueMap<>()); } @Test @@ -85,10 +64,6 @@ public class UserRestImplTest extends RestTestFunctions { dbUtils.setAutoFlush(true); Map<String, Object> data = deserialize(userRestImpl.getUser(TEST_LOGIN, "preferences")); userRestImpl.updatePreferences(TEST_LOGIN, (Map<String, Object>) data.get("preferences")); - - } catch (Exception e) { - e.printStackTrace(); - throw e; } finally { dbUtils.setAutoFlush(false); } @@ -104,104 +79,63 @@ public class UserRestImplTest extends RestTestFunctions { @Test public void testGetUsers() throws Exception { - try { - Object response = userRestImpl.getUsers(""); - assertNotNull(response); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Object response = userRestImpl.getUsers(""); + assertNotNull(response); } @Test public void testParseInputField() throws Exception { - try { - AnnotatorInputParameter object = userRestImpl.parseInputParameter( - userRestImpl.prepareInputParameter(new AnnotatorInputParameter(BioEntityField.ABBREVIATION))); - assertNotNull(object); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + AnnotatorInputParameter object = userRestImpl.parseInputParameter( + userRestImpl.prepareInputParameter(new AnnotatorInputParameter(BioEntityField.ABBREVIATION))); + assertNotNull(object); } @Test public void testParseInputAnnotation() throws Exception { - try { - AnnotatorInputParameter object = userRestImpl.parseInputParameter( - userRestImpl.prepareInputParameter(new AnnotatorInputParameter(MiriamType.BiGG_COMPARTMENT))); - assertNotNull(object); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + AnnotatorInputParameter object = userRestImpl.parseInputParameter( + userRestImpl.prepareInputParameter(new AnnotatorInputParameter(MiriamType.BiGG_COMPARTMENT))); + assertNotNull(object); } @Test public void testParseOutputField() throws Exception { - try { - AnnotatorParameter object = userRestImpl.parseOutputParameter( - userRestImpl.prepareOutputParameter(new AnnotatorOutputParameter(BioEntityField.ABBREVIATION))); - assertNotNull(object); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + AnnotatorParameter object = userRestImpl.parseOutputParameter( + userRestImpl.prepareOutputParameter(new AnnotatorOutputParameter(BioEntityField.ABBREVIATION))); + assertNotNull(object); } @Test public void testParseOutputAnnotation() throws Exception { - try { - AnnotatorParameter object = userRestImpl.parseOutputParameter( - userRestImpl.prepareOutputParameter(new AnnotatorOutputParameter(MiriamType.BiGG_COMPARTMENT))); - assertNotNull(object); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + AnnotatorParameter object = userRestImpl.parseOutputParameter( + userRestImpl.prepareOutputParameter(new AnnotatorOutputParameter(MiriamType.BiGG_COMPARTMENT))); + assertNotNull(object); } @Test public void testParseConfigAnnotation() throws Exception { - try { - AnnotatorParameter object = userRestImpl.parseConfigParameter( - userRestImpl.prepareConfigParameter( - new AnnotatorConfigParameter(AnnotatorParamDefinition.KEGG_ORGANISM_IDENTIFIER, null))); - assertNotNull(object); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + AnnotatorParameter object = userRestImpl.parseConfigParameter( + userRestImpl.prepareConfigParameter( + new AnnotatorConfigParameter(AnnotatorParamDefinition.KEGG_ORGANISM_IDENTIFIER, null))); + assertNotNull(object); } @Test public void testPrepareGuiPreferencesSimple() throws Exception { - try { - Map<String, Object> response = userRestImpl.prepareGuiPreferences(new HashSet<>()); - assertNotNull(response); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Map<String, Object> response = userRestImpl.prepareGuiPreferences(new HashSet<>()); + assertNotNull(response); } @Test public void testPrepareGuiPreferencesWithOption() throws Exception { - try { - Set<UserGuiPreference> guiPreferences = new HashSet<>(); - UserGuiPreference option = new UserGuiPreference(); - option.setKey("TestKey"); - option.setValue("TestValue"); - guiPreferences.add(option); - - Map<String, Object> response = userRestImpl.prepareGuiPreferences(guiPreferences); - assertNotNull(response); - assertEquals("TestValue", response.get(option.getKey())); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Set<UserGuiPreference> guiPreferences = new HashSet<>(); + UserGuiPreference option = new UserGuiPreference(); + option.setKey("TestKey"); + option.setValue("TestValue"); + guiPreferences.add(option); + + Map<String, Object> response = userRestImpl.prepareGuiPreferences(guiPreferences); + assertNotNull(response); + assertEquals("TestValue", response.get(option.getKey())); } } diff --git a/service/src/main/java/lcsb/mapviewer/services/overlay/ChebiTreeRow.java b/service/src/main/java/lcsb/mapviewer/services/overlay/ChebiTreeRow.java deleted file mode 100644 index 0a023e2e13424166f2973ff0eeeb7288c67044a1..0000000000000000000000000000000000000000 --- a/service/src/main/java/lcsb/mapviewer/services/overlay/ChebiTreeRow.java +++ /dev/null @@ -1,125 +0,0 @@ -package lcsb.mapviewer.services.overlay; - -import java.io.Serializable; - -/** - * This object is used for representing row of object in chebi ontology in the - * client side Primefaces p:treeTable object. - * - * @author Piotr Gawron - * - */ -public class ChebiTreeRow implements Serializable { - /** - * - */ - private static final long serialVersionUID = 1L; - - /** - * Name of the chebi entity. - */ - private String name; - - /** - * Identifier of chebi entity. - */ - private String id; - - /** - * Link to the chebi entity in chebi webpage. - */ - private String link; - - /** - * Relation associated with this entity. - */ - private String relationType; - - /** - * Default constructor. - * - * @param name - * Name of the chebi entity - * @param id - * Identifier of chebi entity - * @param link - * Link to the chebi entity in chebi webpage - * @param relationType - * Relation associated with this entity - */ - public ChebiTreeRow(String name, String id, String link, String relationType) { - this.name = name; - this.id = id; - this.link = link; - this.relationType = relationType; - } - - /** - * @return the name - * @see #name - */ - public String getName() { - return name; - } - - /** - * @param name - * the name to set - * @see #name - */ - public void setName(String name) { - this.name = name; - } - - /** - * @return the id - * @see #id - */ - public String getId() { - return id; - } - - /** - * @param id - * the id to set - * @see #id - */ - public void setId(String id) { - this.id = id; - } - - /** - * @return the link - * @see #link - */ - public String getLink() { - return link; - } - - /** - * @param link - * the link to set - * @see #link - */ - public void setLink(String link) { - this.link = link; - } - - /** - * @return the relationType - * @see #relationType - */ - public String getRelationType() { - return relationType; - } - - /** - * @param relationType - * the relationType to set - * @see #relationType - */ - public void setRelationType(String relationType) { - this.relationType = relationType; - } - -} diff --git a/service/src/main/java/lcsb/mapviewer/services/overlay/IconManager.java b/service/src/main/java/lcsb/mapviewer/services/overlay/IconManager.java deleted file mode 100644 index 7cf52eb49e20d85402bcfe2770b33f3e1622342c..0000000000000000000000000000000000000000 --- a/service/src/main/java/lcsb/mapviewer/services/overlay/IconManager.java +++ /dev/null @@ -1,144 +0,0 @@ -package lcsb.mapviewer.services.overlay; - -import org.apache.commons.lang3.mutable.MutableInt; - -import lcsb.mapviewer.common.Configuration; - -/** - * This class return links to icons used by the client. It might be good idea to - * move part of the functionality to client side as server shouldn't decide - * about representation layer. - * - * @author Piotr Gawron - * - */ -public final class IconManager { - /** - * Max index of the image. - */ - private static final int MAX_INDEX = 99; - - /** - * Colors available for bubble icons. - */ - private String[] colors = { "red", "blue", "green", "purple", "yellow", "pink", "paleblue", "brown", "orange" }; - - /** - * Singelton. - */ - private static IconManager manager; - - /** - * Default singleton constructor. - */ - private IconManager() { - - } - - /** - * Returns only available instance of this class. - * - * @return singletone instance - */ - public static IconManager getInstance() { - if (manager == null) { - manager = new IconManager(); - } - return manager; - } - - /** - * Returns path to the search icon with the given index. - * - * @param index - * identifier of the icon - * @param type - * type of the icon to be generated - * @param colorSet - * number of the color set that should be used in the generasted icon - * (number is influenced by {@link IconType#startingColorSet} - * - * @return path to the icon - */ - public String getIconForIndex(MutableInt index, IconType type, int colorSet) { - return getIconForIndex(index.toInteger(), type, colorSet); - } - - /** - * Returns path to the search icon with the given index. - * - * @param index - * identifier of the icon - * @param type - * type of the icon to be generated - * @param colorSet - * number of the color set that should be used in the generasted icon - * (number is influenced by {@link IconType#startingColorSet} - * - * @return path to the icon - */ - public String getIconForIndex(int index, IconType type, int colorSet) { - String color = normalizeColor(colorSet + type.getStartingColorSet()); - index = normalizeIndex(index); - String result = "marker/" + type.getIconFileSystemName() + "/" + type.getIconFileSystemName() + "_" + color + "_" + index + ".png"; - return result; - } - - /** - * Returns index of the icon that is not out of the range. - * - * @param index - * original index - * @return index of the icon that is not out of the range - */ - public int normalizeIndex(int index) { - return (index % MAX_INDEX) + 1; - } - - /** - * Returns color set of the icon that is not out of the range. - * - * @param set - * original index of the color set - * @return index of the color set that is not out of the range - */ - private String normalizeColor(int set) { - return colors[Math.abs(set % colors.length)]; - } - - /** - * Returns path to empty icon. - * - * @return path to empty icon - */ - public String getEmpyIcon() { - return "marker/empty.png"; - } - - /** - * Returns path to delete icon. - * - * @return path to delete icon - */ - public String getDeleteIcon() { - return "icons/delete.png"; - } - - /** - * Returns path to icon that indicate similarity search. - * - * @return path to icon that indicate similarity search - */ - public String getSimilarIcon() { - return "icons/gunsight.png"; - } - - /** - * Returns path to comment icon. - * - * @return path to comment icon - */ - public String getCommentIcon() { - return "icons/comment.png?v="+Configuration.getSystemBuildVersion(null); - } -} diff --git a/service/src/main/java/lcsb/mapviewer/services/overlay/IconType.java b/service/src/main/java/lcsb/mapviewer/services/overlay/IconType.java deleted file mode 100644 index ef96af73c46ddd892f4799c782e47d2f6ebeaf77..0000000000000000000000000000000000000000 --- a/service/src/main/java/lcsb/mapviewer/services/overlay/IconType.java +++ /dev/null @@ -1,68 +0,0 @@ -package lcsb.mapviewer.services.overlay; - -/** - * Type of the icon that is returned to the client. - * - * @author Piotr Gawron - * - */ -public enum IconType { - - /** - * Search result. - */ - SEARCH("marker", 0), - - /** - * Result of the drug search. - */ - DRUG("drug", 5), - /** - * Result of the drug search. - */ - CHEMICAL("ball", 1), - /** - * Result of the drug search. - */ - MI_RNA("target", 2); - - /** - * Name of the icons in filesystem. - */ - private String iconFileSystemName; - - /** - * Color set starting index from which generasted icons should start for given - * type. - */ - private int startingColorSet; - - /** - * Default constructor. - * - * @param name - * {@link #iconFileSystemName} - * @param startColorSet - * {@link #startingColorSet} - */ - IconType(String name, int startColorSet) { - this.iconFileSystemName = name; - this.startingColorSet = startColorSet; - } - - /** - * @return the iconFileSystemName - * @see #iconFileSystemName - */ - public String getIconFileSystemName() { - return iconFileSystemName; - } - - /** - * @return the startingColorSet - * @see #startingColorSet - */ - public int getStartingColorSet() { - return startingColorSet; - } -} diff --git a/service/src/test/java/lcsb/mapviewer/services/ServiceTestFunctions.java b/service/src/test/java/lcsb/mapviewer/services/ServiceTestFunctions.java index 60fddfd73959e50564066e2707383f0e26f535c7..0696927d2ed6d9c6bdf564b4518f167f34713e4c 100644 --- a/service/src/test/java/lcsb/mapviewer/services/ServiceTestFunctions.java +++ b/service/src/test/java/lcsb/mapviewer/services/ServiceTestFunctions.java @@ -2,15 +2,12 @@ package lcsb.mapviewer.services; import java.io.File; import java.io.IOException; -import java.util.HashMap; -import java.util.List; -import java.util.Map; +import java.util.*; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.core.LogEvent; -import org.junit.After; -import org.junit.Before; +import org.junit.*; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.crypto.password.PasswordEncoder; @@ -22,6 +19,7 @@ import org.springframework.transaction.annotation.Transactional; import lcsb.mapviewer.annotation.services.DrugbankHTMLParser; import lcsb.mapviewer.annotation.services.ModelAnnotator; import lcsb.mapviewer.common.MinervaLoggerAppender; +import lcsb.mapviewer.common.UnitTestFailedWatcher; import lcsb.mapviewer.converter.ConverterParams; import lcsb.mapviewer.converter.model.celldesigner.CellDesignerXmlParser; import lcsb.mapviewer.model.map.model.Model; @@ -32,13 +30,7 @@ import lcsb.mapviewer.persist.dao.map.CommentDao; import lcsb.mapviewer.persist.dao.map.ModelDao; import lcsb.mapviewer.persist.dao.map.statistics.SearchHistoryDao; import lcsb.mapviewer.persist.dao.user.UserDao; -import lcsb.mapviewer.services.interfaces.ICommentService; -import lcsb.mapviewer.services.interfaces.IConfigurationService; -import lcsb.mapviewer.services.interfaces.ILayoutService; -import lcsb.mapviewer.services.interfaces.IModelService; -import lcsb.mapviewer.services.interfaces.IProjectService; -import lcsb.mapviewer.services.interfaces.ISearchService; -import lcsb.mapviewer.services.interfaces.IUserService; +import lcsb.mapviewer.services.interfaces.*; import lcsb.mapviewer.services.search.chemical.IChemicalService; import lcsb.mapviewer.services.search.drug.IDrugService; @@ -47,6 +39,10 @@ import lcsb.mapviewer.services.search.drug.IDrugService; @ContextConfiguration(classes = SpringServiceTestConfig.class) @RunWith(SpringJUnit4ClassRunner.class) public abstract class ServiceTestFunctions { + + @Rule + public UnitTestFailedWatcher unitTestFailedWatcher = new UnitTestFailedWatcher(); + private Logger logger = LogManager.getLogger(ServiceTestFunctions.class); @Autowired diff --git a/service/src/test/java/lcsb/mapviewer/services/impl/CommentServiceTest.java b/service/src/test/java/lcsb/mapviewer/services/impl/CommentServiceTest.java index 1f2d2644ce98d50a053a22d635f12f65fa21cbbb..83363c520ecde7089f58c73fc904db25dfae170d 100644 --- a/service/src/test/java/lcsb/mapviewer/services/impl/CommentServiceTest.java +++ b/service/src/test/java/lcsb/mapviewer/services/impl/CommentServiceTest.java @@ -1,17 +1,14 @@ package lcsb.mapviewer.services.impl; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.Assert.*; import java.awt.geom.Point2D; import java.util.List; import java.util.Set; -import org.apache.logging.log4j.*; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.junit.*; import org.springframework.test.annotation.Rollback; import lcsb.mapviewer.model.Project; @@ -32,159 +29,111 @@ public class CommentServiceTest extends ServiceTestFunctions { @Before public void setUp() throws Exception { - try { - dbUtils.setAutoFlush(true); - project = projectDao.getProjectByProjectId(projectId); - if (project != null) { - projectDao.delete(project); - } - project = new Project(); - project.setProjectId(projectId); - model = getModelForFile("testFiles/centeredAnchorInModifier.xml", false); - model.setTileSize(128); - Set<Element> aliases = model.getElements(); - alias = null; - alias2 = null; - for (Element nAlias : aliases) { - alias2 = alias; - alias = nAlias; - } - project.addModel(model); - projectDao.add(project); - - projectDao.evict(project); - modelDao.evict(model); - - project = projectDao.getById(project.getId()); - model = new ModelFullIndexed(modelDao.getLastModelForProjectIdentifier(project.getProjectId(), false)); - } catch (Exception e) { - e.printStackTrace(); + dbUtils.setAutoFlush(true); + project = projectDao.getProjectByProjectId(projectId); + if (project != null) { + projectDao.delete(project); + } + project = new Project(); + project.setProjectId(projectId); + model = getModelForFile("testFiles/centeredAnchorInModifier.xml", false); + model.setTileSize(128); + Set<Element> aliases = model.getElements(); + alias = null; + alias2 = null; + for (Element nAlias : aliases) { + alias2 = alias; + alias = nAlias; } + project.addModel(model); + projectDao.add(project); + + projectDao.evict(project); + modelDao.evict(model); + + project = projectDao.getById(project.getId()); + model = new ModelFullIndexed(modelDao.getLastModelForProjectIdentifier(project.getProjectId(), false)); } @After public void tearDown() throws Exception { - try { - projectDao.delete(project); - } catch (Exception e) { - e.printStackTrace(); - } + projectDao.delete(project); } @Test public void testGetAgregatedComments() throws Exception { - try { - commentService.addComment("John Doe", "a@a.pl", "Conteneta 1", model, new Point2D.Double(0, 1), alias, false, - model); - commentService.addComment("John Doe", "a@a.pl", "Contenetb 2", model, new Point2D.Double(0, 2), alias, false, - model); - commentService.addComment("John Doe", "a@a.pl", "Contenetc 3", model, new Point2D.Double(0, 3), alias2, false, - model); - commentService.addComment("John Doe", "a@a.pl", "Contenetc 4", model, new Point2D.Double(0, 4), null, false, - model); - commentService.addComment("John Doe", "a@a.pl", "Contenetc 5", model, new Point2D.Double(0, 5), null, false, - model); - CommentService service = new CommentService(null, null, null, null); - service.setCommentDao(commentDao); - List<List<Comment>> comments = service.getAgregatedComments(model, null); - assertEquals(4, comments.size()); - int size = 0; - for (List<Comment> list : comments) { - size += list.size(); - } - assertEquals(5, size); - - List<Comment> allComments = commentDao.getCommentByModel(model, null, null); - assertEquals(5, allComments.size()); - for (Comment comment : allComments) { - commentDao.delete(comment); - } - } catch (Exception e) { - e.printStackTrace(); - throw e; + commentService.addComment("John Doe", "a@a.pl", "Conteneta 1", model, new Point2D.Double(0, 1), alias, false, + model); + commentService.addComment("John Doe", "a@a.pl", "Contenetb 2", model, new Point2D.Double(0, 2), alias, false, + model); + commentService.addComment("John Doe", "a@a.pl", "Contenetc 3", model, new Point2D.Double(0, 3), alias2, false, + model); + commentService.addComment("John Doe", "a@a.pl", "Contenetc 4", model, new Point2D.Double(0, 4), null, false, + model); + commentService.addComment("John Doe", "a@a.pl", "Contenetc 5", model, new Point2D.Double(0, 5), null, false, + model); + CommentService service = new CommentService(null, null, null, null); + service.setCommentDao(commentDao); + List<List<Comment>> comments = service.getAgregatedComments(model, null); + assertEquals(4, comments.size()); + int size = 0; + for (List<Comment> list : comments) { + size += list.size(); + } + assertEquals(5, size); + + List<Comment> allComments = commentDao.getCommentByModel(model, null, null); + assertEquals(5, allComments.size()); + for (Comment comment : allComments) { + commentDao.delete(comment); } } @Test public void testAddComment() throws Exception { - try { - - long counter = commentService.getCommentCount(); - Comment feedback = commentService.addComment("a", "b", "c", model, new Point2D.Double(0, 0), null, false, model); - long counter2 = commentService.getCommentCount(); - assertEquals(counter + 1, counter2); - commentDao.delete(feedback); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + long counter = commentService.getCommentCount(); + Comment feedback = commentService.addComment("a", "b", "c", model, new Point2D.Double(0, 0), null, false, model); + long counter2 = commentService.getCommentCount(); + assertEquals(counter + 1, counter2); + commentDao.delete(feedback); } @Test public void testAddCommentForReaction() throws Exception { - try { - - long counter = commentService.getCommentCount(); - Comment feedback = commentService.addComment("a", "b", "c", model, new Point2D.Double(0, 0), - model.getReactions().iterator().next(), false, model); - long counter2 = commentService.getCommentCount(); - assertEquals(counter + 1, counter2); - commentDao.delete(feedback); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + long counter = commentService.getCommentCount(); + Comment feedback = commentService.addComment("a", "b", "c", model, new Point2D.Double(0, 0), + model.getReactions().iterator().next(), false, model); + long counter2 = commentService.getCommentCount(); + assertEquals(counter + 1, counter2); + commentDao.delete(feedback); } @Test public void testAddCommentForAlias() throws Exception { - try { - Element alias = model.getElementByElementId("sa1"); - long counter = commentService.getCommentCount(); - Comment feedback = commentService.addComment("a", "b", "c", model, new Point2D.Double(0, 0), alias, false, model); - long counter2 = commentService.getCommentCount(); - assertEquals(counter + 1, counter2); - commentDao.delete(feedback); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Element alias = model.getElementByElementId("sa1"); + long counter = commentService.getCommentCount(); + Comment feedback = commentService.addComment("a", "b", "c", model, new Point2D.Double(0, 0), alias, false, model); + long counter2 = commentService.getCommentCount(); + assertEquals(counter + 1, counter2); + commentDao.delete(feedback); } @Test public void testComparePointCommentId() throws Exception { - try { - CommentService cs = new CommentService(null, null, null, null); - assertTrue(cs.equalPoints("Point2D.Double[117.685546875, 204.6923828125001]", "(117.69, 204.69)")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + CommentService cs = new CommentService(null, null, null, null); + assertTrue(cs.equalPoints("Point2D.Double[117.685546875, 204.6923828125001]", "(117.69, 204.69)")); } @Test public void testComparePointCommentId2() throws Exception { - try { - CommentService cs = new CommentService(null, null, null, null); - assertFalse(cs.equalPoints("Point2D.Double[118.685546875, 204.6923828125001]", "(117.69, 204.69)")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + CommentService cs = new CommentService(null, null, null, null); + assertFalse(cs.equalPoints("Point2D.Double[118.685546875, 204.6923828125001]", "(117.69, 204.69)")); } @Test public void testComparePointCommentId3() throws Exception { - try { - CommentService cs = new CommentService(null, null, null, null); - assertFalse(cs.equalPoints("Point2D.Double[117.685546875, 205.6923828125001]", "(117.69, 204.69)")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + CommentService cs = new CommentService(null, null, null, null); + assertFalse(cs.equalPoints("Point2D.Double[117.685546875, 205.6923828125001]", "(117.69, 204.69)")); } } diff --git a/service/src/test/java/lcsb/mapviewer/services/impl/ConfigurationServiceTest.java b/service/src/test/java/lcsb/mapviewer/services/impl/ConfigurationServiceTest.java index 411b8100bde0b31e0d7d87ac885faa791766e9ff..c70c9c96051a76851db9ed01ca9179f25740f68f 100644 --- a/service/src/test/java/lcsb/mapviewer/services/impl/ConfigurationServiceTest.java +++ b/service/src/test/java/lcsb/mapviewer/services/impl/ConfigurationServiceTest.java @@ -35,89 +35,55 @@ public class ConfigurationServiceTest extends ServiceTestFunctions { @Test public void testGetUpdate() throws Exception { - try { - String address = configurationService.getConfigurationValue(ConfigurationElementType.EMAIL_ADDRESS); - configurationService.deleteConfigurationValue(ConfigurationElementType.EMAIL_ADDRESS); - String newAddress = configurationService.getConfigurationValue(ConfigurationElementType.EMAIL_ADDRESS); - assertEquals(ConfigurationElementType.EMAIL_ADDRESS.getDefaultValue(), newAddress); - configurationService.setConfigurationValue(ConfigurationElementType.EMAIL_ADDRESS, "hello@world"); - newAddress = configurationService.getConfigurationValue(ConfigurationElementType.EMAIL_ADDRESS); - assertEquals("hello@world", newAddress); - - configurationService.setConfigurationValue(ConfigurationElementType.EMAIL_ADDRESS, address); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String address = configurationService.getConfigurationValue(ConfigurationElementType.EMAIL_ADDRESS); + configurationService.deleteConfigurationValue(ConfigurationElementType.EMAIL_ADDRESS); + String newAddress = configurationService.getConfigurationValue(ConfigurationElementType.EMAIL_ADDRESS); + assertEquals(ConfigurationElementType.EMAIL_ADDRESS.getDefaultValue(), newAddress); + configurationService.setConfigurationValue(ConfigurationElementType.EMAIL_ADDRESS, "hello@world"); + newAddress = configurationService.getConfigurationValue(ConfigurationElementType.EMAIL_ADDRESS); + assertEquals("hello@world", newAddress); + + configurationService.setConfigurationValue(ConfigurationElementType.EMAIL_ADDRESS, address); } @Test public void testList() throws Exception { - try { - List<ConfigurationOption> list = configurationService.getAllValues(); - assertEquals(ConfigurationElementType.values().length, list.size()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + List<ConfigurationOption> list = configurationService.getAllValues(); + assertEquals(ConfigurationElementType.values().length, list.size()); } @Test public void testGetSystemVersion() throws Exception { - try { - FrameworkVersion view = configurationService.getSystemVersion("testFiles/gitVersionTest/testNormal/"); - assertNotNull(view); - assertEquals("100", view.getGitVersion()); - assertEquals("202", view.getVersion()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + FrameworkVersion view = configurationService.getSystemVersion("testFiles/gitVersionTest/testNormal/"); + assertNotNull(view); + assertEquals("100", view.getGitVersion()); + assertEquals("202", view.getVersion()); } @Test public void testGetSystemVersion2() throws Exception { - try { - FrameworkVersion view = configurationService.getSystemVersion("testFiles/gitVersionTest/testModified/"); - assertNotNull(view); - assertEquals("100:105", view.getGitVersion()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + FrameworkVersion view = configurationService.getSystemVersion("testFiles/gitVersionTest/testModified/"); + assertNotNull(view); + assertEquals("100:105", view.getGitVersion()); } @Test public void testGetSystemVersion3() throws Exception { - try { - FrameworkVersion view = configurationService.getSystemVersion("testFiles/gitVersionTest/testCorrectSvn/"); - assertNotNull(view); - assertEquals("117", view.getGitVersion()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + FrameworkVersion view = configurationService.getSystemVersion("testFiles/gitVersionTest/testCorrectSvn/"); + assertNotNull(view); + assertEquals("117", view.getGitVersion()); } - @Test public void testGetConfiguratioElemntForPrivilege() throws Exception { - try { - for (PrivilegeType type : PrivilegeType.values()) { - ConfigurationOption value = configurationService.getValue(type); - if (Project.class.equals(type.getPrivilegeObjectType()) || type.equals(PrivilegeType.CAN_CREATE_OVERLAYS)) { - assertNotNull("No default value for privilege " + type.getDescription(), value); - assertNotNull(value.getValue()); - } else { - assertNull(value); - } + for (PrivilegeType type : PrivilegeType.values()) { + ConfigurationOption value = configurationService.getValue(type); + if (Project.class.equals(type.getPrivilegeObjectType()) || type.equals(PrivilegeType.CAN_CREATE_OVERLAYS)) { + assertNotNull("No default value for privilege " + type.getDescription(), value); + assertNotNull(value.getValue()); + } else { + assertNull(value); } - } catch (Exception e) { - e.printStackTrace(); - throw e; } } diff --git a/service/src/test/java/lcsb/mapviewer/services/impl/CustomMd5PasswordEncoderTest.java b/service/src/test/java/lcsb/mapviewer/services/impl/CustomMd5PasswordEncoderTest.java index f4bab0d9ea68c6f5b1501a6e152e72363b2299a0..427d3ccbf1637356915b9683daea446021aa03df 100644 --- a/service/src/test/java/lcsb/mapviewer/services/impl/CustomMd5PasswordEncoderTest.java +++ b/service/src/test/java/lcsb/mapviewer/services/impl/CustomMd5PasswordEncoderTest.java @@ -22,22 +22,12 @@ public class CustomMd5PasswordEncoderTest extends ServiceTestFunctions { @Test public void testEncode() { - try { - assertEquals(hash, passwordEncoder.encode(passwd)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(hash, passwordEncoder.encode(passwd)); } @Test public void testMatch() { - try { - assertTrue(passwordEncoder.matches(passwd, hash)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertTrue(passwordEncoder.matches(passwd, hash)); } } diff --git a/service/src/test/java/lcsb/mapviewer/services/impl/LayoutServiceTest.java b/service/src/test/java/lcsb/mapviewer/services/impl/LayoutServiceTest.java index e55fa4412cea2c0ea6a0bb6d32b7cae4f9109d02..731e4ad090f1532f3c3a0bca5f8006e3738f90cb 100644 --- a/service/src/test/java/lcsb/mapviewer/services/impl/LayoutServiceTest.java +++ b/service/src/test/java/lcsb/mapviewer/services/impl/LayoutServiceTest.java @@ -1,25 +1,16 @@ package lcsb.mapviewer.services.impl; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.Assert.*; import java.awt.Color; -import java.io.ByteArrayInputStream; -import java.io.File; -import java.io.FileInputStream; +import java.io.*; import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; -import java.util.Map; +import java.util.*; import org.apache.commons.io.IOUtils; -import org.apache.logging.log4j.*; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.junit.*; import org.mockito.Mockito; import org.springframework.beans.factory.annotation.Autowired; @@ -29,15 +20,8 @@ import lcsb.mapviewer.common.TextFileUtils; import lcsb.mapviewer.converter.ConverterParams; import lcsb.mapviewer.converter.model.celldesigner.CellDesignerXmlParser; import lcsb.mapviewer.model.Project; -import lcsb.mapviewer.model.map.layout.ColorSchema; -import lcsb.mapviewer.model.map.layout.ColorSchemaType; -import lcsb.mapviewer.model.map.layout.DataOverlayImageLayer; -import lcsb.mapviewer.model.map.layout.GeneVariationColorSchema; -import lcsb.mapviewer.model.map.layout.Layout; -import lcsb.mapviewer.model.map.layout.LayoutStatus; -import lcsb.mapviewer.model.map.model.Model; -import lcsb.mapviewer.model.map.model.ModelSubmodelConnection; -import lcsb.mapviewer.model.map.model.SubmodelType; +import lcsb.mapviewer.model.map.layout.*; +import lcsb.mapviewer.model.map.model.*; import lcsb.mapviewer.model.user.User; import lcsb.mapviewer.persist.dao.map.LayoutDao; import lcsb.mapviewer.services.ServiceTestFunctions; @@ -118,120 +102,91 @@ public class LayoutServiceTest extends ServiceTestFunctions { @Test public void testGetCustomLayouts() throws Exception { - try { - List<Layout> layouts = layoutService.getLayoutsByProject(project); - assertNotNull(layouts); - assertEquals(0, layouts.size()); - - CreateLayoutParams params = new CreateLayoutParams().name("Test"). - directory("testDir"). - project(project). - colorInputStream(new FileInputStream("testFiles/enricoData/ge001.txt")). - user(user); - Layout row = layoutService.createLayout(params); + List<Layout> layouts = layoutService.getLayoutsByProject(project); + assertNotNull(layouts); + assertEquals(0, layouts.size()); - assertNotNull(row); - assertTrue(row.getId() > 0); + CreateLayoutParams params = new CreateLayoutParams().name("Test").directory("testDir").project(project) + .colorInputStream(new FileInputStream("testFiles/enricoData/ge001.txt")).user(user); + Layout row = layoutService.createLayout(params); - layouts = layoutService.getLayoutsByProject(project); - assertEquals(1, layouts.size()); + assertNotNull(row); + assertTrue(row.getId() > 0); - layoutService.removeLayout(row, null); + layouts = layoutService.getLayoutsByProject(project); + assertEquals(1, layouts.size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + layoutService.removeLayout(row, null); } @Test public void testUpdateLayout() throws Exception { - try { - List<Layout> layouts = layoutService.getLayoutsByProject(project); - assertNotNull(layouts); - assertEquals(0, layouts.size()); + List<Layout> layouts = layoutService.getLayoutsByProject(project); + assertNotNull(layouts); + assertEquals(0, layouts.size()); - CreateLayoutParams params = new CreateLayoutParams().name("Test"). - directory("testDir"). - project(project). - colorInputStream(new FileInputStream("testFiles/enricoData/ge001.txt")). - user(user); - Layout row = layoutService.createLayout(params); + CreateLayoutParams params = new CreateLayoutParams().name("Test").directory("testDir").project(project) + .colorInputStream(new FileInputStream("testFiles/enricoData/ge001.txt")).user(user); + Layout row = layoutService.createLayout(params); - layouts = layoutService.getLayoutsByProject(project); - assertEquals(1, layouts.size()); - assertEquals("Test", layouts.get(0).getTitle()); + layouts = layoutService.getLayoutsByProject(project); + assertEquals(1, layouts.size()); + assertEquals("Test", layouts.get(0).getTitle()); - row.setTitle("New name"); + row.setTitle("New name"); - layoutService.updateLayout(row); + layoutService.updateLayout(row); - layouts = layoutService.getLayoutsByProject(project); - assertEquals(1, layouts.size()); - assertEquals("New name", layouts.get(0).getTitle()); + layouts = layoutService.getLayoutsByProject(project); + assertEquals(1, layouts.size()); + assertEquals("New name", layouts.get(0).getTitle()); - layoutService.removeLayout(row, null); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + layoutService.removeLayout(row, null); } @Test(timeout = 15000) public void testCreateAsyncLayout() throws Exception { - try { - List<Layout> layouts = layoutService.getLayoutsByProject(project); - assertNotNull(layouts); - assertEquals(0, layouts.size()); - - CreateLayoutParams params = new CreateLayoutParams().name("Test"). - directory("testDir"). - project(project). - colorInputStream(new FileInputStream("testFiles/enricoData/ge001.txt")). - user(user). - async(true); + List<Layout> layouts = layoutService.getLayoutsByProject(project); + assertNotNull(layouts); + assertEquals(0, layouts.size()); - long logCounter = getInfos().size(); - Layout row = layoutService.createLayout(params); + CreateLayoutParams params = new CreateLayoutParams().name("Test").directory("testDir").project(project) + .colorInputStream(new FileInputStream("testFiles/enricoData/ge001.txt")).user(user).async(true); - assertNotNull(row); - assertTrue(row.getId() > 0); + long logCounter = getInfos().size(); + Layout row = layoutService.createLayout(params); - Layout layoutDb = layoutDao.getById(row.getId()); - do { - Thread.sleep(200); - layoutDao.refresh(layoutDb); - } while (layoutDb.getStatus() != LayoutStatus.OK); + assertNotNull(row); + assertTrue(row.getId() > 0); - layouts = layoutService.getLayoutsByProject(project); - assertEquals(1, layouts.size()); + Layout layoutDb = layoutDao.getById(row.getId()); + do { + Thread.sleep(200); + layoutDao.refresh(layoutDb); + } while (layoutDb.getStatus() != LayoutStatus.OK); - long logCounter2 = getInfos().size(); - assertTrue("Log didn't appeard after creating layout", logCounter < logCounter2); + layouts = layoutService.getLayoutsByProject(project); + assertEquals(1, layouts.size()); - Layout layout = layouts.get(0); - logger.debug(layout.getStatus() + ", " + layout.getProgress()); + long logCounter2 = getInfos().size(); + assertTrue("Log didn't appeard after creating layout", logCounter < logCounter2); - assertFalse("Layout images weren't generated...", layout.getStatus().equals(LayoutStatus.NA)); + Layout layout = layouts.get(0); + logger.debug(layout.getStatus() + ", " + layout.getProgress()); - logCounter = getInfos().size(); - layoutService.removeLayout(layout, null); - logCounter2 = getInfos().size(); + assertFalse("Layout images weren't generated...", layout.getStatus().equals(LayoutStatus.NA)); - assertTrue("Log didn't appeard after removing layout", logCounter < logCounter2); + logCounter = getInfos().size(); + layoutService.removeLayout(layout, null); + logCounter2 = getInfos().size(); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertTrue("Log didn't appeard after removing layout", logCounter < logCounter2); } @Test public void testAddLayoutToComplexModel() throws Exception { Project localProject = new Project(); try { - CellDesignerXmlParser parser = new CellDesignerXmlParser(); Model localModel = parser.createModel(new ConverterParams().filename("testFiles/sample.xml")); Model localSubmodelModel = parser.createModel(new ConverterParams().filename("testFiles/sample.xml")); @@ -245,11 +200,8 @@ public class LayoutServiceTest extends ServiceTestFunctions { projectService.addProject(localProject); - CreateLayoutParams params = new CreateLayoutParams().name("Test"). - directory("testDir"). - project(localProject). - colorInputStream(new FileInputStream("testFiles/enricoData/ge001.txt")). - user(user); + CreateLayoutParams params = new CreateLayoutParams().name("Test").directory("testDir").project(localProject) + .colorInputStream(new FileInputStream("testFiles/enricoData/ge001.txt")).user(user); layoutService.createLayout(params); @@ -266,9 +218,6 @@ public class LayoutServiceTest extends ServiceTestFunctions { assertTrue(f1.exists()); } } - } catch (Exception e) { - e.printStackTrace(); - throw e; } finally { projectService.removeProject(localProject, null, false); } @@ -276,77 +225,55 @@ public class LayoutServiceTest extends ServiceTestFunctions { @Test public void testInputDataInLayout() throws Exception { - try { - List<Layout> layouts = layoutService.getLayoutsByProject(project); - assertNotNull(layouts); - assertEquals(0, layouts.size()); - - CreateLayoutParams params = new CreateLayoutParams().name("Test"). - directory("testDir"). - project(project). - colorInputStream(new FileInputStream("testFiles/enricoData/ge001.txt")). - user(user). - async(false); - - Layout row = layoutService.createLayout(params); - - assertNotNull(row); - assertTrue(row.getId() > 0); - assertNotNull(row.getInputData()); - byte[] inputData = row.getInputData().getFileContent(); - assertNotNull(inputData); - byte[] originalData = IOUtils.toByteArray(new FileInputStream("testFiles/enricoData/ge001.txt")); - assertEquals(new String(originalData, StandardCharsets.UTF_8), new String(inputData, StandardCharsets.UTF_8)); - - layoutService.removeLayout(row, null); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + List<Layout> layouts = layoutService.getLayoutsByProject(project); + assertNotNull(layouts); + assertEquals(0, layouts.size()); + + CreateLayoutParams params = new CreateLayoutParams().name("Test").directory("testDir").project(project) + .colorInputStream(new FileInputStream("testFiles/enricoData/ge001.txt")).user(user).async(false); + + Layout row = layoutService.createLayout(params); + + assertNotNull(row); + assertTrue(row.getId() > 0); + assertNotNull(row.getInputData()); + byte[] inputData = row.getInputData().getFileContent(); + assertNotNull(inputData); + byte[] originalData = IOUtils.toByteArray(new FileInputStream("testFiles/enricoData/ge001.txt")); + assertEquals(new String(originalData, StandardCharsets.UTF_8), new String(inputData, StandardCharsets.UTF_8)); + + layoutService.removeLayout(row, null); } @Test public void testGetLayoutAliases() throws Exception { - try { - List<Layout> layouts = layoutService.getLayoutsByProject(project); - assertNotNull(layouts); - assertEquals(0, layouts.size()); - - ByteArrayInputStream bais = new ByteArrayInputStream( - "name reactionIdentifier Color\ns1 #CC0000\ns2 #CCCC00\n re1 #CCCC00\n" - .getBytes(StandardCharsets.UTF_8)); - CreateLayoutParams params = new CreateLayoutParams().name("Test"). - directory("testDir"). - project(project). - colorInputStream(bais). - user(user). - async(false); + List<Layout> layouts = layoutService.getLayoutsByProject(project); + assertNotNull(layouts); + assertEquals(0, layouts.size()); - Layout row = layoutService.createLayout(params); + ByteArrayInputStream bais = new ByteArrayInputStream( + "name reactionIdentifier Color\ns1 #CC0000\ns2 #CCCC00\n re1 #CCCC00\n" + .getBytes(StandardCharsets.UTF_8)); + CreateLayoutParams params = new CreateLayoutParams().name("Test").directory("testDir").project(project) + .colorInputStream(bais).user(user).async(false); - List<?> result = layoutService.getAliasesForLayout(model, row.getId()); + Layout row = layoutService.createLayout(params); - assertTrue(result.size() > 0); + List<?> result = layoutService.getAliasesForLayout(model, row.getId()); - List<?> result2 = layoutService.getReactionsForLayout(model, row.getId()); + assertTrue(result.size() > 0); - assertEquals(1, result2.size()); + List<?> result2 = layoutService.getReactionsForLayout(model, row.getId()); - layoutService.removeLayout(row, null); + assertEquals(1, result2.size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + layoutService.removeLayout(row, null); } - @Test public void testGetLayoutAliasesForInvalidAlias() throws Exception { Project project = new Project("p_id"); try { - Model model = new CellDesignerXmlParser() .createModel(new ConverterParams().filename("testFiles/coloring/problematicModel2.xml")); @@ -354,11 +281,8 @@ public class LayoutServiceTest extends ServiceTestFunctions { projectService.addProject(project); FileInputStream fis = new FileInputStream("testFiles/coloring/problematicSchema2.txt"); - CreateLayoutParams params = new CreateLayoutParams().name("Test"). - directory("testDir"). - project(project). - colorInputStream(fis). - async(false); + CreateLayoutParams params = new CreateLayoutParams().name("Test").directory("testDir").project(project) + .colorInputStream(fis).async(false); ColorSchemaReader reader = new ColorSchemaReader(); final Collection<ColorSchema> schemas = reader.readColorSchema(params.getColorInputStream(), TextFileUtils.getHeaderParametersFromFile(params.getColorInputStream())); @@ -367,87 +291,58 @@ public class LayoutServiceTest extends ServiceTestFunctions { command.execute(); command.getModifiedElements(); - - } catch (Exception e) { - e.printStackTrace(); - throw e; } finally { projectDao.delete(project); } } + @Test public void testEmptyPreprareTableResultForGeneVariant() throws Exception { - try { - class CSR extends ColorSchemaReader { - public Collection<ColorSchemaColumn> getSetColorSchemaColumns(Collection<ColorSchema> schemas) { - List<ColorSchemaColumn> result = new ArrayList<ColorSchemaColumn>(); - for (ColorSchemaColumn csc : ColorSchemaColumn.values()) { - if (csc.getTypes().contains(ColorSchemaType.GENETIC_VARIANT)) { - result.add(csc); - } + class CSR extends ColorSchemaReader { + public Collection<ColorSchemaColumn> getSetColorSchemaColumns(Collection<ColorSchema> schemas) { + List<ColorSchemaColumn> result = new ArrayList<ColorSchemaColumn>(); + for (ColorSchemaColumn csc : ColorSchemaColumn.values()) { + if (csc.getTypes().contains(ColorSchemaType.GENETIC_VARIANT)) { + result.add(csc); } - return result; } + return result; } - ; - List<ColorSchema> schemas = new ArrayList<ColorSchema>(); - ColorSchema cs = new GeneVariationColorSchema(); - schemas.add(cs); - - LayoutService ls = new LayoutService(null, null, null, null); - String result = ls.prepareTableResult(schemas, new CSR()); - assertNotNull(result); - } catch (Exception e) { - e.printStackTrace(); - throw e; } - + ; + List<ColorSchema> schemas = new ArrayList<ColorSchema>(); + ColorSchema cs = new GeneVariationColorSchema(); + schemas.add(cs); + + LayoutService ls = new LayoutService(null, null, null, null); + String result = ls.prepareTableResult(schemas, new CSR()); + assertNotNull(result); } - @Test public void testDataOverlayWithType() throws Exception { - try { - String layoutId = "Test"; - CreateLayoutParams params = new CreateLayoutParams().name(layoutId). - directory("testDir"). - project(project). - colorInputStream(new FileInputStream("testFiles/coloring/gene_variants_without_type.txt")). - user(user).colorSchemaType(ColorSchemaType.GENETIC_VARIANT); - - Layout layout = layoutService.createLayout(params); - Map<Object, ColorSchema> result = layoutService.getElementsForLayout(model, layout.getId()); - assertNotNull(result); - layoutService.removeLayout(layout, null); - - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String layoutId = "Test"; + CreateLayoutParams params = new CreateLayoutParams().name(layoutId).directory("testDir").project(project) + .colorInputStream(new FileInputStream("testFiles/coloring/gene_variants_without_type.txt")).user(user) + .colorSchemaType(ColorSchemaType.GENETIC_VARIANT); + + Layout layout = layoutService.createLayout(params); + Map<Object, ColorSchema> result = layoutService.getElementsForLayout(model, layout.getId()); + assertNotNull(result); + layoutService.removeLayout(layout, null); } @Test public void testDataOverlayWithConflictingType() throws Exception { - try { - String layoutId = "Test"; - CreateLayoutParams params = new CreateLayoutParams().name(layoutId). - directory("testDir"). - project(project). - colorInputStream(new FileInputStream("testFiles/coloring/gene_variants.txt")). - user(user).colorSchemaType(ColorSchemaType.GENERIC); - - Layout layout = layoutService.createLayout(params); - Map<Object, ColorSchema> result = layoutService.getElementsForLayout(model, layout.getId()); - assertNotNull(result); - layoutService.removeLayout(layout, null); - - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String layoutId = "Test"; + CreateLayoutParams params = new CreateLayoutParams().name(layoutId).directory("testDir").project(project) + .colorInputStream(new FileInputStream("testFiles/coloring/gene_variants.txt")).user(user) + .colorSchemaType(ColorSchemaType.GENERIC); + + Layout layout = layoutService.createLayout(params); + Map<Object, ColorSchema> result = layoutService.getElementsForLayout(model, layout.getId()); + assertNotNull(result); + layoutService.removeLayout(layout, null); } - } diff --git a/service/src/test/java/lcsb/mapviewer/services/impl/LdapServiceTest.java b/service/src/test/java/lcsb/mapviewer/services/impl/LdapServiceTest.java index d870b55dea830e6cc0917ef2c05e6d68638beef9..56a60d964df9d44679e65393c39c4eee536dbf50 100644 --- a/service/src/test/java/lcsb/mapviewer/services/impl/LdapServiceTest.java +++ b/service/src/test/java/lcsb/mapviewer/services/impl/LdapServiceTest.java @@ -21,7 +21,6 @@ import lcsb.mapviewer.model.user.ConfigurationElementType; import lcsb.mapviewer.services.ServiceTestFunctions; import lcsb.mapviewer.services.UserDTO; -//@TODO: Replace with Spring Security LDAP @Rollback(true) public class LdapServiceTest extends ServiceTestFunctions { static Logger logger = LogManager.getLogger(LdapServiceTest.class); @@ -30,36 +29,31 @@ public class LdapServiceTest extends ServiceTestFunctions { @Before public void setUp() throws Exception { - try { - configurationService.setConfigurationValue(ConfigurationElementType.LDAP_BASE_DN, "dc=uni,dc=lu"); - configurationService.setConfigurationValue(ConfigurationElementType.LDAP_UID, "uid"); - configurationService.setConfigurationValue(ConfigurationElementType.LDAP_OBJECT_CLASS, "person"); - configurationService.setConfigurationValue(ConfigurationElementType.LDAP_FILTER, "memberof=cn=gitlab,cn=groups,cn=accounts,dc=uni,dc=lu"); - - ldapService = Mockito.spy(new LdapService(null)); - ldapService.setConfigurationService(configurationService); - Mockito.when(ldapService.getConnection()).thenAnswer(new Answer<LDAPConnection>() { - - @Override - public LDAPConnection answer(InvocationOnMock invocation) throws Throwable { - // Create the configuration to use for the server. - InMemoryDirectoryServerConfig config = new InMemoryDirectoryServerConfig("dc=uni,dc=lu"); - config.addAdditionalBindCredentials("uid=piotr.gawron,cn=users,cn=accounts,dc=uni,dc=lu", "test_passwd"); - config.setSchema(null); - - // Create the directory server instance, populate it with data from the - // "test-data.ldif" file, and start listening for client connections. - InMemoryDirectoryServer ds = new InMemoryDirectoryServer(config); - ds.importFromLDIF(true, "testFiles/ldap/testdata.ldif"); - ds.startListening(); - return ds.getConnection(); - } - }); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + configurationService.setConfigurationValue(ConfigurationElementType.LDAP_BASE_DN, "dc=uni,dc=lu"); + configurationService.setConfigurationValue(ConfigurationElementType.LDAP_UID, "uid"); + configurationService.setConfigurationValue(ConfigurationElementType.LDAP_OBJECT_CLASS, "person"); + configurationService.setConfigurationValue(ConfigurationElementType.LDAP_FILTER, + "memberof=cn=gitlab,cn=groups,cn=accounts,dc=uni,dc=lu"); + + ldapService = Mockito.spy(new LdapService(null)); + ldapService.setConfigurationService(configurationService); + Mockito.when(ldapService.getConnection()).thenAnswer(new Answer<LDAPConnection>() { + + @Override + public LDAPConnection answer(InvocationOnMock invocation) throws Throwable { + // Create the configuration to use for the server. + InMemoryDirectoryServerConfig config = new InMemoryDirectoryServerConfig("dc=uni,dc=lu"); + config.addAdditionalBindCredentials("uid=piotr.gawron,cn=users,cn=accounts,dc=uni,dc=lu", "test_passwd"); + config.setSchema(null); + + // Create the directory server instance, populate it with data from the + // "test-data.ldif" file, and start listening for client connections. + InMemoryDirectoryServer ds = new InMemoryDirectoryServer(config); + ds.importFromLDIF(true, "testFiles/ldap/testdata.ldif"); + ds.startListening(); + return ds.getConnection(); + } + }); } @After @@ -68,81 +62,51 @@ public class LdapServiceTest extends ServiceTestFunctions { @Test public void testIsValidConfiguration() throws Exception { - try { - assertTrue(ldapService.isValidConfiguration()); - configurationService.setConfigurationValue(ConfigurationElementType.LDAP_BASE_DN, ""); - assertFalse(ldapService.isValidConfiguration()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertTrue(ldapService.isValidConfiguration()); + configurationService.setConfigurationValue(ConfigurationElementType.LDAP_BASE_DN, ""); + assertFalse(ldapService.isValidConfiguration()); } @Test public void testCreateAttributeFilterForEmpty() throws Exception { - try { - configurationService.setConfigurationValue(ConfigurationElementType.LDAP_FILTER, ""); - Filter filter = ldapService.createAttributeFilter(); - assertNotNull(filter); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + configurationService.setConfigurationValue(ConfigurationElementType.LDAP_FILTER, ""); + Filter filter = ldapService.createAttributeFilter(); + assertNotNull(filter); } @Test public void testLogin() throws Exception { - try { - assertTrue(ldapService.login("piotr.gawron", "test_passwd")); - assertFalse(ldapService.login("piotr.gawron", "invalid_password")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertTrue(ldapService.login("piotr.gawron", "test_passwd")); + assertFalse(ldapService.login("piotr.gawron", "invalid_password")); } @Test public void testGetUsernames() throws Exception { - try { - List<String> list = ldapService.getUsernames(); - assertEquals(2, list.size()); - assertTrue(list.contains("piotr.gawron")); - assertFalse(list.contains("john.doe")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + List<String> list = ldapService.getUsernames(); + assertEquals(2, list.size()); + assertTrue(list.contains("piotr.gawron")); + assertFalse(list.contains("john.doe")); } @Test public void testGetUsernamesWithFiltering() throws Exception { - try { - configurationService.setConfigurationValue(ConfigurationElementType.LDAP_FILTER, - "(memberof=cn=owncloud,cn=groups,cn=accounts,dc=uni,dc=lu)"); - - List<String> list = ldapService.getUsernames(); - assertEquals(1, list.size()); - assertTrue(list.contains("piotr.gawron")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + configurationService.setConfigurationValue(ConfigurationElementType.LDAP_FILTER, + "(memberof=cn=owncloud,cn=groups,cn=accounts,dc=uni,dc=lu)"); + + List<String> list = ldapService.getUsernames(); + assertEquals(1, list.size()); + assertTrue(list.contains("piotr.gawron")); } @Test public void testGetUserByLogin() throws Exception { - try { - UserDTO user = ldapService.getUserByLogin("piotr.gawron"); - assertNotNull(user); - assertEquals("Piotr", user.getFirstName()); - assertEquals("Gawron", user.getLastName()); - assertEquals("piotr.gawron", user.getLogin()); - assertEquals("piotr.gawron@uni.lu", user.getEmail()); - assertNotNull(user.getBindDn()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + UserDTO user = ldapService.getUserByLogin("piotr.gawron"); + assertNotNull(user); + assertEquals("Piotr", user.getFirstName()); + assertEquals("Gawron", user.getLastName()); + assertEquals("piotr.gawron", user.getLogin()); + assertEquals("piotr.gawron@uni.lu", user.getEmail()); + assertNotNull(user.getBindDn()); } } diff --git a/service/src/test/java/lcsb/mapviewer/services/impl/ProjectServiceTest.java b/service/src/test/java/lcsb/mapviewer/services/impl/ProjectServiceTest.java index 3f8f27a0f2f73ddbb16f23b36e61e9d1e3dec100..6e87809a6427d156bd45d5ec458c5bc687458207 100644 --- a/service/src/test/java/lcsb/mapviewer/services/impl/ProjectServiceTest.java +++ b/service/src/test/java/lcsb/mapviewer/services/impl/ProjectServiceTest.java @@ -65,50 +65,39 @@ public class ProjectServiceTest extends ServiceTestFunctions { @Test public void testGetAllProjects() { - try { - List<Project> projects = projectService.getAllProjects(); + List<Project> projects = projectService.getAllProjects(); - Project project = new Project(); - project.setProjectId(projectId); - projectDao.add(project); - projectDao.evict(project); + Project project = new Project(); + project.setProjectId(projectId); + projectDao.add(project); + projectDao.evict(project); - List<Project> projects2 = projectService.getAllProjects(); + List<Project> projects2 = projectService.getAllProjects(); - assertEquals(projects.size() + 1, projects2.size()); + assertEquals(projects.size() + 1, projects2.size()); - for (Project tmpProject : projects2) { - if (!projects.contains(tmpProject)) { - assertEquals(projectId, tmpProject.getProjectId()); - } + for (Project tmpProject : projects2) { + if (!projects.contains(tmpProject)) { + assertEquals(projectId, tmpProject.getProjectId()); } + } - Project project2 = projectDao.getProjectByProjectId(projectId); - assertNotNull(project2); - assertNotEquals(project2, project); - assertEquals(project.getId(), project2.getId()); - - projectDao.delete(project2); + Project project2 = projectDao.getProjectByProjectId(projectId); + assertNotNull(project2); + assertNotEquals(project2, project); + assertEquals(project.getId(), project2.getId()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + projectDao.delete(project2); } @Test public void testUpdater() throws Exception { - try { - projectService - .createProject(createProjectParams("testFiles/centeredAnchorInModifier.xml").analyzeAnnotations(true)); - Project project = projectService.getProjectByProjectId(projectId); - assertNotNull(project); - assertEquals(ProjectStatus.DONE, project.getStatus()); - projectService.removeProject(project, null, false); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + projectService + .createProject(createProjectParams("testFiles/centeredAnchorInModifier.xml").analyzeAnnotations(true)); + Project project = projectService.getProjectByProjectId(projectId); + assertNotNull(project); + assertEquals(ProjectStatus.DONE, project.getStatus()); + projectService.removeProject(project, null, false); } @Test @@ -190,9 +179,6 @@ public class ProjectServiceTest extends ServiceTestFunctions { directories.add(imageLayer.getDirectory()); } assertEquals(1 + model.getSubmodels().size(), directories.size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; } finally { Project project = projectService.getProjectByProjectId(projectId); if (project != null) { @@ -231,10 +217,6 @@ public class ProjectServiceTest extends ServiceTestFunctions { tmp = new File(path + "/nested"); assertTrue(tmp.exists()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; } finally { f.delete(); } @@ -276,10 +258,6 @@ public class ProjectServiceTest extends ServiceTestFunctions { tmp = new File(path + "/nested_B"); assertTrue(tmp.exists()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; } finally { f.delete(); } @@ -288,237 +266,203 @@ public class ProjectServiceTest extends ServiceTestFunctions { @Test public void testCopyComplexWithCompartments() throws Exception { - try { - ZipEntryFile entry1 = new ModelZipEntryFile("main.xml", "main", true, false, SubmodelType.UNKNOWN); - ZipEntryFile entry2 = new ModelZipEntryFile("s1.xml", "s1", false, false, SubmodelType.UNKNOWN); - ZipEntryFile entry3 = new ModelZipEntryFile("s2.xml", "s2", false, false, SubmodelType.UNKNOWN); - ZipEntryFile entry4 = new ModelZipEntryFile("s3.xml", "s3", false, false, SubmodelType.UNKNOWN); - ZipEntryFile entry5 = new ModelZipEntryFile("mapping.xml", "mapping", false, true, SubmodelType.UNKNOWN); - - CreateProjectParams params = createProjectParams("testFiles/complexModel/complex_model_with_compartment.zip") - .addZipEntry(entry1).addZipEntry(entry2).addZipEntry(entry3).addZipEntry(entry4).addZipEntry(entry5) - .analyzeAnnotations(false); - - ComplexZipConverter parser = new ComplexZipConverter(CellDesignerXmlParser.class); - ComplexZipConverterParams complexParams = new ComplexZipConverterParams().zipFile(params.getProjectFile()); - for (ZipEntryFile entry : params.getZipEntries()) { - complexParams.entry(entry); - } - Model model = parser.createModel(complexParams); - - assertNotNull(model); - assertEquals("main", model.getName()); - assertEquals(3, model.getSubmodelConnections().size()); + ZipEntryFile entry1 = new ModelZipEntryFile("main.xml", "main", true, false, SubmodelType.UNKNOWN); + ZipEntryFile entry2 = new ModelZipEntryFile("s1.xml", "s1", false, false, SubmodelType.UNKNOWN); + ZipEntryFile entry3 = new ModelZipEntryFile("s2.xml", "s2", false, false, SubmodelType.UNKNOWN); + ZipEntryFile entry4 = new ModelZipEntryFile("s3.xml", "s3", false, false, SubmodelType.UNKNOWN); + ZipEntryFile entry5 = new ModelZipEntryFile("mapping.xml", "mapping", false, true, SubmodelType.UNKNOWN); + + CreateProjectParams params = createProjectParams("testFiles/complexModel/complex_model_with_compartment.zip") + .addZipEntry(entry1).addZipEntry(entry2).addZipEntry(entry3).addZipEntry(entry4).addZipEntry(entry5) + .analyzeAnnotations(false); + + ComplexZipConverter parser = new ComplexZipConverter(CellDesignerXmlParser.class); + ComplexZipConverterParams complexParams = new ComplexZipConverterParams().zipFile(params.getProjectFile()); + for (ZipEntryFile entry : params.getZipEntries()) { + complexParams.entry(entry); + } + Model model = parser.createModel(complexParams); - int oldSize = 0; - for (Model m : model.getSubmodels()) { - oldSize += m.getParentModels().size(); - } + assertNotNull(model); + assertEquals("main", model.getName()); + assertEquals(3, model.getSubmodelConnections().size()); - new CopyCommand(model).execute(); + int oldSize = 0; + for (Model m : model.getSubmodels()) { + oldSize += m.getParentModels().size(); + } - int newSize = 0; - for (Model m : model.getSubmodels()) { - newSize += m.getParentModels().size(); - } - assertEquals("Submodels doesn't match after copying", oldSize, newSize); + new CopyCommand(model).execute(); - } catch (Exception e) { - e.printStackTrace(); - throw e; + int newSize = 0; + for (Model m : model.getSubmodels()) { + newSize += m.getParentModels().size(); } + assertEquals("Submodels doesn't match after copying", oldSize, newSize); } @Test public void testAnnotatorTree() throws Exception { - try { - TreeNode tree = projectService.createClassAnnotatorTree(null); - assertNotNull(tree); + TreeNode tree = projectService.createClassAnnotatorTree(null); + assertNotNull(tree); - AnnotatedObjectTreeRow dataNode = (AnnotatedObjectTreeRow) tree.getData(); + AnnotatedObjectTreeRow dataNode = (AnnotatedObjectTreeRow) tree.getData(); - assertEquals(BioEntity.class, dataNode.getClazz()); + assertEquals(BioEntity.class, dataNode.getClazz()); - Queue<TreeNode> nodes = new LinkedList<TreeNode>(); - nodes.add(tree); - boolean annotatorsFound = false; - while (!nodes.isEmpty()) { - TreeNode node = nodes.poll(); - dataNode = (AnnotatedObjectTreeRow) node.getData(); - if (dataNode.getValidAnnotators().size() > 0) { - annotatorsFound = true; - } - for (TreeNode n : node.getChildren()) { - nodes.add(n); - } + Queue<TreeNode> nodes = new LinkedList<TreeNode>(); + nodes.add(tree); + boolean annotatorsFound = false; + while (!nodes.isEmpty()) { + TreeNode node = nodes.poll(); + dataNode = (AnnotatedObjectTreeRow) node.getData(); + if (dataNode.getValidAnnotators().size() > 0) { + annotatorsFound = true; + } + for (TreeNode n : node.getChildren()) { + nodes.add(n); } - assertTrue(annotatorsFound); - } catch (Exception e) { - e.printStackTrace(); - throw e; } - + assertTrue(annotatorsFound); } @Test public void testEmptyAnnotatorTreeForUser() throws Exception { - try { - User user = createUser(); - UserAnnotationSchema schema = modelAnnotator.createDefaultAnnotatorSchema(); - for (UserClassAnnotators classAnnotators : schema.getClassAnnotators()) { - classAnnotators.setAnnotators(new ArrayList<>()); - } - user.setAnnotationSchema(schema); - userDao.update(user); + User user = createUser(); + UserAnnotationSchema schema = modelAnnotator.createDefaultAnnotatorSchema(); + for (UserClassAnnotators classAnnotators : schema.getClassAnnotators()) { + classAnnotators.setAnnotators(new ArrayList<>()); + } + user.setAnnotationSchema(schema); + userDao.update(user); - TreeNode tree = projectService.createClassAnnotatorTree(user); - assertNotNull(tree); + TreeNode tree = projectService.createClassAnnotatorTree(user); + assertNotNull(tree); - AnnotatedObjectTreeRow dataNode = (AnnotatedObjectTreeRow) tree.getData(); + AnnotatedObjectTreeRow dataNode = (AnnotatedObjectTreeRow) tree.getData(); - assertEquals(BioEntity.class, dataNode.getClazz()); + assertEquals(BioEntity.class, dataNode.getClazz()); - Queue<TreeNode> nodes = new LinkedList<TreeNode>(); - nodes.add(tree); - boolean annotatorsFound = false; - while (!nodes.isEmpty()) { - TreeNode node = nodes.poll(); - dataNode = (AnnotatedObjectTreeRow) node.getData(); - assertEquals("Annotators found for class: " + dataNode.getClazz(), 0, dataNode.getUsedAnnotators().size()); - if (dataNode.getValidAnnotators().size() > 0) { - annotatorsFound = true; - } - for (TreeNode n : node.getChildren()) { - nodes.add(n); - } + Queue<TreeNode> nodes = new LinkedList<TreeNode>(); + nodes.add(tree); + boolean annotatorsFound = false; + while (!nodes.isEmpty()) { + TreeNode node = nodes.poll(); + dataNode = (AnnotatedObjectTreeRow) node.getData(); + assertEquals("Annotators found for class: " + dataNode.getClazz(), 0, dataNode.getUsedAnnotators().size()); + if (dataNode.getValidAnnotators().size() > 0) { + annotatorsFound = true; + } + for (TreeNode n : node.getChildren()) { + nodes.add(n); } - assertTrue(annotatorsFound); - - userDao.delete(user); - } catch (Exception e) { - e.printStackTrace(); - throw e; } + assertTrue(annotatorsFound); + + userDao.delete(user); } @Test public void testAnnotatorTreeForUser() throws Exception { - try { - User user = createUser(); - UserAnnotationSchema schema = new UserAnnotationSchema(); - schema.addClassAnnotator( - new UserClassAnnotators(Protein.class, modelAnnotator.getDefaultAnnotators(Protein.class))); - user.setAnnotationSchema(schema); - userDao.update(user); - - TreeNode tree = projectService.createClassAnnotatorTree(user); - assertNotNull(tree); - - AnnotatedObjectTreeRow dataNode = (AnnotatedObjectTreeRow) tree.getData(); - - assertEquals(BioEntity.class, dataNode.getClazz()); - - Queue<TreeNode> nodes = new LinkedList<>(); - nodes.add(tree); - boolean annotatorsFound = false; - while (!nodes.isEmpty()) { - TreeNode node = nodes.poll(); - dataNode = (AnnotatedObjectTreeRow) node.getData(); - if (dataNode.getUsedAnnotators().size() > 0) { - annotatorsFound = true; - } - for (TreeNode n : node.getChildren()) { - nodes.add(n); - } + User user = createUser(); + UserAnnotationSchema schema = new UserAnnotationSchema(); + schema.addClassAnnotator( + new UserClassAnnotators(Protein.class, modelAnnotator.getDefaultAnnotators(Protein.class))); + user.setAnnotationSchema(schema); + userDao.update(user); + + TreeNode tree = projectService.createClassAnnotatorTree(user); + assertNotNull(tree); + + AnnotatedObjectTreeRow dataNode = (AnnotatedObjectTreeRow) tree.getData(); + + assertEquals(BioEntity.class, dataNode.getClazz()); + + Queue<TreeNode> nodes = new LinkedList<>(); + nodes.add(tree); + boolean annotatorsFound = false; + while (!nodes.isEmpty()) { + TreeNode node = nodes.poll(); + dataNode = (AnnotatedObjectTreeRow) node.getData(); + if (dataNode.getUsedAnnotators().size() > 0) { + annotatorsFound = true; + } + for (TreeNode n : node.getChildren()) { + nodes.add(n); } - assertTrue(annotatorsFound); - - userDao.delete(user); - } catch (Exception e) { - e.printStackTrace(); - throw e; } + assertTrue(annotatorsFound); + userDao.delete(user); } @Test public void testEmptyValidMiriamTreeForUser() throws Exception { - try { - User user = createUser(); - UserAnnotationSchema schema = new UserAnnotationSchema(); - user.setAnnotationSchema(schema); - userDao.update(user); - - TreeNode tree = projectService.createClassAnnotatorTree(user); - assertNotNull(tree); - - AnnotatedObjectTreeRow dataNode = (AnnotatedObjectTreeRow) tree.getData(); - - assertEquals(BioEntity.class, dataNode.getClazz()); - - Queue<TreeNode> nodes = new LinkedList<TreeNode>(); - nodes.add(tree); - boolean annotatorsFound = false; - while (!nodes.isEmpty()) { - TreeNode node = nodes.poll(); - dataNode = (AnnotatedObjectTreeRow) node.getData(); - assertEquals("Valid miriam found for class: " + dataNode.getClazz(), 0, dataNode.getValidAnnotations().size()); - assertEquals("Required miriam found for class: " + dataNode.getClazz(), 0, - dataNode.getRequiredAnnotations().size()); - if (dataNode.getMissingValidAnnotations().size() > 0 && dataNode.getMissingRequiredAnnotations().size() > 0) { - annotatorsFound = true; - } - for (TreeNode n : node.getChildren()) { - nodes.add(n); - } + User user = createUser(); + UserAnnotationSchema schema = new UserAnnotationSchema(); + user.setAnnotationSchema(schema); + userDao.update(user); + + TreeNode tree = projectService.createClassAnnotatorTree(user); + assertNotNull(tree); + + AnnotatedObjectTreeRow dataNode = (AnnotatedObjectTreeRow) tree.getData(); + + assertEquals(BioEntity.class, dataNode.getClazz()); + + Queue<TreeNode> nodes = new LinkedList<TreeNode>(); + nodes.add(tree); + boolean annotatorsFound = false; + while (!nodes.isEmpty()) { + TreeNode node = nodes.poll(); + dataNode = (AnnotatedObjectTreeRow) node.getData(); + assertEquals("Valid miriam found for class: " + dataNode.getClazz(), 0, dataNode.getValidAnnotations().size()); + assertEquals("Required miriam found for class: " + dataNode.getClazz(), 0, + dataNode.getRequiredAnnotations().size()); + if (dataNode.getMissingValidAnnotations().size() > 0 && dataNode.getMissingRequiredAnnotations().size() > 0) { + annotatorsFound = true; + } + for (TreeNode n : node.getChildren()) { + nodes.add(n); } - assertTrue(annotatorsFound); - - userDao.delete(user); - } catch (Exception e) { - e.printStackTrace(); - throw e; } + assertTrue(annotatorsFound); + + userDao.delete(user); } @Test public void testValidMiriamTreeForUser() throws Exception { - try { - User user = createUser(); - UserAnnotationSchema schema = new UserAnnotationSchema(); - schema.addClassValidAnnotations(new UserClassValidAnnotations(Protein.class, MiriamType.values())); - user.setAnnotationSchema(schema); - userDao.update(user); - userDao.flush(); - - TreeNode tree = projectService.createClassAnnotatorTree(user); - assertNotNull(tree); - - AnnotatedObjectTreeRow dataNode = (AnnotatedObjectTreeRow) tree.getData(); - - assertEquals(BioEntity.class, dataNode.getClazz()); - - Queue<TreeNode> nodes = new LinkedList<>(); - nodes.add(tree); - boolean annotatorsFound = false; - while (!nodes.isEmpty()) { - TreeNode node = nodes.poll(); - dataNode = (AnnotatedObjectTreeRow) node.getData(); - if (dataNode.getValidAnnotations().size() > 0) { - annotatorsFound = true; - } - for (TreeNode n : node.getChildren()) { - nodes.add(n); - } + User user = createUser(); + UserAnnotationSchema schema = new UserAnnotationSchema(); + schema.addClassValidAnnotations(new UserClassValidAnnotations(Protein.class, MiriamType.values())); + user.setAnnotationSchema(schema); + userDao.update(user); + userDao.flush(); + + TreeNode tree = projectService.createClassAnnotatorTree(user); + assertNotNull(tree); + + AnnotatedObjectTreeRow dataNode = (AnnotatedObjectTreeRow) tree.getData(); + + assertEquals(BioEntity.class, dataNode.getClazz()); + + Queue<TreeNode> nodes = new LinkedList<>(); + nodes.add(tree); + boolean annotatorsFound = false; + while (!nodes.isEmpty()) { + TreeNode node = nodes.poll(); + dataNode = (AnnotatedObjectTreeRow) node.getData(); + if (dataNode.getValidAnnotations().size() > 0) { + annotatorsFound = true; + } + for (TreeNode n : node.getChildren()) { + nodes.add(n); } - assertTrue(annotatorsFound); - - userDao.delete(user); - } catch (Exception e) { - e.printStackTrace(); - throw e; } + assertTrue(annotatorsFound); + userDao.delete(user); } protected Project createComplexProject(String projectId, String filename) throws IOException, SecurityException { @@ -540,62 +484,52 @@ public class ProjectServiceTest extends ServiceTestFunctions { @Test public void testCreateComplexWithImages() throws Exception { - try { - String filename = "testFiles/complexModel/complex_model_with_images.zip"; - Project project = createComplexProject(projectId, filename); - - Model model = modelService.getLastModelByProjectId(projectId); - assertNotNull(model); - assertEquals("main", model.getName()); - assertEquals(ProjectStatus.DONE, project.getStatus()); - assertEquals("Cannot find overview images the model", 2, project.getOverviewImages().size()); - assertEquals("Number of layouts doesn't match", BuildInLayout.values().length, project.getLayouts().size()); - assertEquals(BuildInLayout.NESTED.getTitle(), project.getLayouts().get(0).getTitle()); - assertEquals(BuildInLayout.NORMAL.getTitle(), project.getLayouts().get(1).getTitle()); - projectService.removeProject(project, null, false); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String filename = "testFiles/complexModel/complex_model_with_images.zip"; + Project project = createComplexProject(projectId, filename); + + Model model = modelService.getLastModelByProjectId(projectId); + assertNotNull(model); + assertEquals("main", model.getName()); + assertEquals(ProjectStatus.DONE, project.getStatus()); + assertEquals("Cannot find overview images the model", 2, project.getOverviewImages().size()); + assertEquals("Number of layouts doesn't match", BuildInLayout.values().length, project.getLayouts().size()); + assertEquals(BuildInLayout.NESTED.getTitle(), project.getLayouts().get(0).getTitle()); + assertEquals(BuildInLayout.NORMAL.getTitle(), project.getLayouts().get(1).getTitle()); + projectService.removeProject(project, null, false); } @Test public void testCreateComplexWithLayoutOrder() throws Exception { - try { - String filename = "testFiles/complexModel/complex_model_with_images.zip"; - CreateProjectParams params = createProjectParams(filename); - - ZipFile zipFile = new ZipFile(filename); - Enumeration<? extends ZipEntry> entries = zipFile.entries(); - while (entries.hasMoreElements()) { - ZipEntry entry = entries.nextElement(); - params.addZipEntry(zefFactory.createZipEntryFile(entry, zipFile)); - } - zipFile.close(); + String filename = "testFiles/complexModel/complex_model_with_images.zip"; + CreateProjectParams params = createProjectParams(filename); - projectService.createProject(params.networkLayoutAsDefault(true)); - Project project = projectService.getProjectByProjectId(projectId); + ZipFile zipFile = new ZipFile(filename); + Enumeration<? extends ZipEntry> entries = zipFile.entries(); + while (entries.hasMoreElements()) { + ZipEntry entry = entries.nextElement(); + params.addZipEntry(zefFactory.createZipEntryFile(entry, zipFile)); + } + zipFile.close(); - Model model = modelService.getLastModelByProjectId(projectId); - for (OverviewImage oi : project.getOverviewImages()) { - for (OverviewLink ol : oi.getLinks()) { - if (ol instanceof OverviewImageLink) { - logger.debug(((OverviewImageLink) ol).getLinkedOverviewImage()); - } + projectService.createProject(params.networkLayoutAsDefault(true)); + Project project = projectService.getProjectByProjectId(projectId); + + Model model = modelService.getLastModelByProjectId(projectId); + for (OverviewImage oi : project.getOverviewImages()) { + for (OverviewLink ol : oi.getLinks()) { + if (ol instanceof OverviewImageLink) { + logger.debug(((OverviewImageLink) ol).getLinkedOverviewImage()); } } - assertNotNull(model); - assertEquals("main", model.getName()); - assertEquals(ProjectStatus.DONE, project.getStatus()); - assertEquals("Cannot find overview images the model", 2, project.getOverviewImages().size()); - assertEquals("Number of layouts doesn't match", BuildInLayout.values().length, project.getLayouts().size()); - assertEquals(BuildInLayout.NESTED.getTitle(), project.getLayouts().get(1).getTitle()); - assertEquals(BuildInLayout.NORMAL.getTitle(), project.getLayouts().get(0).getTitle()); - projectService.removeProject(project, null, false); - } catch (Exception e) { - e.printStackTrace(); - throw e; } + assertNotNull(model); + assertEquals("main", model.getName()); + assertEquals(ProjectStatus.DONE, project.getStatus()); + assertEquals("Cannot find overview images the model", 2, project.getOverviewImages().size()); + assertEquals("Number of layouts doesn't match", BuildInLayout.values().length, project.getLayouts().size()); + assertEquals(BuildInLayout.NESTED.getTitle(), project.getLayouts().get(1).getTitle()); + assertEquals(BuildInLayout.NORMAL.getTitle(), project.getLayouts().get(0).getTitle()); + projectService.removeProject(project, null, false); } private CreateProjectParams createProjectParams(String filename) throws FileNotFoundException, IOException { @@ -621,141 +555,106 @@ public class ProjectServiceTest extends ServiceTestFunctions { @Test(timeout = 15000) public void testCreateComplexWithLayouts() throws Exception { - try { - String filename = "testFiles/complexModel/complex_model_with_layouts.zip"; - int overlaysInZipFile = 1; - Project project = createComplexProject(projectId, filename); - - Model model = modelService.getLastModelByProjectId(projectId); - assertNotNull(model); - assertEquals("main", model.getName()); - assertEquals(ProjectStatus.DONE, project.getStatus()); - assertEquals("Number of layouts doesn't match", BuildInLayout.values().length + overlaysInZipFile, - project.getLayouts().size()); - boolean additionalFound = false; - - for (Layout layout : project.getLayouts()) { - if ("example name".equals(layout.getTitle())) { - additionalFound = true; - assertEquals("layout description", layout.getDescription()); - for (DataOverlayImageLayer imageLayer : layout.getDataOverlayImageLayers()) { - assertTrue(imageLayer.getDirectory().contains("example")); - } + String filename = "testFiles/complexModel/complex_model_with_layouts.zip"; + int overlaysInZipFile = 1; + Project project = createComplexProject(projectId, filename); + + Model model = modelService.getLastModelByProjectId(projectId); + assertNotNull(model); + assertEquals("main", model.getName()); + assertEquals(ProjectStatus.DONE, project.getStatus()); + assertEquals("Number of layouts doesn't match", BuildInLayout.values().length + overlaysInZipFile, + project.getLayouts().size()); + boolean additionalFound = false; + + for (Layout layout : project.getLayouts()) { + if ("example name".equals(layout.getTitle())) { + additionalFound = true; + assertEquals("layout description", layout.getDescription()); + for (DataOverlayImageLayer imageLayer : layout.getDataOverlayImageLayers()) { + assertTrue(imageLayer.getDirectory().contains("example")); } } - assertTrue("Cannot find layout with predefined name from file", additionalFound); - projectService.removeProject(project, null, false); - assertNull(projectService.getProjectByProjectId(projectId)); - } catch (Exception e) { - e.printStackTrace(); - throw e; } + assertTrue("Cannot find layout with predefined name from file", additionalFound); + projectService.removeProject(project, null, false); + assertNull(projectService.getProjectByProjectId(projectId)); } @Test public void testCreateComplexWithSumbaps() throws Exception { - try { - String filename = "testFiles/complexModel/complex_model_with_submaps.zip"; - Project project = createComplexProject(projectId, filename); - - Model model = modelService.getLastModelByProjectId(projectId); - assertNotNull(model); - assertEquals("main", model.getName()); - assertEquals(ProjectStatus.DONE, project.getStatus()); - assertEquals("Number of layouts doesn't match", BuildInLayout.values().length, project.getLayouts().size()); - projectService.removeProject(project, null, false); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String filename = "testFiles/complexModel/complex_model_with_submaps.zip"; + Project project = createComplexProject(projectId, filename); + + Model model = modelService.getLastModelByProjectId(projectId); + assertNotNull(model); + assertEquals("main", model.getName()); + assertEquals(ProjectStatus.DONE, project.getStatus()); + assertEquals("Number of layouts doesn't match", BuildInLayout.values().length, project.getLayouts().size()); + projectService.removeProject(project, null, false); } @Test public void testCreateEmptyComplex() throws Exception { - try { - String filename = "testFiles/complexModel/empty_complex_model.zip"; - Project project = createComplexProject(projectId, filename); + String filename = "testFiles/complexModel/empty_complex_model.zip"; + Project project = createComplexProject(projectId, filename); - Model model = modelService.getLastModelByProjectId(projectId); - assertNotNull(model); - assertEquals(ProjectStatus.DONE, project.getStatus()); - projectService.removeProject(project, null, false); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Model model = modelService.getLastModelByProjectId(projectId); + assertNotNull(model); + assertEquals(ProjectStatus.DONE, project.getStatus()); + projectService.removeProject(project, null, false); } @Test public void testCreateEmptyComplex2() throws Exception { - try { - String filename = "testFiles/complexModel/empty_complex_model2.zip"; - Project project = createComplexProject(projectId, filename); + String filename = "testFiles/complexModel/empty_complex_model2.zip"; + Project project = createComplexProject(projectId, filename); - Model model = modelService.getLastModelByProjectId(projectId); - assertNotNull(model); - assertEquals(ProjectStatus.DONE, project.getStatus()); - projectService.removeProject(project, null, false); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Model model = modelService.getLastModelByProjectId(projectId); + assertNotNull(model); + assertEquals(ProjectStatus.DONE, project.getStatus()); + projectService.removeProject(project, null, false); } @Test public void testCreateEmptyComplex3() throws Exception { - try { - String filename = "testFiles/complexModel/empty_complex_model3.zip"; - Project project = createComplexProject(projectId, filename); + String filename = "testFiles/complexModel/empty_complex_model3.zip"; + Project project = createComplexProject(projectId, filename); - Model model = modelService.getLastModelByProjectId(projectId); - assertNotNull(model); - assertEquals(ProjectStatus.DONE, project.getStatus()); - projectService.removeProject(project, null, false); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Model model = modelService.getLastModelByProjectId(projectId); + assertNotNull(model); + assertEquals(ProjectStatus.DONE, project.getStatus()); + projectService.removeProject(project, null, false); } @Test public void testUpdateProjectWithoutModel() throws Exception { - try { - createUser(); + createUser(); - Project project = new Project(); - project.setProjectId(projectId); - projectDao.add(project); - projectService.updateProject(project); - projectService.removeProject(project, null, false); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Project project = new Project(); + project.setProjectId(projectId); + projectDao.add(project); + projectService.updateProject(project); + projectService.removeProject(project, null, false); } @Test public void uploadToBigFile() throws Exception { - try { - Integer value = Integer - .parseInt(configurationService.getValue(ConfigurationElementType.MAX_NUMBER_OF_MAP_LEVELS).getValue()); - double size = MapGenerator.TILE_SIZE * Math.pow(2, value) + 1; - Model model = new ModelFullIndexed(null); - model.setWidth(size); - model.setHeight(size); - String xml = new CellDesignerXmlParser().model2String(model); - InputStream is = new ByteArrayInputStream(xml.getBytes(StandardCharsets.UTF_8)); + Integer value = Integer + .parseInt(configurationService.getValue(ConfigurationElementType.MAX_NUMBER_OF_MAP_LEVELS).getValue()); + double size = MapGenerator.TILE_SIZE * Math.pow(2, value) + 1; + Model model = new ModelFullIndexed(null); + model.setWidth(size); + model.setHeight(size); + String xml = new CellDesignerXmlParser().model2String(model); + InputStream is = new ByteArrayInputStream(xml.getBytes(StandardCharsets.UTF_8)); - CreateProjectParams params = createProjectParams("sample.xml", is); + CreateProjectParams params = createProjectParams("sample.xml", is); - projectService.createProject(params); + projectService.createProject(params); - Project project = projectService.getProjectByProjectId(projectId); - assertEquals(ProjectStatus.FAIL, project.getStatus()); - projectService.removeProject(project, null, false); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Project project = projectService.getProjectByProjectId(projectId); + assertEquals(ProjectStatus.FAIL, project.getStatus()); + projectService.removeProject(project, null, false); } } diff --git a/service/src/test/java/lcsb/mapviewer/services/impl/SearchServiceTest.java b/service/src/test/java/lcsb/mapviewer/services/impl/SearchServiceTest.java index 69146289c20d00bbbe4455295771f4059ced8e3e..4bd1f9604d39d47f5530b4a8047136909d0ed574 100644 --- a/service/src/test/java/lcsb/mapviewer/services/impl/SearchServiceTest.java +++ b/service/src/test/java/lcsb/mapviewer/services/impl/SearchServiceTest.java @@ -1,46 +1,20 @@ package lcsb.mapviewer.services.impl; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.junit.Assert.*; import java.awt.geom.Point2D; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; +import java.util.*; -import org.apache.logging.log4j.*; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.junit.*; import lcsb.mapviewer.common.Configuration; import lcsb.mapviewer.model.Project; -import lcsb.mapviewer.model.map.BioEntity; -import lcsb.mapviewer.model.map.MiriamData; -import lcsb.mapviewer.model.map.MiriamRelationType; -import lcsb.mapviewer.model.map.MiriamType; -import lcsb.mapviewer.model.map.model.Model; -import lcsb.mapviewer.model.map.model.ModelFullIndexed; -import lcsb.mapviewer.model.map.model.ModelSubmodelConnection; -import lcsb.mapviewer.model.map.model.SubmodelType; +import lcsb.mapviewer.model.map.*; +import lcsb.mapviewer.model.map.model.*; import lcsb.mapviewer.model.map.reaction.Reaction; -import lcsb.mapviewer.model.map.species.Complex; -import lcsb.mapviewer.model.map.species.Degraded; -import lcsb.mapviewer.model.map.species.Drug; -import lcsb.mapviewer.model.map.species.Element; -import lcsb.mapviewer.model.map.species.Gene; -import lcsb.mapviewer.model.map.species.GenericProtein; -import lcsb.mapviewer.model.map.species.Ion; -import lcsb.mapviewer.model.map.species.Phenotype; -import lcsb.mapviewer.model.map.species.Protein; -import lcsb.mapviewer.model.map.species.Rna; -import lcsb.mapviewer.model.map.species.SimpleMolecule; -import lcsb.mapviewer.model.map.species.Species; -import lcsb.mapviewer.model.map.species.Unknown; +import lcsb.mapviewer.model.map.species.*; import lcsb.mapviewer.services.ServiceTestFunctions; import lcsb.mapviewer.services.utils.SearchIndexer; @@ -85,273 +59,198 @@ public class SearchServiceTest extends ServiceTestFunctions { @Test public void testSearchByName() throws Exception { - try { - Model model = createFullModel(); - long count = searchHistoryDao.getCount(); - List<BioEntity> result = searchService.searchByQuery(model, "reaction:re21", 50, null, "127.0.0.1"); + Model model = createFullModel(); + long count = searchHistoryDao.getCount(); + List<BioEntity> result = searchService.searchByQuery(model, "reaction:re21", 50, null, "127.0.0.1"); - assertNotNull(result); - assertEquals(4, result.size()); - Reaction reaction = (Reaction) result.get(0); - assertTrue(reaction.getIdReaction().contains("re21")); + assertNotNull(result); + assertEquals(4, result.size()); + Reaction reaction = (Reaction) result.get(0); + assertTrue(reaction.getIdReaction().contains("re21")); - long count2 = searchHistoryDao.getCount(); + long count2 = searchHistoryDao.getCount(); - assertEquals(count + 1, count2); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals(count + 1, count2); } @Test public void testSearchByName2() throws Exception { - try { - Model model = createFullModel(); - List<BioEntity> result = searchService.searchByQuery(model, "BAD:BCL-2", 50, null, "127.0.0.1"); - - assertNotNull(result); - assertTrue(result.size() > 0); - Species alias = (Species) result.get(0); - assertEquals("BAD:BCL-2", alias.getName()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Model model = createFullModel(); + List<BioEntity> result = searchService.searchByQuery(model, "BAD:BCL-2", 50, null, "127.0.0.1"); + + assertNotNull(result); + assertTrue(result.size() > 0); + Species alias = (Species) result.get(0); + assertEquals("BAD:BCL-2", alias.getName()); } @Test public void testSearchById() throws Exception { - try { - Model model = createFullModel(); - MiriamData md = new MiriamData(MiriamRelationType.BQ_BIOL_HAS_VERSION, MiriamType.CAS, "123"); - model.getElements().iterator().next().addMiriamData(md); - List<BioEntity> global = searchService.searchByQuery(model, "CAS:123", 50, null, "127.0.0.1"); - assertNotNull(global); - assertEquals(1, global.size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Model model = createFullModel(); + MiriamData md = new MiriamData(MiriamRelationType.BQ_BIOL_HAS_VERSION, MiriamType.CAS, "123"); + model.getElements().iterator().next().addMiriamData(md); + List<BioEntity> global = searchService.searchByQuery(model, "CAS:123", 50, null, "127.0.0.1"); + assertNotNull(global); + assertEquals(1, global.size()); } @Test public void testSearchByElementId() throws Exception { - try { - Model model = createFullModel(); - Element element = model.getElements().iterator().next(); - element.setId(907); - List<BioEntity> global = searchService.searchByQuery(model, "element:907", 50, null, "127.0.0.1"); - assertNotNull(global); - assertEquals(1, global.size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Model model = createFullModel(); + Element element = model.getElements().iterator().next(); + element.setId(907); + List<BioEntity> global = searchService.searchByQuery(model, "element:907", 50, null, "127.0.0.1"); + assertNotNull(global); + assertEquals(1, global.size()); } @Test public void testSearchByUnknwonElementId() throws Exception { - try { - Model model = createFullModel(); - Element element = model.getElements().iterator().next(); - element.setId(907); - List<BioEntity> global = searchService.searchByQuery(model, "species:90111117", 50, null, "127.0.0.1"); - assertEquals(0, global.size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Model model = createFullModel(); + Element element = model.getElements().iterator().next(); + element.setId(907); + List<BioEntity> global = searchService.searchByQuery(model, "species:90111117", 50, null, "127.0.0.1"); + assertEquals(0, global.size()); } @Test public void testSearchByName4() throws Exception { - try { - Model model = createFullModel(); - List<BioEntity> result = searchService.searchByQuery(model, "BC", 50, true, "127.0.0.1"); - - assertNotNull(result); - assertEquals(0, result.size()); - - result = searchService.searchByQuery(model, "BC", 50, false, "127.0.0.1"); - assertNotNull(result); - assertTrue(result.size() > 0); - - result = searchService.searchByQuery(model, "BAD:BCL-2", 50, true, "127.0.0.1"); - assertNotNull(result); - assertEquals(1, result.size()); - Species alias = (Species) result.get(0); - assertEquals("BAD:BCL-2", alias.getName()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Model model = createFullModel(); + List<BioEntity> result = searchService.searchByQuery(model, "BC", 50, true, "127.0.0.1"); + + assertNotNull(result); + assertEquals(0, result.size()); + + result = searchService.searchByQuery(model, "BC", 50, false, "127.0.0.1"); + assertNotNull(result); + assertTrue(result.size() > 0); + + result = searchService.searchByQuery(model, "BAD:BCL-2", 50, true, "127.0.0.1"); + assertNotNull(result); + assertEquals(1, result.size()); + Species alias = (Species) result.get(0); + assertEquals("BAD:BCL-2", alias.getName()); } @Test public void testQueryName() throws Exception { - try { - Model model = createFullModel(); - List<BioEntity> result = searchService.searchByQuery(model, - indexer.getQueryStringForIndex("reaction:re21", new HashSet<>()), 50, null, "127.0.0.1"); - - assertNotNull(result); - assertEquals(4, result.size()); - Reaction reaction = (Reaction) result.get(0); - assertEquals("re21", reaction.getIdReaction()); - assertTrue(result.get(1) instanceof Species); - assertTrue(result.get(2) instanceof Species); - assertTrue(result.get(3) instanceof Species); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Model model = createFullModel(); + List<BioEntity> result = searchService.searchByQuery(model, + indexer.getQueryStringForIndex("reaction:re21", new HashSet<>()), 50, null, "127.0.0.1"); + + assertNotNull(result); + assertEquals(4, result.size()); + Reaction reaction = (Reaction) result.get(0); + assertEquals("re21", reaction.getIdReaction()); + assertTrue(result.get(1) instanceof Species); + assertTrue(result.get(2) instanceof Species); + assertTrue(result.get(3) instanceof Species); } @Test public void testQueryReactionId() throws Exception { - try { - Model model = createFullModel(); - model.getReactions().iterator().next().setIdReaction("R_x1"); - List<BioEntity> result = searchService.searchByQuery(model, - indexer.getQueryStringForIndex("reaction:r_x1", new HashSet<>()), 50, null, "127.0.0.1"); - - assertNotNull(result); - assertTrue(result.size() > 0); - Reaction reaction = (Reaction) result.get(0); - assertTrue(reaction.getIdReaction().contains("R_x1")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Model model = createFullModel(); + model.getReactions().iterator().next().setIdReaction("R_x1"); + List<BioEntity> result = searchService.searchByQuery(model, + indexer.getQueryStringForIndex("reaction:r_x1", new HashSet<>()), 50, null, "127.0.0.1"); + + assertNotNull(result); + assertTrue(result.size() > 0); + Reaction reaction = (Reaction) result.get(0); + assertTrue(reaction.getIdReaction().contains("R_x1")); } @Test public void testQueryReactionId2() throws Exception { - try { - Model model = createFullModel(); - Reaction reaction = model.getReactions().iterator().next(); - reaction.setId(154); - reaction.setIdReaction("test-name"); - List<BioEntity> result = searchService.searchByQuery(model, - indexer.getQueryStringForIndex("reaction:154", new HashSet<>()), 50, null, "127.0.0.1"); - - assertNotNull(result); - assertTrue(result.size() > 0); - Reaction resultReaction = (Reaction) result.get(0); - assertTrue(resultReaction.getIdReaction().contains("test-name")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Model model = createFullModel(); + Reaction reaction = model.getReactions().iterator().next(); + reaction.setId(154); + reaction.setIdReaction("test-name"); + List<BioEntity> result = searchService.searchByQuery(model, + indexer.getQueryStringForIndex("reaction:154", new HashSet<>()), 50, null, "127.0.0.1"); + + assertNotNull(result); + assertTrue(result.size() > 0); + Reaction resultReaction = (Reaction) result.get(0); + assertTrue(resultReaction.getIdReaction().contains("test-name")); } @Test public void testQueryName2() throws Exception { - try { - Model model = createFullModel(); - model.getModelData().setId(-13); - List<BioEntity> result = searchService.searchByQuery(model, - indexer.getQueryStringForIndex("BCL-2", speciesSearchReversePrefix.keySet()), 50, null, "127.0.0.1"); - assertNotNull(result); - assertTrue(result.size() > 0); - Species alias = (Species) result.get(0); - assertTrue("Invalid alias: " + alias.getName(), alias.getName().toUpperCase().contains("BCL")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Model model = createFullModel(); + model.getModelData().setId(-13); + List<BioEntity> result = searchService.searchByQuery(model, + indexer.getQueryStringForIndex("BCL-2", speciesSearchReversePrefix.keySet()), 50, null, "127.0.0.1"); + assertNotNull(result); + assertTrue(result.size() > 0); + Species alias = (Species) result.get(0); + assertTrue("Invalid alias: " + alias.getName(), alias.getName().toUpperCase().contains("BCL")); } @Test public void testQueryName3() throws Exception { - try { - Model model = createFullModel(); - List<BioEntity> result = searchService.searchByQuery(model, "fdhgjkhdsfsdhfgfhsd", 50, null, "127.0.0.1"); - - assertNotNull(result); - assertEquals(0, result.size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Model model = createFullModel(); + List<BioEntity> result = searchService.searchByQuery(model, "fdhgjkhdsfsdhfgfhsd", 50, null, "127.0.0.1"); + + assertNotNull(result); + assertEquals(0, result.size()); } @Test public void testQueryName4() throws Exception { - try { - Model model = createFullModel(); - List<BioEntity> result = searchService.searchByQuery(model, - indexer.getQueryStringForIndex("protein:BCL-2", speciesSearchReversePrefix.keySet()), 50, null, "127.0.0.1"); - assertNotNull(result); - assertTrue(result.size() > 0); - Species alias = (Species) result.get(0); - assertTrue("Invalid alias: " + alias.getName(), alias.getName().toUpperCase().contains("BCL")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Model model = createFullModel(); + List<BioEntity> result = searchService.searchByQuery(model, + indexer.getQueryStringForIndex("protein:BCL-2", speciesSearchReversePrefix.keySet()), 50, null, "127.0.0.1"); + assertNotNull(result); + assertTrue(result.size() > 0); + Species alias = (Species) result.get(0); + assertTrue("Invalid alias: " + alias.getName(), alias.getName().toUpperCase().contains("BCL")); } @Test public void testSearchClosest() throws Exception { - try { - Model model = getModelForFile("testFiles/graph_path_example3.xml", true); - List<BioEntity> elements = searchService.getClosestElements(model, new Point2D.Double(0, 0), 5, false, - new ArrayList<>()); - assertNotNull(elements); - assertEquals(5, elements.size()); - assertTrue(elements.get(0) instanceof Species); - Species sAlias = (Species) elements.get(0); - assertEquals("s1", sAlias.getName()); - assertTrue(elements.get(1) instanceof Reaction); - Reaction reaction = (Reaction) elements.get(1); - assertEquals("re1", reaction.getIdReaction()); - assertTrue(elements.get(2) instanceof Species); - sAlias = (Species) elements.get(2); - assertEquals("s3", sAlias.getName()); - assertTrue(elements.get(3) instanceof Reaction); - reaction = (Reaction) elements.get(3); - assertEquals("re2", reaction.getIdReaction()); - assertTrue(elements.get(4) instanceof Species); - sAlias = (Species) elements.get(4); - assertEquals("s2", sAlias.getName()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Model model = getModelForFile("testFiles/graph_path_example3.xml", true); + List<BioEntity> elements = searchService.getClosestElements(model, new Point2D.Double(0, 0), 5, false, + new ArrayList<>()); + assertNotNull(elements); + assertEquals(5, elements.size()); + assertTrue(elements.get(0) instanceof Species); + Species sAlias = (Species) elements.get(0); + assertEquals("s1", sAlias.getName()); + assertTrue(elements.get(1) instanceof Reaction); + Reaction reaction = (Reaction) elements.get(1); + assertEquals("re1", reaction.getIdReaction()); + assertTrue(elements.get(2) instanceof Species); + sAlias = (Species) elements.get(2); + assertEquals("s3", sAlias.getName()); + assertTrue(elements.get(3) instanceof Reaction); + reaction = (Reaction) elements.get(3); + assertEquals("re2", reaction.getIdReaction()); + assertTrue(elements.get(4) instanceof Species); + sAlias = (Species) elements.get(4); + assertEquals("s2", sAlias.getName()); } @Test public void testSearchClosestByZIndex() throws Exception { - try { - Model model = new ModelFullIndexed(null); - GenericProtein protein1 = createProtein(); - protein1.setZ(0); - model.addElement(protein1); - GenericProtein protein2 = createProtein(); - protein2.setZ(1); - model.addElement(protein2); - GenericProtein protein3 = createProtein(); - protein3.setZ(-1); - model.addElement(protein3); - - List<BioEntity> elements = searchService.getClosestElements(model, protein2.getCenter(), 5, false, - new ArrayList<>()); - assertNotNull(elements); - assertEquals(3, elements.size()); - assertEquals(protein2, elements.get(0)); - assertEquals(protein1, elements.get(1)); - assertEquals(protein3, elements.get(2)); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Model model = new ModelFullIndexed(null); + GenericProtein protein1 = createProtein(); + protein1.setZ(0); + model.addElement(protein1); + GenericProtein protein2 = createProtein(); + protein2.setZ(1); + model.addElement(protein2); + GenericProtein protein3 = createProtein(); + protein3.setZ(-1); + model.addElement(protein3); + + List<BioEntity> elements = searchService.getClosestElements(model, protein2.getCenter(), 5, false, + new ArrayList<>()); + assertNotNull(elements); + assertEquals(3, elements.size()); + assertEquals(protein2, elements.get(0)); + assertEquals(protein1, elements.get(1)); + assertEquals(protein3, elements.get(2)); } private GenericProtein createProtein() { @@ -366,166 +265,120 @@ public class SearchServiceTest extends ServiceTestFunctions { @Test public void testSearchClosestWithEmptyModel() throws Exception { - try { - Model model = new ModelFullIndexed(null); - List<BioEntity> elements = searchService.getClosestElements(model, new Point2D.Double(0, 0), 5, false, - new ArrayList<>()); - assertNotNull(elements); - assertEquals(0, elements.size()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Model model = new ModelFullIndexed(null); + List<BioEntity> elements = searchService.getClosestElements(model, new Point2D.Double(0, 0), 5, false, + new ArrayList<>()); + assertNotNull(elements); + assertEquals(0, elements.size()); } @Test public void testGetAutocompleList() { - try { - Model model = new ModelFullIndexed(null); - Species proteinAlias = new GenericProtein("a"); - proteinAlias.setName("PROT identifier"); - proteinAlias.getSynonyms().add("PROT synonym"); - proteinAlias.getSynonyms().add("another synonym"); - proteinAlias.setFullName("Protein common name"); - model.addElement(proteinAlias); - - SimpleMolecule alias = new SimpleMolecule("a2"); - alias.setName("Molecule2"); - model.addElement(alias); - - int oldVal = Configuration.getAutocompleteSize(); - Configuration.setAutocompleteSize(5); - - List<String> list = searchService.getAutocompleteList(model, "P"); - assertNotNull(list); - assertEquals(4, list.size()); - assertTrue(list.contains("PROT identifier".toLowerCase())); - assertTrue(list.contains("PROT synonym".toLowerCase())); - assertTrue(list.contains("Protein common name".toLowerCase())); - - list = searchService.getAutocompleteList(model, "PROTEIN"); - assertNotNull(list); - assertEquals(2, list.size()); - assertTrue(list.contains("Protein common name".toLowerCase())); - - list = searchService.getAutocompleteList(model, "m"); - assertNotNull(list); - assertEquals(2, list.size()); - assertTrue(list.contains("Molecule2".toLowerCase())); - - list = searchService.getAutocompleteList(model, "blablabla"); - assertNotNull(list); - assertEquals(0, list.size()); - - Configuration.setAutocompleteSize(oldVal); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - + Model model = new ModelFullIndexed(null); + Species proteinAlias = new GenericProtein("a"); + proteinAlias.setName("PROT identifier"); + proteinAlias.getSynonyms().add("PROT synonym"); + proteinAlias.getSynonyms().add("another synonym"); + proteinAlias.setFullName("Protein common name"); + model.addElement(proteinAlias); + + SimpleMolecule alias = new SimpleMolecule("a2"); + alias.setName("Molecule2"); + model.addElement(alias); + + int oldVal = Configuration.getAutocompleteSize(); + Configuration.setAutocompleteSize(5); + + List<String> list = searchService.getAutocompleteList(model, "P"); + assertNotNull(list); + assertEquals(4, list.size()); + assertTrue(list.contains("PROT identifier".toLowerCase())); + assertTrue(list.contains("PROT synonym".toLowerCase())); + assertTrue(list.contains("Protein common name".toLowerCase())); + + list = searchService.getAutocompleteList(model, "PROTEIN"); + assertNotNull(list); + assertEquals(2, list.size()); + assertTrue(list.contains("Protein common name".toLowerCase())); + + list = searchService.getAutocompleteList(model, "m"); + assertNotNull(list); + assertEquals(2, list.size()); + assertTrue(list.contains("Molecule2".toLowerCase())); + + list = searchService.getAutocompleteList(model, "blablabla"); + assertNotNull(list); + assertEquals(0, list.size()); + + Configuration.setAutocompleteSize(oldVal); } @Test public void testGetAutocompleList2() { - try { - Model model = new ModelFullIndexed(null); - GenericProtein proteinAlias = new GenericProtein("a1"); - proteinAlias.setName("PROT identifier"); - proteinAlias.setNotes("Synonyms: PROT synonym, another synonym\nName: Protein common name"); - model.addElement(proteinAlias); - - SimpleMolecule alias = new SimpleMolecule("a2"); - alias.setName("Molecule2"); - model.addElement(alias); - - List<String> list = searchService.getAutocompleteList(model, "PROT identifier"); - assertNotNull(list); - assertEquals(1, list.size()); - assertTrue(list.get(0).equalsIgnoreCase("PROT identifier")); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - + Model model = new ModelFullIndexed(null); + GenericProtein proteinAlias = new GenericProtein("a1"); + proteinAlias.setName("PROT identifier"); + proteinAlias.setNotes("Synonyms: PROT synonym, another synonym\nName: Protein common name"); + model.addElement(proteinAlias); + + SimpleMolecule alias = new SimpleMolecule("a2"); + alias.setName("Molecule2"); + model.addElement(alias); + + List<String> list = searchService.getAutocompleteList(model, "PROT identifier"); + assertNotNull(list); + assertEquals(1, list.size()); + assertTrue(list.get(0).equalsIgnoreCase("PROT identifier")); } @Test public void testSearchGenericProtein() throws Exception { - try { - Model model = getModelForFile("testFiles/generic.xml", true); - - List<String> list = searchService.getAutocompleteList(model, "generic"); - assertNotNull(list); - assertEquals(2, list.size()); - assertTrue(list.contains("generic")); - assertTrue(list.contains("generic protein")); + Model model = getModelForFile("testFiles/generic.xml", true); - List<BioEntity> result = searchService.searchByQuery(model, "generic protein", 10, false, null); - assertNotNull(result); + List<String> list = searchService.getAutocompleteList(model, "generic"); + assertNotNull(list); + assertEquals(2, list.size()); + assertTrue(list.contains("generic")); + assertTrue(list.contains("generic protein")); - assertTrue(result.size() > 0); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + List<BioEntity> result = searchService.searchByQuery(model, "generic protein", 10, false, null); + assertNotNull(result); + assertTrue(result.size() > 0); } @Test public void testGetMiriamTypeForQuery() throws Exception { - try { - MiriamData md = new SearchService(null, null).getMiriamTypeForQuery("hgnc:SNCA"); - assertNotNull(md); - assertEquals(MiriamType.HGNC, md.getDataType()); - assertEquals("SNCA", md.getResource()); - - md = new SearchService(null, null).getMiriamTypeForQuery("reactome:REACT_15128"); - assertNotNull(md); - assertEquals(MiriamType.REACTOME, md.getDataType()); - assertEquals("REACT_15128", md.getResource()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - + MiriamData md = new SearchService(null, null).getMiriamTypeForQuery("hgnc:SNCA"); + assertNotNull(md); + assertEquals(MiriamType.HGNC, md.getDataType()); + assertEquals("SNCA", md.getResource()); + + md = new SearchService(null, null).getMiriamTypeForQuery("reactome:REACT_15128"); + assertNotNull(md); + assertEquals(MiriamType.REACTOME, md.getDataType()); + assertEquals("REACT_15128", md.getResource()); } @Test public void testSearchByMiriamInSubmap() throws Exception { - try { - String query = "HGNC_SYMBOL:SNCA"; - Model model = new ModelFullIndexed(null); - Model submodel = new ModelFullIndexed(null); - GenericProtein protein = new GenericProtein("s1"); - protein.addMiriamData(new MiriamData(MiriamType.HGNC_SYMBOL, "SNCA")); - submodel.addElement(protein); - model.addSubmodelConnection(new ModelSubmodelConnection(submodel, SubmodelType.UNKNOWN)); + String query = "HGNC_SYMBOL:SNCA"; + Model model = new ModelFullIndexed(null); + Model submodel = new ModelFullIndexed(null); + GenericProtein protein = new GenericProtein("s1"); + protein.addMiriamData(new MiriamData(MiriamType.HGNC_SYMBOL, "SNCA")); + submodel.addElement(protein); + model.addSubmodelConnection(new ModelSubmodelConnection(submodel, SubmodelType.UNKNOWN)); - List<BioEntity> result = searchService.searchByQuery(model, query, 50, null, "127.0.0.1"); - - assertEquals(1, result.size()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + List<BioEntity> result = searchService.searchByQuery(model, query, 50, null, "127.0.0.1"); + assertEquals(1, result.size()); } @Test public void testGetMiriamTypeForQuery2() throws Exception { - try { - MiriamData md = new SearchService(null, null).getMiriamTypeForQuery("UNKNOWN_HGNC:SNCA"); - assertNull(md); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - + MiriamData md = new SearchService(null, null).getMiriamTypeForQuery("UNKNOWN_HGNC:SNCA"); + assertNull(md); } } diff --git a/service/src/test/java/lcsb/mapviewer/services/impl/UserServiceTest.java b/service/src/test/java/lcsb/mapviewer/services/impl/UserServiceTest.java index 4d7f5f488a4b0fcb3ded0b0c41eff7755ff8b930..f74dfdf93763ac7d8e3d1e2200eb19abbcd00d1c 100644 --- a/service/src/test/java/lcsb/mapviewer/services/impl/UserServiceTest.java +++ b/service/src/test/java/lcsb/mapviewer/services/impl/UserServiceTest.java @@ -139,32 +139,25 @@ public class UserServiceTest extends ServiceTestFunctions { assertFalse(user2.getPrivileges().contains(privilege)); } - @Test public void testAddUser() throws Exception { - try { - long logCount = getInfos().size(); - User user2 = new User(); - user2.setLogin("login"); - user2.setCryptedPassword(""); - userService.addUser(user2); - assertNotNull(user2.getId()); - long logCount2 = getInfos().size(); - assertEquals("Log entry is missing for add user event", logCount + 1, logCount2); - userDao.evict(user2); - User user3 = userService.getUserByLogin(user2.getLogin()); - assertNotNull(user3); - userService.deleteUser(user3); - user3 = userService.getUserByLogin(user2.getLogin()); - assertNull(user3); - - long logCount3 = getInfos().size(); - assertEquals("Log entry is missing for remove user event", logCount2 + 1, logCount3); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + long logCount = getInfos().size(); + User user2 = new User(); + user2.setCryptedPassword(""); + user2.setLogin("login"); + userService.addUser(user2); + assertNotNull(user2.getId()); + long logCount2 = getInfos().size(); + assertEquals("Log entry is missing for add user event", logCount + 1, logCount2); + userDao.evict(user2); + User user3 = userService.getUserByLogin(user2.getLogin()); + assertNotNull(user3); + userService.deleteUser(user3); + user3 = userService.getUserByLogin(user2.getLogin()); + assertNull(user3); + + long logCount3 = getInfos().size(); + assertEquals("Log entry is missing for remove user event", logCount2 + 1, logCount3); } } diff --git a/service/src/test/java/lcsb/mapviewer/services/overlay/AllOverlayTests.java b/service/src/test/java/lcsb/mapviewer/services/overlay/AllOverlayTests.java index 0f5eedc1882f88e3fa72d6491200145aa06731bd..0d0d1de8ce4003f9cacf3501f324b63f231620e5 100644 --- a/service/src/test/java/lcsb/mapviewer/services/overlay/AllOverlayTests.java +++ b/service/src/test/java/lcsb/mapviewer/services/overlay/AllOverlayTests.java @@ -6,8 +6,6 @@ import org.junit.runners.Suite.SuiteClasses; @RunWith(Suite.class) @SuiteClasses({ AnnotatedObjectTreeRowTest.class, - ChebiTreeRowTest.class, - IconManagerTest.class, }) public class AllOverlayTests { diff --git a/service/src/test/java/lcsb/mapviewer/services/overlay/AnnotatedObjectTreeRowTest.java b/service/src/test/java/lcsb/mapviewer/services/overlay/AnnotatedObjectTreeRowTest.java index f8e6609b5e5578722f2e969cb786f0b85f4aa4b8..3866029c0539c036b18ee4b9a88c281343988215 100644 --- a/service/src/test/java/lcsb/mapviewer/services/overlay/AnnotatedObjectTreeRowTest.java +++ b/service/src/test/java/lcsb/mapviewer/services/overlay/AnnotatedObjectTreeRowTest.java @@ -1,31 +1,24 @@ package lcsb.mapviewer.services.overlay; -import lcsb.mapviewer.modelutils.map.ClassTreeNode; - import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; -public class AnnotatedObjectTreeRowTest { +import lcsb.mapviewer.modelutils.map.ClassTreeNode; +import lcsb.mapviewer.services.ServiceTestFunctions; - @Before - public void setUp() throws Exception { - } +public class AnnotatedObjectTreeRowTest extends ServiceTestFunctions { - @After - public void tearDown() throws Exception { - } + @Before + public void setUp() throws Exception { + } - @Test - public void testSerialization() { - try { - SerializationUtils.serialize(new AnnotatedObjectTreeRow(new ClassTreeNode(Object.class))); + @After + public void tearDown() throws Exception { + } - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } + @Test + public void testSerialization() { + SerializationUtils.serialize(new AnnotatedObjectTreeRow(new ClassTreeNode(Object.class))); + } } diff --git a/service/src/test/java/lcsb/mapviewer/services/overlay/ChebiTreeRowTest.java b/service/src/test/java/lcsb/mapviewer/services/overlay/ChebiTreeRowTest.java deleted file mode 100644 index 5c3f1795f211811427156011e544c0d82b2cb4b0..0000000000000000000000000000000000000000 --- a/service/src/test/java/lcsb/mapviewer/services/overlay/ChebiTreeRowTest.java +++ /dev/null @@ -1,29 +0,0 @@ -package lcsb.mapviewer.services.overlay; - -import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -public class ChebiTreeRowTest { - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testSerialization() { - try { - SerializationUtils.serialize(new ChebiTreeRow(null,null,null,null)); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - -} diff --git a/service/src/test/java/lcsb/mapviewer/services/overlay/IconManagerTest.java b/service/src/test/java/lcsb/mapviewer/services/overlay/IconManagerTest.java deleted file mode 100644 index d030a8f1c4810e5d5a8f990ccf8cc8c55c24b717..0000000000000000000000000000000000000000 --- a/service/src/test/java/lcsb/mapviewer/services/overlay/IconManagerTest.java +++ /dev/null @@ -1,47 +0,0 @@ -package lcsb.mapviewer.services.overlay; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -public class IconManagerTest { - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void test() { - IconManager im = IconManager.getInstance(); - assertNotNull(im); - String icon1 = im.getIconForIndex(0, IconType.SEARCH, 0); - String icon2 = im.getIconForIndex(1, IconType.SEARCH, 0); - assertFalse(icon1.equals(icon2)); - } - - @Test - public void test1() { - IconManager im = IconManager.getInstance(); - assertNotNull(im); - String icon1 = im.getIconForIndex(0, IconType.SEARCH, 0); - String icon2 = im.getIconForIndex(0, IconType.DRUG, 0); - assertFalse(icon1.equals(icon2)); - } - - @Test - public void test2() { - IconManager im = IconManager.getInstance(); - assertNotNull(im); - String icon1 = im.getIconForIndex(0, IconType.SEARCH, 0); - String icon2 = im.getIconForIndex(0, IconType.SEARCH, 1); - assertFalse(icon1.equals(icon2)); - } - -} diff --git a/service/src/test/java/lcsb/mapviewer/services/search/chemical/ChemicalServiceTest.java b/service/src/test/java/lcsb/mapviewer/services/search/chemical/ChemicalServiceTest.java index eec6fdde3e376c5c7ca8c8dcd6b8a2c977fa3588..15d6f88c05c5cf85f456755e3f0303f61c3cdcd6 100644 --- a/service/src/test/java/lcsb/mapviewer/services/search/chemical/ChemicalServiceTest.java +++ b/service/src/test/java/lcsb/mapviewer/services/search/chemical/ChemicalServiceTest.java @@ -1,17 +1,13 @@ package lcsb.mapviewer.services.search.chemical; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.Assert.*; import java.util.ArrayList; import java.util.List; -import org.apache.logging.log4j.*; -import org.junit.After; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.junit.*; import lcsb.mapviewer.annotation.data.Chemical; import lcsb.mapviewer.model.map.MiriamData; @@ -35,41 +31,30 @@ public class ChemicalServiceTest extends ServiceTestFunctions { @Test public void testgetChemicalByName() throws Exception { - try { - MiriamData pdDiseaseID = new MiriamData(MiriamType.MESH_2012, "D010300"); - String name = "GSSG"; - Chemical result = chemicalService.getByName(name, new DbSearchCriteria().disease(pdDiseaseID)); - assertNotNull(result); - assertEquals("D019803", result.getChemicalId().getResource()); + MiriamData pdDiseaseID = new MiriamData(MiriamType.MESH_2012, "D010300"); + String name = "GSSG"; + Chemical result = chemicalService.getByName(name, new DbSearchCriteria().disease(pdDiseaseID)); + assertNotNull(result); + assertEquals("D019803", result.getChemicalId().getResource()); - assertEquals("No warnings expected.", 0, getWarnings().size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals("No warnings expected.", 0, getWarnings().size()); } @Test public void testSearchByElements() throws Exception { - try { - List<Element> elements = new ArrayList<>(); - Rna protein = new Rna("id"); - protein.setName("GCH1"); - MiriamData dystoniaDisease = new MiriamData(MiriamType.MESH_2012, "C538007"); + List<Element> elements = new ArrayList<>(); + Rna protein = new Rna("id"); + protein.setName("GCH1"); + MiriamData dystoniaDisease = new MiriamData(MiriamType.MESH_2012, "C538007"); - elements.add(protein); + elements.add(protein); - List<Chemical> chemicals = chemicalService.getForTargets(elements, - new DbSearchCriteria().disease(dystoniaDisease)); - assertNotNull(chemicals); - assertTrue(chemicals.size() > 0); - - assertEquals("No warnings expected.", 0, getWarnings().size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + List<Chemical> chemicals = chemicalService.getForTargets(elements, + new DbSearchCriteria().disease(dystoniaDisease)); + assertNotNull(chemicals); + assertTrue(chemicals.size() > 0); + assertEquals("No warnings expected.", 0, getWarnings().size()); } } diff --git a/service/src/test/java/lcsb/mapviewer/services/search/drug/DrugServiceTest.java b/service/src/test/java/lcsb/mapviewer/services/search/drug/DrugServiceTest.java index 0b23329eb18251ac1befdd522b7673a10af125f8..ed04915bfc95cbdb94b8628b3a70b6a0bb6addd7 100644 --- a/service/src/test/java/lcsb/mapviewer/services/search/drug/DrugServiceTest.java +++ b/service/src/test/java/lcsb/mapviewer/services/search/drug/DrugServiceTest.java @@ -1,20 +1,12 @@ package lcsb.mapviewer.services.search.drug; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import org.apache.logging.log4j.*; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import static org.junit.Assert.*; + +import java.util.*; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.junit.*; import org.springframework.beans.factory.annotation.Autowired; import lcsb.mapviewer.annotation.data.Drug; @@ -25,9 +17,7 @@ import lcsb.mapviewer.model.map.MiriamData; import lcsb.mapviewer.model.map.MiriamType; import lcsb.mapviewer.model.map.model.Model; import lcsb.mapviewer.model.map.model.ModelFullIndexed; -import lcsb.mapviewer.model.map.species.Element; -import lcsb.mapviewer.model.map.species.GenericProtein; -import lcsb.mapviewer.model.map.species.Protein; +import lcsb.mapviewer.model.map.species.*; import lcsb.mapviewer.persist.dao.map.species.ElementDao; import lcsb.mapviewer.services.ServiceTestFunctions; import lcsb.mapviewer.services.search.DbSearchCriteria; @@ -48,234 +38,160 @@ public class DrugServiceTest extends ServiceTestFunctions { @Test public void testGetEmpty() throws Exception { - try { - Drug drug = drugService.getByName("blablablabla", new DbSearchCriteria()); - assertNull(drug); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Drug drug = drugService.getByName("blablablabla", new DbSearchCriteria()); + assertNull(drug); } @Test public void testGetTargets() throws Exception { - try { - long count = searchHistoryDao.getCount(); - Model model = new ModelFullIndexed(null); - Project project = new Project(); - project.setProjectId("TesT"); - project.addModel(model); - Drug drug = drugService.getByName("Diazoxide", new DbSearchCriteria().project(project).ipAddress("ip")); - assertNotNull(drug); - assertNotNull(drug.getName()); - assertFalse(drug.getName().trim().equals("")); - assertNotNull(drug.getDescription()); - assertFalse(drug.getDescription().trim().equals("")); - - String hgnc1 = "SLC12A3"; - String hgnc2 = "KCNJ8"; - - boolean hgnc1Exists = false; - boolean hgnc2Exists = false; - - for (Target target : drug.getTargets()) { - for (MiriamData row : target.getGenes()) { - if (row.getResource().equalsIgnoreCase(hgnc1)) - hgnc1Exists = true; - if (row.getResource().equalsIgnoreCase(hgnc2)) - hgnc2Exists = true; - } + long count = searchHistoryDao.getCount(); + Model model = new ModelFullIndexed(null); + Project project = new Project(); + project.setProjectId("TesT"); + project.addModel(model); + Drug drug = drugService.getByName("Diazoxide", new DbSearchCriteria().project(project).ipAddress("ip")); + assertNotNull(drug); + assertNotNull(drug.getName()); + assertFalse(drug.getName().trim().equals("")); + assertNotNull(drug.getDescription()); + assertFalse(drug.getDescription().trim().equals("")); + + String hgnc1 = "SLC12A3"; + String hgnc2 = "KCNJ8"; + + boolean hgnc1Exists = false; + boolean hgnc2Exists = false; + + for (Target target : drug.getTargets()) { + for (MiriamData row : target.getGenes()) { + if (row.getResource().equalsIgnoreCase(hgnc1)) + hgnc1Exists = true; + if (row.getResource().equalsIgnoreCase(hgnc2)) + hgnc2Exists = true; } + } - assertTrue("Target " + hgnc1 + " doesn't exist in target list but should", hgnc1Exists); - assertTrue("Target " + hgnc2 + " doesn't exist in target list but should", hgnc2Exists); - - long count2 = searchHistoryDao.getCount(); + assertTrue("Target " + hgnc1 + " doesn't exist in target list but should", hgnc1Exists); + assertTrue("Target " + hgnc2 + " doesn't exist in target list but should", hgnc2Exists); - assertEquals(count + 1, count2); + long count2 = searchHistoryDao.getCount(); - assertEquals("YES", drug.getBloodBrainBarrier()); + assertEquals(count + 1, count2); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertEquals("YES", drug.getBloodBrainBarrier()); } @Test public void testGetTargetsBySynonym() throws Exception { - try { - // search by synonym - Drug drug = drugService.getByName("Amantidine", new DbSearchCriteria().ipAddress("ip")); - // search by name - Drug drug2 = drugService.getByName("Amantadine", new DbSearchCriteria().ipAddress("ip")); - assertNotNull(drug); - assertNotNull(drug.getName()); - assertFalse(drug.getName().trim().equals("")); - assertNotNull(drug.getDescription()); - assertFalse(drug.getDescription().trim().equals("")); - - // number of targets should be the same - assertEquals(drug.getTargets().size(), drug2.getTargets().size()); - assertTrue(drug.getTargets().size() > 0); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + // search by synonym + Drug drug = drugService.getByName("Amantidine", new DbSearchCriteria().ipAddress("ip")); + // search by name + Drug drug2 = drugService.getByName("Amantadine", new DbSearchCriteria().ipAddress("ip")); + assertNotNull(drug); + assertNotNull(drug.getName()); + assertFalse(drug.getName().trim().equals("")); + assertNotNull(drug.getDescription()); + assertFalse(drug.getDescription().trim().equals("")); + + // number of targets should be the same + assertEquals(drug.getTargets().size(), drug2.getTargets().size()); + assertTrue(drug.getTargets().size() > 0); } @Test public void testFindDrugSelegiline() throws Exception { - try { - Drug test = drugService.getByName("Selegiline", - new DbSearchCriteria().ipAddress("ip").organisms(TaxonomyBackend.HUMAN_TAXONOMY)); - assertNotNull(test); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Drug test = drugService.getByName("Selegiline", + new DbSearchCriteria().ipAddress("ip").organisms(TaxonomyBackend.HUMAN_TAXONOMY)); + assertNotNull(test); } @Test public void testAnnotationsInDrug() throws Exception { - try { - Drug test = drugService.getByName("Selegiline", new DbSearchCriteria().organisms(TaxonomyBackend.HUMAN_TAXONOMY)); - assertNotNull(test); - for (Target target : test.getTargets()) { - for (MiriamData md : target.getGenes()) { - assertNull(md.getAnnotator()); - } + Drug test = drugService.getByName("Selegiline", new DbSearchCriteria().organisms(TaxonomyBackend.HUMAN_TAXONOMY)); + assertNotNull(test); + for (Target target : test.getTargets()) { + for (MiriamData md : target.getGenes()) { + assertNull(md.getAnnotator()); } - } catch (Exception e) { - e.printStackTrace(); - throw e; } } @Test public void testDornaseAplha() throws Exception { - try { - Drug drug = drugService.getByName("Dornase alpha", new DbSearchCriteria()); - assertNotNull(drug.getName()); - assertEquals("N/A", drug.getBloodBrainBarrier()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - + Drug drug = drugService.getByName("Dornase alpha", new DbSearchCriteria()); + assertNotNull(drug.getName()); + assertEquals("N/A", drug.getBloodBrainBarrier()); } @Test public void testRapamycin() throws Exception { - try { - Drug drug = drugService.getByName("Rapamycin", new DbSearchCriteria()); - assertNotNull(drug.getName()); - assertEquals("NO", drug.getBloodBrainBarrier()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - + Drug drug = drugService.getByName("Rapamycin", new DbSearchCriteria()); + assertNotNull(drug.getName()); + assertEquals("NO", drug.getBloodBrainBarrier()); } @Test public void testSearchByElements() throws Exception { - try { - List<Element> elements = new ArrayList<>(); - List<Drug> drugs = drugService.getForTargets(elements, new DbSearchCriteria()); - assertNotNull(drugs); - assertEquals(0, drugs.size()); - - Protein protein = new GenericProtein("id"); - protein.setName("DRD2"); - protein.addMiriamData(new MiriamData(MiriamType.HGNC_SYMBOL, "SIRT3")); - elements.add(protein); - - drugs = drugService.getForTargets(elements, new DbSearchCriteria()); - assertNotNull(drugs); - assertTrue(drugs.size() > 0); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - + List<Element> elements = new ArrayList<>(); + List<Drug> drugs = drugService.getForTargets(elements, new DbSearchCriteria()); + assertNotNull(drugs); + assertEquals(0, drugs.size()); + + Protein protein = new GenericProtein("id"); + protein.setName("DRD2"); + protein.addMiriamData(new MiriamData(MiriamType.HGNC_SYMBOL, "SIRT3")); + elements.add(protein); + + drugs = drugService.getForTargets(elements, new DbSearchCriteria()); + assertNotNull(drugs); + assertTrue(drugs.size() > 0); } - @Test public void testSearchByElements3() throws Exception { - try { - List<Element> elements = new ArrayList<>(); - Protein protein = new GenericProtein("id"); - protein.setName("SIRT3"); - protein.addMiriamData(new MiriamData(MiriamType.HGNC_SYMBOL, "SIRT3")); - protein.addMiriamData(new MiriamData(MiriamType.ENTREZ, "23410")); - elements.add(protein); - List<Drug> drugs = drugService.getForTargets(elements, new DbSearchCriteria()); - - assertNotNull(drugs); - assertTrue(drugs.size() > 0); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - + List<Element> elements = new ArrayList<>(); + Protein protein = new GenericProtein("id"); + protein.setName("SIRT3"); + protein.addMiriamData(new MiriamData(MiriamType.HGNC_SYMBOL, "SIRT3")); + protein.addMiriamData(new MiriamData(MiriamType.ENTREZ, "23410")); + elements.add(protein); + List<Drug> drugs = drugService.getForTargets(elements, new DbSearchCriteria()); + + assertNotNull(drugs); + assertTrue(drugs.size() > 0); } @Test public void testObjectToDrugTargetList() throws Exception { - try { - Drug drug = drugService.getByName("AMANTADINE", new DbSearchCriteria()); - Drug drug2 = drugBankHTMLParser.findDrug("AMANTADINE"); - - assertTrue(drug2.getTargets().size() <= drug.getTargets().size()); + Drug drug = drugService.getByName("AMANTADINE", new DbSearchCriteria()); + Drug drug2 = drugBankHTMLParser.findDrug("AMANTADINE"); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertTrue(drug2.getTargets().size() <= drug.getTargets().size()); } @Test public void testAspirinToDrugTargetList() throws Exception { - try { - Drug drug = drugService.getByName("Aspirin", new DbSearchCriteria()); - Drug drug2 = drugBankHTMLParser.findDrug("Aspirin"); - - assertTrue(drug2.getTargets().size() <= drug.getTargets().size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Drug drug = drugService.getByName("Aspirin", new DbSearchCriteria()); + Drug drug2 = drugBankHTMLParser.findDrug("Aspirin"); + + assertTrue(drug2.getTargets().size() <= drug.getTargets().size()); } @Test public void testAspirinSynonyms() throws Exception { - try { - Drug drug = drugService.getByName("Aspirin", new DbSearchCriteria()); + Drug drug = drugService.getByName("Aspirin", new DbSearchCriteria()); - Set<String> synonyms = new HashSet<String>(); - for (String string : drug.getSynonyms()) { - assertFalse("Duplicate entry in drug synonym: " + string, synonyms.contains(string)); - synonyms.add(string); - } - - } catch (Exception e) { - e.printStackTrace(); - throw e; + Set<String> synonyms = new HashSet<String>(); + for (String string : drug.getSynonyms()) { + assertFalse("Duplicate entry in drug synonym: " + string, synonyms.contains(string)); + synonyms.add(string); } } @Test public void testGetSuggestedQueryList() throws Exception { - try { - List<String> result = drugService.getSuggestedQueryList(new Project(), null); - assertEquals(0, result.size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + List<String> result = drugService.getSuggestedQueryList(new Project(), null); + assertEquals(0, result.size()); } } diff --git a/service/src/test/java/lcsb/mapviewer/services/search/mirna/MiRNAServiceTest.java b/service/src/test/java/lcsb/mapviewer/services/search/mirna/MiRNAServiceTest.java index 915fa64a57783e9671ab98218a73924f5b154989..8a9f7a18f8aeb33c2b60a5bc78c76f312d8407d3 100644 --- a/service/src/test/java/lcsb/mapviewer/services/search/mirna/MiRNAServiceTest.java +++ b/service/src/test/java/lcsb/mapviewer/services/search/mirna/MiRNAServiceTest.java @@ -1,13 +1,10 @@ package lcsb.mapviewer.services.search.mirna; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.*; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.springframework.beans.factory.annotation.Autowired; import lcsb.mapviewer.annotation.data.MiRNA; @@ -37,38 +34,25 @@ public class MiRNAServiceTest extends ServiceTestFunctions { @Test public void testCacheStub() throws Exception { - try { - // CellDesignerXmlParser parser = new CellDesignerXmlParser(); - // Model model = parser.createModel(new - // ConverterParams().filename("testFiles/pd_full/PD_130909.xml")); - Model model = new ModelFullIndexed(null); - miRNAService.cacheDataForModel(model, new IProgressUpdater() { - @Override - public void setProgress(double progress) { - logger.debug("Progress: " + progress); - } - }); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Model model = new ModelFullIndexed(null); + miRNAService.cacheDataForModel(model, new IProgressUpdater() { + @Override + public void setProgress(double progress) { + logger.debug("Progress: " + progress); + } + }); } @Test public void testFindMiRNAFilteredByOrganism() throws Exception { - try { - MiRNA test = miRNAService.getByName("hsa-miR-29a-3p", - new DbSearchCriteria().organisms(TaxonomyBackend.HUMAN_TAXONOMY)); - assertNotNull(test); - for (Target t : test.getTargets()) { - for (MiriamData md : t.getGenes()) { - assertEquals("Only hgnc symbols should be used for gene annotations", MiriamType.HGNC_SYMBOL, - md.getDataType()); - } + MiRNA test = miRNAService.getByName("hsa-miR-29a-3p", + new DbSearchCriteria().organisms(TaxonomyBackend.HUMAN_TAXONOMY)); + assertNotNull(test); + for (Target t : test.getTargets()) { + for (MiriamData md : t.getGenes()) { + assertEquals("Only hgnc symbols should be used for gene annotations", MiriamType.HGNC_SYMBOL, + md.getDataType()); } - } catch (Exception e) { - e.printStackTrace(); - throw e; } } diff --git a/service/src/test/java/lcsb/mapviewer/services/utils/ColorSchemaReaderTest.java b/service/src/test/java/lcsb/mapviewer/services/utils/ColorSchemaReaderTest.java index 57fd3ef5684ee60203a48e649d18f6f1207a4735..55fc71dbc6b0ab96382fcfd078d7d89027be8e53 100644 --- a/service/src/test/java/lcsb/mapviewer/services/utils/ColorSchemaReaderTest.java +++ b/service/src/test/java/lcsb/mapviewer/services/utils/ColorSchemaReaderTest.java @@ -1,40 +1,22 @@ package lcsb.mapviewer.services.utils; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import java.awt.Color; -import java.io.ByteArrayInputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; +import java.io.*; import java.nio.charset.StandardCharsets; -import java.util.Collection; -import java.util.HashMap; -import java.util.List; -import java.util.Map; +import java.util.*; import org.apache.commons.io.output.ByteArrayOutputStream; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import lcsb.mapviewer.commands.ColorExtractor; import lcsb.mapviewer.commands.ColorModelCommand; import lcsb.mapviewer.common.TextFileUtils; import lcsb.mapviewer.model.map.MiriamData; -import lcsb.mapviewer.model.map.layout.ColorSchema; -import lcsb.mapviewer.model.map.layout.GeneVariation; -import lcsb.mapviewer.model.map.layout.GeneVariationColorSchema; -import lcsb.mapviewer.model.map.layout.InvalidColorSchemaException; +import lcsb.mapviewer.model.map.layout.*; import lcsb.mapviewer.model.map.model.Model; import lcsb.mapviewer.model.map.species.Element; import lcsb.mapviewer.services.ServiceTestFunctions; @@ -55,62 +37,46 @@ public class ColorSchemaReaderTest extends ServiceTestFunctions { @Test public void testReadSchema() throws Exception { - try { - Collection<ColorSchema> schemas = reader.readColorSchema("testFiles/enricoData/ageing.txt"); + Collection<ColorSchema> schemas = reader.readColorSchema("testFiles/enricoData/ageing.txt"); - assertNotNull(schemas); - assertEquals(412, schemas.size()); + assertNotNull(schemas); + assertEquals(412, schemas.size()); - schemas = reader.readColorSchema("testFiles/enricoData/ge001.txt"); + schemas = reader.readColorSchema("testFiles/enricoData/ge001.txt"); - assertNotNull(schemas); - assertEquals(3057, schemas.size()); + assertNotNull(schemas); + assertEquals(3057, schemas.size()); - schemas = reader.readColorSchema("testFiles/enricoData/ge005.txt"); + schemas = reader.readColorSchema("testFiles/enricoData/ge005.txt"); - assertNotNull(schemas); - assertEquals(4338, schemas.size()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertNotNull(schemas); + assertEquals(4338, schemas.size()); } @Test public void testReadGeneVariantsSchema() throws Exception { - try { - File f = new File("testFiles/coloring/gene_variants.txt"); - byte[] data = fileToByteArray(f); - - ByteArrayInputStream bin = new ByteArrayInputStream(data); - - Collection<ColorSchema> schemas = reader.readColorSchema(bin, - TextFileUtils.getHeaderParametersFromFile(new ByteArrayInputStream(data))); - assertNotNull(schemas); - assertEquals(3, schemas.size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + File f = new File("testFiles/coloring/gene_variants.txt"); + byte[] data = fileToByteArray(f); + + ByteArrayInputStream bin = new ByteArrayInputStream(data); + + Collection<ColorSchema> schemas = reader.readColorSchema(bin, + TextFileUtils.getHeaderParametersFromFile(new ByteArrayInputStream(data))); + assertNotNull(schemas); + assertEquals(3, schemas.size()); } @Test public void testReadGeneVariantByIdSchema() throws Exception { - try { - File f = new File("testFiles/coloring/gene_variants_id.txt"); - byte[] data = fileToByteArray(f); - - ByteArrayInputStream bin = new ByteArrayInputStream(data); - - Collection<ColorSchema> schemas = reader.readColorSchema(bin, - TextFileUtils.getHeaderParametersFromFile(new ByteArrayInputStream(data))); - assertNotNull(schemas); - assertEquals(1, schemas.size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + File f = new File("testFiles/coloring/gene_variants_id.txt"); + byte[] data = fileToByteArray(f); + + ByteArrayInputStream bin = new ByteArrayInputStream(data); + + Collection<ColorSchema> schemas = reader.readColorSchema(bin, + TextFileUtils.getHeaderParametersFromFile(new ByteArrayInputStream(data))); + assertNotNull(schemas); + assertEquals(1, schemas.size()); } private byte[] fileToByteArray(File f) throws FileNotFoundException, IOException { @@ -134,308 +100,197 @@ public class ColorSchemaReaderTest extends ServiceTestFunctions { @Test public void testReadGeneVariantsWithAminoAcidChange() throws Exception { - try { - File f = new File("testFiles/coloring/gene_variants_aa_change.txt"); - byte[] data = fileToByteArray(f); - - ByteArrayInputStream bin = new ByteArrayInputStream(data); - - Collection<ColorSchema> schemas = reader.readColorSchema(bin, - TextFileUtils.getHeaderParametersFromFile(new ByteArrayInputStream(data))); - assertNotNull(schemas); - assertEquals(2, schemas.size()); - GeneVariationColorSchema schema = (GeneVariationColorSchema) schemas.iterator().next(); - boolean aaChangeFound = false; - for (GeneVariation geneVariant : schema.getGeneVariations()) { - if (geneVariant.getAminoAcidChange() != null && !geneVariant.getAminoAcidChange().trim().isEmpty()) { - aaChangeFound = true; - } + File f = new File("testFiles/coloring/gene_variants_aa_change.txt"); + byte[] data = fileToByteArray(f); + + ByteArrayInputStream bin = new ByteArrayInputStream(data); + + Collection<ColorSchema> schemas = reader.readColorSchema(bin, + TextFileUtils.getHeaderParametersFromFile(new ByteArrayInputStream(data))); + assertNotNull(schemas); + assertEquals(2, schemas.size()); + GeneVariationColorSchema schema = (GeneVariationColorSchema) schemas.iterator().next(); + boolean aaChangeFound = false; + for (GeneVariation geneVariant : schema.getGeneVariations()) { + if (geneVariant.getAminoAcidChange() != null && !geneVariant.getAminoAcidChange().trim().isEmpty()) { + aaChangeFound = true; } - assertTrue("Amino acid are not present in parsed data", aaChangeFound); - } catch (Exception e) { - e.printStackTrace(); - throw e; } + assertTrue("Amino acid are not present in parsed data", aaChangeFound); } @Test public void testReadGeneVariantsWithNewNamingSchema() throws Exception { - try { - File f = new File("testFiles/coloring/gene_variants_new_naming.txt"); - byte[] data = fileToByteArray(f); - - ByteArrayInputStream bin = new ByteArrayInputStream(data); - - Collection<ColorSchema> schemas = reader.readColorSchema(bin, - TextFileUtils.getHeaderParametersFromFile(new ByteArrayInputStream(data))); - assertNotNull(schemas); - assertEquals(3, schemas.size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + File f = new File("testFiles/coloring/gene_variants_new_naming.txt"); + byte[] data = fileToByteArray(f); + + ByteArrayInputStream bin = new ByteArrayInputStream(data); + + Collection<ColorSchema> schemas = reader.readColorSchema(bin, + TextFileUtils.getHeaderParametersFromFile(new ByteArrayInputStream(data))); + assertNotNull(schemas); + assertEquals(3, schemas.size()); } @Test public void testReadGeneVariantsSchemaWithAF() throws Exception { - try { - File f = new File("testFiles/coloring/gene_variants_all_freq.txt"); - byte[] data = fileToByteArray(f); - - ByteArrayInputStream bin = new ByteArrayInputStream(data); - - Collection<ColorSchema> schemas = reader.readColorSchema(bin, - TextFileUtils.getHeaderParametersFromFile(new ByteArrayInputStream(data))); - assertNotNull(schemas); - assertEquals(2, schemas.size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + File f = new File("testFiles/coloring/gene_variants_all_freq.txt"); + byte[] data = fileToByteArray(f); + + ByteArrayInputStream bin = new ByteArrayInputStream(data); + + Collection<ColorSchema> schemas = reader.readColorSchema(bin, + TextFileUtils.getHeaderParametersFromFile(new ByteArrayInputStream(data))); + assertNotNull(schemas); + assertEquals(2, schemas.size()); } - @Test + @Test(expected = InvalidColorSchemaException.class) public void testReadInvalidGeneVariantsSchema() throws Exception { - try { - reader.readColorSchema("testFiles/coloring/gene_variants_invalid_genome.txt"); - fail("Exception expected"); - } catch (InvalidColorSchemaException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + reader.readColorSchema("testFiles/coloring/gene_variants_invalid_genome.txt"); } @Test public void testReadSchema2() throws Exception { - try { - Collection<ColorSchema> schemas = reader.readColorSchema("testFiles/coloring/goodSchema.txt"); - - assertNotNull(schemas); - assertEquals(3, schemas.size()); + Collection<ColorSchema> schemas = reader.readColorSchema("testFiles/coloring/goodSchema.txt"); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertNotNull(schemas); + assertEquals(3, schemas.size()); } - @Test + @Test(expected = InvalidColorSchemaException.class) public void testReadSchema3() throws Exception { - try { - try { - reader.readColorSchema("testFiles/coloring/wrongSchema.txt"); - fail("Excepion expected"); - } catch (InvalidColorSchemaException e) { - } - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + reader.readColorSchema("testFiles/coloring/wrongSchema.txt"); } @Test public void testProblematicStephanSchema3() throws Exception { - try { - reader.readColorSchema("testFiles/coloring/problematicSchema.txt"); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + reader.readColorSchema("testFiles/coloring/problematicSchema.txt"); } @Test public void testReadReactionSchema() throws Exception { - try { - Collection<ColorSchema> collection = reader.readColorSchema("testFiles/coloring/reactionSchema.txt"); - assertEquals(1, collection.size()); - ColorSchema schema = collection.iterator().next(); - assertEquals("re1", schema.getElementId()); - assertEquals(3.0, schema.getLineWidth(), EPSILON); - assertEquals(Color.RED, schema.getColor()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Collection<ColorSchema> collection = reader.readColorSchema("testFiles/coloring/reactionSchema.txt"); + assertEquals(1, collection.size()); + ColorSchema schema = collection.iterator().next(); + assertEquals("re1", schema.getElementId()); + assertEquals(3.0, schema.getLineWidth(), EPSILON); + assertEquals(Color.RED, schema.getColor()); } @Test(timeout = 15000) public void testNextVersionReadSchema() throws Exception { - try { - Collection<ColorSchema> schemas = reader.readColorSchema("testFiles/coloring/goodLayout.v=1.0.txt"); - - assertNotNull(schemas); - assertEquals(3, schemas.size()); + Collection<ColorSchema> schemas = reader.readColorSchema("testFiles/coloring/goodLayout.v=1.0.txt"); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertNotNull(schemas); + assertEquals(3, schemas.size()); } @Test public void testColoring3() throws Exception { - try { - ColorExtractor colorExtractor = new ColorExtractor(Color.RED, Color.GREEN, Color.BLUE); + ColorExtractor colorExtractor = new ColorExtractor(Color.RED, Color.GREEN, Color.BLUE); - Model model = getModelForFile("testFiles/coloring/protein_to_color.xml", false); + Model model = getModelForFile("testFiles/coloring/protein_to_color.xml", false); - Collection<ColorSchema> schemas = reader.readColorSchema("testFiles/coloring/problematicSchema.txt"); - ColorModelCommand factory = new ColorModelCommand(model, schemas, colorExtractor); - factory.execute(); + Collection<ColorSchema> schemas = reader.readColorSchema("testFiles/coloring/problematicSchema.txt"); + ColorModelCommand factory = new ColorModelCommand(model, schemas, colorExtractor); + factory.execute(); - assertFalse(model.getElementByElementId("sa1").getColor().equals(Color.WHITE)); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + assertFalse(model.getElementByElementId("sa1").getColor().equals(Color.WHITE)); } @Test public void testColoringWithValueOrColor() throws Exception { - try { - Map<String, String> params = new HashMap<>(); - params.put(TextFileUtils.COLUMN_COUNT_PARAM, "3"); - - String input = "name\tcolor\tvalue\n" + - "s1\t#ff0000\t\n" + - "s2\t\t1.0\n"; - Collection<ColorSchema> schemas = reader - .readColorSchema(new ByteArrayInputStream(input.getBytes(StandardCharsets.UTF_8)), params); - assertEquals(2, schemas.size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Map<String, String> params = new HashMap<>(); + params.put(TextFileUtils.COLUMN_COUNT_PARAM, "3"); + + String input = "name\tcolor\tvalue\n" + + "s1\t#ff0000\t\n" + + "s2\t\t1.0\n"; + Collection<ColorSchema> schemas = reader + .readColorSchema(new ByteArrayInputStream(input.getBytes(StandardCharsets.UTF_8)), params); + assertEquals(2, schemas.size()); } @Test public void testElementsByType() throws Exception { - try { - Map<String, String> params = new HashMap<>(); - params.put(TextFileUtils.COLUMN_COUNT_PARAM, "3"); - - String input = "type\tname\tvalue\n" + - "protein\t\t1.0\n"; - Collection<ColorSchema> schemas = reader - .readColorSchema(new ByteArrayInputStream(input.getBytes(StandardCharsets.UTF_8)), params); - assertEquals(1, schemas.size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Map<String, String> params = new HashMap<>(); + params.put(TextFileUtils.COLUMN_COUNT_PARAM, "3"); + + String input = "type\tname\tvalue\n" + + "protein\t\t1.0\n"; + Collection<ColorSchema> schemas = reader + .readColorSchema(new ByteArrayInputStream(input.getBytes(StandardCharsets.UTF_8)), params); + assertEquals(1, schemas.size()); } - @Test + @Test(expected = InvalidColorSchemaException.class) public void testColoringWithInvalidValueAndColor() throws Exception { - try { - Map<String, String> params = new HashMap<>(); - params.put(TextFileUtils.COLUMN_COUNT_PARAM, "3"); - - String input = "name\tcolor\tvalue\ns1\t#ff0000\t1.0"; - reader.readColorSchema(new ByteArrayInputStream(input.getBytes(StandardCharsets.UTF_8)), params); - fail("Exception expected"); - } catch (InvalidColorSchemaException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Map<String, String> params = new HashMap<>(); + params.put(TextFileUtils.COLUMN_COUNT_PARAM, "3"); + + String input = "name\tcolor\tvalue\ns1\t#ff0000\t1.0"; + reader.readColorSchema(new ByteArrayInputStream(input.getBytes(StandardCharsets.UTF_8)), params); } - @Test + @Test(expected = InvalidColorSchemaException.class) public void testColoringWithEmptyColor() throws Exception { - try { - Map<String, String> params = new HashMap<>(); - params.put(TextFileUtils.COLUMN_COUNT_PARAM, "3"); - - String input = "name\tcolor\ns1\tx"; - reader.readColorSchema(new ByteArrayInputStream(input.getBytes(StandardCharsets.UTF_8)), params); - fail("Exception expected"); - } catch (InvalidColorSchemaException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Map<String, String> params = new HashMap<>(); + params.put(TextFileUtils.COLUMN_COUNT_PARAM, "3"); + + String input = "name\tcolor\ns1\tx"; + reader.readColorSchema(new ByteArrayInputStream(input.getBytes(StandardCharsets.UTF_8)), params); } @Test public void testColoringWithInvalidValueAndColor2() throws Exception { - try { - Map<String, String> params = new HashMap<>(); - params.put(TextFileUtils.COLUMN_COUNT_PARAM, "3"); - - String input = "name\tcolor\tvalue\ns1\t\t"; - reader.readColorSchema(new ByteArrayInputStream(input.getBytes(StandardCharsets.UTF_8)), params); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + Map<String, String> params = new HashMap<>(); + params.put(TextFileUtils.COLUMN_COUNT_PARAM, "3"); + + String input = "name\tcolor\tvalue\ns1\t\t"; + reader.readColorSchema(new ByteArrayInputStream(input.getBytes(StandardCharsets.UTF_8)), params); } @Test public void testSchemasWithId() throws Exception { - try { - Collection<ColorSchema> schemas = reader.readColorSchema("testFiles/coloring/schemaWithIdentifiers.txt"); - for (ColorSchema colorSchema : schemas) { - for (MiriamData md : colorSchema.getMiriamData()) { - assertNotNull(md.getResource()); - assertFalse(md.getResource().isEmpty()); - } + Collection<ColorSchema> schemas = reader.readColorSchema("testFiles/coloring/schemaWithIdentifiers.txt"); + for (ColorSchema colorSchema : schemas) { + for (MiriamData md : colorSchema.getMiriamData()) { + assertNotNull(md.getResource()); + assertFalse(md.getResource().isEmpty()); } - - } catch (Exception e) { - e.printStackTrace(); - throw e; } } @Test public void testSchemasWithIdSnakeCase() throws Exception { - try { - Collection<ColorSchema> schemas = reader - .readColorSchema("testFiles/coloring/schema_with_identifiers_in_snake_case.txt"); - for (ColorSchema colorSchema : schemas) { - for (MiriamData md : colorSchema.getMiriamData()) { - assertNotNull(md.getResource()); - assertFalse(md.getResource().isEmpty()); - } + Collection<ColorSchema> schemas = reader + .readColorSchema("testFiles/coloring/schema_with_identifiers_in_snake_case.txt"); + for (ColorSchema colorSchema : schemas) { + for (MiriamData md : colorSchema.getMiriamData()) { + assertNotNull(md.getResource()); + assertFalse(md.getResource().isEmpty()); } - - } catch (Exception e) { - e.printStackTrace(); - throw e; } } @Test public void testSchemasWithEmptyNameAndId() throws Exception { - try { - Collection<ColorSchema> schemas = reader.readColorSchema("testFiles/coloring/schemaIdWithoutName.txt"); - for (ColorSchema colorSchema : schemas) { - for (MiriamData md : colorSchema.getMiriamData()) { - assertFalse(md.getResource().isEmpty()); - assertNull(colorSchema.getName()); - } + Collection<ColorSchema> schemas = reader.readColorSchema("testFiles/coloring/schemaIdWithoutName.txt"); + for (ColorSchema colorSchema : schemas) { + for (MiriamData md : colorSchema.getMiriamData()) { + assertFalse(md.getResource().isEmpty()); + assertNull(colorSchema.getName()); } - - } catch (Exception e) { - e.printStackTrace(); - throw e; } } @Test public void testSimpleNameSchemas() throws Exception { - try { - String input = "#header\ns1\ns2\n"; - Collection<ColorSchema> schemas = reader - .readSimpleNameColorSchema(new ByteArrayInputStream(input.getBytes(StandardCharsets.UTF_8))); - assertEquals(2, schemas.size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String input = "#header\ns1\ns2\n"; + Collection<ColorSchema> schemas = reader + .readSimpleNameColorSchema(new ByteArrayInputStream(input.getBytes(StandardCharsets.UTF_8))); + assertEquals(2, schemas.size()); } @Test @@ -446,39 +301,28 @@ public class ColorSchemaReaderTest extends ServiceTestFunctions { @Test public void testColoringWithModelName() throws Exception { - try { - String input = "name\tcolor\tmodel_name\n" + - "s1\t#ff0000\txxx\n" ; - Map<String, String> params = new HashMap<>(); - params.put(TextFileUtils.COLUMN_COUNT_PARAM, "3"); - - Collection<ColorSchema> schemas = reader - .readColorSchema(new ByteArrayInputStream(input.getBytes(StandardCharsets.UTF_8)), params); - assertEquals(1, schemas.size()); - assertNotNull(schemas.iterator().next().getModelName()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String input = "name\tcolor\tmodel_name\n" + + "s1\t#ff0000\txxx\n"; + Map<String, String> params = new HashMap<>(); + params.put(TextFileUtils.COLUMN_COUNT_PARAM, "3"); + + Collection<ColorSchema> schemas = reader + .readColorSchema(new ByteArrayInputStream(input.getBytes(StandardCharsets.UTF_8)), params); + assertEquals(1, schemas.size()); + assertNotNull(schemas.iterator().next().getModelName()); } @Test public void testColoringWithMapName() throws Exception { - try { - String input = "name\tcolor\tmap_name\n" + - "s1\t#ff0000\txxx\n" ; - Map<String, String> params = new HashMap<>(); - params.put(TextFileUtils.COLUMN_COUNT_PARAM, "3"); - - Collection<ColorSchema> schemas = reader - .readColorSchema(new ByteArrayInputStream(input.getBytes(StandardCharsets.UTF_8)), params); - assertEquals(1, schemas.size()); - assertNotNull(schemas.iterator().next().getModelName()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + String input = "name\tcolor\tmap_name\n" + + "s1\t#ff0000\txxx\n"; + Map<String, String> params = new HashMap<>(); + params.put(TextFileUtils.COLUMN_COUNT_PARAM, "3"); + + Collection<ColorSchema> schemas = reader + .readColorSchema(new ByteArrayInputStream(input.getBytes(StandardCharsets.UTF_8)), params); + assertEquals(1, schemas.size()); + assertNotNull(schemas.iterator().next().getModelName()); } - } diff --git a/service/src/test/java/lcsb/mapviewer/services/utils/EmailSenderTest.java b/service/src/test/java/lcsb/mapviewer/services/utils/EmailSenderTest.java index c07e2e322a4b08e70dc03059e6f7e1eef5f9efee..7cccdf27eda49140d428adcc360e424bae3397b3 100644 --- a/service/src/test/java/lcsb/mapviewer/services/utils/EmailSenderTest.java +++ b/service/src/test/java/lcsb/mapviewer/services/utils/EmailSenderTest.java @@ -3,11 +3,9 @@ package lcsb.mapviewer.services.utils; import java.util.ArrayList; import java.util.List; -import org.apache.logging.log4j.*; -import org.junit.After; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.junit.*; import lcsb.mapviewer.services.ServiceTestFunctions; @@ -25,15 +23,10 @@ public class EmailSenderTest extends ServiceTestFunctions { @Test @Ignore("This is just a showcase") public void test() throws Exception { - try { - EmailSender emailSender = new EmailSender(configurationService); - List<String> recipients = new ArrayList<>(); - recipients.add("piotr.gawron@uni.lu"); - emailSender.sendEmail(recipients, new ArrayList<>(), "Test subject", "Test content"); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + EmailSender emailSender = new EmailSender(configurationService); + List<String> recipients = new ArrayList<>(); + recipients.add("piotr.gawron@uni.lu"); + emailSender.sendEmail(recipients, new ArrayList<>(), "Test subject", "Test content"); } } diff --git a/web/src/test/java/lcsb/mapviewer/web/ControllerIntegrationTest.java b/web/src/test/java/lcsb/mapviewer/web/ControllerIntegrationTest.java index 7dbe244a8de6a81caf8615244fe52345fcde22d6..4044855a7d9a38328851c60e083d53728f35ad6c 100644 --- a/web/src/test/java/lcsb/mapviewer/web/ControllerIntegrationTest.java +++ b/web/src/test/java/lcsb/mapviewer/web/ControllerIntegrationTest.java @@ -13,8 +13,7 @@ import javax.annotation.PreDestroy; import javax.servlet.Filter; import org.apache.logging.log4j.core.LogEvent; -import org.junit.After; -import org.junit.Before; +import org.junit.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.mock.web.MockHttpSession; import org.springframework.security.crypto.password.PasswordEncoder; @@ -26,6 +25,7 @@ import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; import lcsb.mapviewer.common.MinervaLoggerAppender; +import lcsb.mapviewer.common.UnitTestFailedWatcher; import lcsb.mapviewer.model.Project; import lcsb.mapviewer.model.cache.UploadedFileEntry; import lcsb.mapviewer.model.graphics.PolylineData; @@ -47,6 +47,9 @@ import lcsb.mapviewer.web.config.SpringWebConfig; @ContextConfiguration(classes = SpringWebConfig.class) abstract public class ControllerIntegrationTest { + @Rule + public UnitTestFailedWatcher unitTestFailedWatcher = new UnitTestFailedWatcher(); + @Autowired private WebApplicationContext context; diff --git a/web/src/test/java/lcsb/mapviewer/web/ProjectControllerIntegrationTestForAsyncCalls.java b/web/src/test/java/lcsb/mapviewer/web/ProjectControllerIntegrationTestForAsyncCalls.java index c5f54c5b39586413a96d4e9f5fb15ca15c23133e..02dd41778afb5c246d4101e26a426b5f464310df 100644 --- a/web/src/test/java/lcsb/mapviewer/web/ProjectControllerIntegrationTestForAsyncCalls.java +++ b/web/src/test/java/lcsb/mapviewer/web/ProjectControllerIntegrationTestForAsyncCalls.java @@ -7,9 +7,6 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. import java.nio.file.Files; import java.nio.file.Paths; import java.util.Arrays; -import java.util.List; -import java.util.concurrent.*; -import java.util.function.Supplier; import javax.transaction.Transactional; @@ -31,7 +28,6 @@ import lcsb.mapviewer.model.cache.UploadedFileEntry; import lcsb.mapviewer.model.security.Privilege; import lcsb.mapviewer.model.security.PrivilegeType; import lcsb.mapviewer.model.user.User; -import lcsb.mapviewer.persist.DbUtils; import lcsb.mapviewer.persist.dao.ProjectDao; import lcsb.mapviewer.persist.dao.user.UserDao; import lcsb.mapviewer.services.interfaces.IUserService;