diff --git a/bitrepository-alarm-service/src/test/java/org/bitrepository/alarm/AlarmExceptionTest.java b/bitrepository-alarm-service/src/test/java/org/bitrepository/alarm/AlarmExceptionTest.java index 28655f84c..ad69c2bd4 100644 --- a/bitrepository-alarm-service/src/test/java/org/bitrepository/alarm/AlarmExceptionTest.java +++ b/bitrepository-alarm-service/src/test/java/org/bitrepository/alarm/AlarmExceptionTest.java @@ -5,16 +5,16 @@ * Copyright (C) 2010 - 2012 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% @@ -22,29 +22,31 @@ package org.bitrepository.alarm; import org.jaccept.structure.ExtendedTestCase; -import org.testng.Assert; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; public class AlarmExceptionTest extends ExtendedTestCase { - - @Test(groups = {"regressiontest"}) + + @Test + @Tag("regressiontest") public void alarmExceptionTest() throws Exception { addDescription("Tests that AlarmExceptions can be thrown."); String alarmError = "The message of the alarm exception"; try { throw new AlarmException(alarmError); } catch (AlarmException e) { - Assert.assertEquals(e.getMessage(), alarmError); - Assert.assertNull(e.getCause()); + Assertions.assertEquals(alarmError, e.getMessage()); + Assertions.assertNull(e.getCause()); } - + String otherError = "This is the message of the included exception"; try { throw new AlarmException(alarmError, new Exception(otherError)); } catch (AlarmException e) { - Assert.assertEquals(e.getMessage(), alarmError); - Assert.assertNotNull(e.getCause()); - Assert.assertEquals(e.getCause().getMessage(), otherError); + Assertions.assertEquals(alarmError, e.getMessage()); + Assertions.assertNotNull(e.getCause()); + Assertions.assertEquals(otherError, e.getCause().getMessage()); } } diff --git a/bitrepository-alarm-service/src/test/java/org/bitrepository/alarm/handler/AlarmHandlerTest.java b/bitrepository-alarm-service/src/test/java/org/bitrepository/alarm/handler/AlarmHandlerTest.java index 1728fda3a..87a5445d6 100644 --- a/bitrepository-alarm-service/src/test/java/org/bitrepository/alarm/handler/AlarmHandlerTest.java +++ b/bitrepository-alarm-service/src/test/java/org/bitrepository/alarm/handler/AlarmHandlerTest.java @@ -26,38 +26,39 @@ import org.bitrepository.bitrepositorymessages.AlarmMessage; import org.bitrepository.bitrepositorymessages.Message; import org.bitrepository.protocol.IntegrationTest; -import org.testng.Assert; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; -import static org.testng.AssertJUnit.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; public class AlarmHandlerTest extends IntegrationTest { - @Test(groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public void alarmMediatorTest() throws Exception { addDescription("Test the mediator handling of alarm messages."); addStep("Setup mediator and create alarm handler.", "Should be ok."); AlarmMediator mediator = new AlarmMediator(messageBus, alarmDestinationID); MockAlarmHandler alarmHandler = new MockAlarmHandler(); mediator.addHandler(alarmHandler); - Assert.assertEquals(alarmHandler.getCallsForClose(), 0); - Assert.assertEquals(alarmHandler.getCallsForHandleAlarm(), 0); + assertEquals(0, alarmHandler.getCallsForClose()); + assertEquals(0, alarmHandler.getCallsForHandleAlarm()); addStep("Try giving it a non-alarm message", "Should not call the alarm handler."); Message msg = new Message(); mediator.onMessage(msg, null); - assertEquals(alarmHandler.getCallsForClose(), 0); - Assert.assertEquals(alarmHandler.getCallsForHandleAlarm(), 0); + assertEquals(0, alarmHandler.getCallsForClose()); + assertEquals(0, alarmHandler.getCallsForHandleAlarm()); addStep("Giv the mediator an AlarmMessage", "Should be sent to the alarm handler"); AlarmMessage alarmMsg = new AlarmMessage(); mediator.onMessage(alarmMsg, null); - Assert.assertEquals(alarmHandler.getCallsForClose(), 0); - Assert.assertEquals(alarmHandler.getCallsForHandleAlarm(), 1); + assertEquals(0, alarmHandler.getCallsForClose()); + assertEquals(1, alarmHandler.getCallsForHandleAlarm()); addStep("Close the mediator.", "Should also close the alarm handler."); mediator.close(); - Assert.assertEquals(alarmHandler.getCallsForClose(), 1); - Assert.assertEquals(alarmHandler.getCallsForHandleAlarm(), 1); + assertEquals(1, alarmHandler.getCallsForClose()); + assertEquals(1, alarmHandler.getCallsForHandleAlarm()); } protected class MockAlarmHandler implements AlarmHandler { diff --git a/bitrepository-alarm-service/src/test/java/org/bitrepository/alarm/store/AlarmDatabaseExtractionModelTest.java b/bitrepository-alarm-service/src/test/java/org/bitrepository/alarm/store/AlarmDatabaseExtractionModelTest.java index ad746832d..151b978b1 100644 --- a/bitrepository-alarm-service/src/test/java/org/bitrepository/alarm/store/AlarmDatabaseExtractionModelTest.java +++ b/bitrepository-alarm-service/src/test/java/org/bitrepository/alarm/store/AlarmDatabaseExtractionModelTest.java @@ -5,16 +5,16 @@ * Copyright (C) 2010 - 2012 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% @@ -23,8 +23,9 @@ import org.bitrepository.bitrepositoryelements.AlarmCode; import org.jaccept.structure.ExtendedTestCase; -import org.testng.Assert; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; import java.util.Date; @@ -33,62 +34,63 @@ */ public class AlarmDatabaseExtractionModelTest extends ExtendedTestCase { - @Test(groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public void alarmExceptionTest() throws Exception { addDescription("Test the AlarmDatabaseExtractionModel class"); addStep("Define constants etc.", "Should be OK"); boolean ascending = true; - + addStep("Create an empty model", "Should be populated with nulls."); AlarmDatabaseExtractionModel model = new AlarmDatabaseExtractionModel(null, null, null, null, null, null, null, ascending); - - Assert.assertNull(model.getAlarmCode()); - Assert.assertNull(model.getComponentId()); - Assert.assertNull(model.getEndDate()); - Assert.assertNull(model.getFileID()); - Assert.assertNull(model.getStartDate()); - Assert.assertNull(model.getCollectionID()); - Assert.assertEquals(model.getAscending(), ascending); - Assert.assertEquals(model.getMaxCount().intValue(), Integer.MAX_VALUE); - + + Assertions.assertNull(model.getAlarmCode()); + Assertions.assertNull(model.getComponentId()); + Assertions.assertNull(model.getEndDate()); + Assertions.assertNull(model.getFileID()); + Assertions.assertNull(model.getStartDate()); + Assertions.assertNull(model.getCollectionID()); + Assertions.assertEquals(ascending, model.getAscending()); + Assertions.assertEquals(Integer.MAX_VALUE, model.getMaxCount().intValue()); + addStep("Test the AlarmCode", "Should be able to put a new one in and extract it again."); AlarmCode defaultAlarmCode = AlarmCode.COMPONENT_FAILURE; model.setAlarmCode(defaultAlarmCode); - Assert.assertEquals(model.getAlarmCode(), defaultAlarmCode); - + Assertions.assertEquals(defaultAlarmCode, model.getAlarmCode()); + addStep("Test the ascending", "Should be able to put a new one in and extract it again."); boolean defaultAscending = false; model.setAscending(defaultAscending); - Assert.assertEquals(model.getAscending(), defaultAscending); + Assertions.assertEquals(defaultAscending, model.getAscending()); addStep("Test the ComponentID", "Should be able to put a new one in and extract it again."); String defaultComponentID = "DefaultComponentID"; model.setComponentId(defaultComponentID); - Assert.assertEquals(model.getComponentId(), defaultComponentID); + Assertions.assertEquals(defaultComponentID, model.getComponentId()); addStep("Test the EndDate", "Should be able to put a new one in and extract it again."); Date defaultEndDate = new Date(987654321); model.setEndDate(defaultEndDate); - Assert.assertEquals(model.getEndDate(), defaultEndDate); + Assertions.assertEquals(model.getEndDate(), defaultEndDate); addStep("Test the FileID", "Should be able to put a new one in and extract it again."); String defaultFileID = "DefaultFileID"; model.setFileID(defaultFileID); - Assert.assertEquals(model.getFileID(), defaultFileID); + Assertions.assertEquals(defaultFileID, model.getFileID()); addStep("Test the MaxCount", "Should be able to put a new one in and extract it again."); Integer defaultMaxCount = 192837456; model.setMaxCount(defaultMaxCount); - Assert.assertEquals(model.getMaxCount(), defaultMaxCount); - + Assertions.assertEquals(defaultMaxCount, model.getMaxCount()); + addStep("Test the StartDate", "Should be able to put a new one in and extract it again."); Date defaultStartDate = new Date(123456789); model.setStartDate(defaultStartDate); - Assert.assertEquals(model.getStartDate(), defaultStartDate); - + Assertions.assertEquals(model.getStartDate(), defaultStartDate); + addStep("Test the CollectionID", "Should be able to put a new one in and extract it again."); String collectionID = "collection1"; model.setCollectionID(collectionID); - Assert.assertEquals(model.getCollectionID(), collectionID); + Assertions.assertEquals(collectionID, model.getCollectionID()); } } diff --git a/bitrepository-alarm-service/src/test/java/org/bitrepository/alarm/store/AlarmDatabaseTest.java b/bitrepository-alarm-service/src/test/java/org/bitrepository/alarm/store/AlarmDatabaseTest.java index bdcbc0417..09b397ead 100644 --- a/bitrepository-alarm-service/src/test/java/org/bitrepository/alarm/store/AlarmDatabaseTest.java +++ b/bitrepository-alarm-service/src/test/java/org/bitrepository/alarm/store/AlarmDatabaseTest.java @@ -5,16 +5,16 @@ * Copyright (C) 2010 - 2012 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% @@ -31,11 +31,13 @@ import org.bitrepository.service.database.DatabaseUtils; import org.bitrepository.service.database.DerbyDatabaseDestroyer; import org.jaccept.structure.ExtendedTestCase; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; import java.io.File; import java.text.ParseException; @@ -51,8 +53,11 @@ /** * Sees if alarms are correctly stored in the database. */ +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class AlarmDatabaseTest extends ExtendedTestCase { - /** The settings for the tests. Should be instantiated in the setup.*/ + /** + * The settings for the tests. Should be instantiated in the setup. + */ Settings settings; String fileID = "TEST-FILE-ID-" + new Date().getTime(); String component1 = "ACTOR-1"; @@ -64,7 +69,7 @@ public class AlarmDatabaseTest extends ExtendedTestCase { String DATABASE_URL = "jdbc:derby:" + DATABASE_DIRECTORY + "/" + DATABASE_NAME; File dbDir = null; - @BeforeClass (alwaysRun = true) + @BeforeAll public void setup() { settings = TestSettingsProvider.reloadSettings("AlarmDatabaseUnderTest"); @@ -74,8 +79,8 @@ public void setup() { AlarmDatabaseCreator integrityDatabaseCreator = new AlarmDatabaseCreator(); integrityDatabaseCreator.createAlarmDatabase(settings, null); } - - @AfterMethod (alwaysRun = true) + + @AfterEach public void cleanupDatabase() { // TODO DBConnector connector = new DBConnector(settings.getReferenceSettings().getAlarmServiceSettings().getAlarmServiceDatabase()); @@ -83,187 +88,193 @@ public void cleanupDatabase() { DatabaseUtils.executeStatement(connector, "DELETE FROM " + COMPONENT_TABLE); } - @AfterClass (alwaysRun = true) - public void shutdown() { + @AfterAll + public void shutdown() { addStep("Cleanup after test.", "Should remove directory with test material."); - if(dbDir != null) { + if (dbDir != null) { FileUtils.delete(dbDir); } } - @Test(groups = {"regressiontest", "databasetest"}) + @Test + @Tag("regressiontest") + @Tag("databasetest") public void AlarmDatabaseExtractionTest() { addDescription("Testing the connection to the alarm service database especially with regards to " + "extracting the data from it."); addStep("Setup the variables and constants.", "Should be ok."); Date restrictionDate = new Date(123456789); // Sometime between epoch and now! - + addStep("Adds the variables to the settings and instantiates the database cache", "Should be connected."); AlarmDAOFactory alarmDAOFactory = new AlarmDAOFactory(); AlarmServiceDAO database = alarmDAOFactory.getAlarmServiceDAOInstance( settings.getReferenceSettings().getAlarmServiceSettings().getAlarmServiceDatabase()); - + addStep("Populate the database with two alarms.", "Should be inserted."); - for(Alarm alarm : makeAlarms()) { + for (Alarm alarm : makeAlarms()) { database.addAlarm(alarm); } - + addStep("Try to extract all the data from the database.", "Should deliver both alarms."); List extractedAlarms = database.extractAlarms(null, null, null, null, null, null, null, false); - Assert.assertEquals(extractedAlarms.size(), 2); - + Assertions.assertEquals(2, extractedAlarms.size()); + addStep("Try to extract the alarms for component 1.", "Should deliver one alarm."); extractedAlarms = database.extractAlarms(component1, null, null, null, null, null, null, false); - Assert.assertEquals(extractedAlarms.size(), 1); - Assert.assertEquals(extractedAlarms.get(0).getAlarmRaiser(), component1); - Assert.assertEquals(extractedAlarms.get(0).getAlarmCode(), AlarmCode.COMPONENT_FAILURE); - Assert.assertNull(extractedAlarms.get(0).getFileID()); - + Assertions.assertEquals(1, extractedAlarms.size()); + Assertions.assertEquals(extractedAlarms.get(0).getAlarmRaiser(), component1); + Assertions.assertEquals(AlarmCode.COMPONENT_FAILURE, extractedAlarms.get(0).getAlarmCode()); + Assertions.assertNull(extractedAlarms.get(0).getFileID()); + addStep("Try to extract the alarms for component 2.", "Should deliver one alarm."); extractedAlarms = database.extractAlarms(component2, null, null, null, null, null, null, false); - Assert.assertEquals(extractedAlarms.size(), 1); - Assert.assertEquals(extractedAlarms.get(0).getAlarmRaiser(), component2); - Assert.assertEquals(extractedAlarms.get(0).getAlarmCode(), AlarmCode.CHECKSUM_ALARM); - Assert.assertEquals(extractedAlarms.get(0).getFileID(), fileID); - + Assertions.assertEquals(1, extractedAlarms.size()); + Assertions.assertEquals(extractedAlarms.get(0).getAlarmRaiser(), component2); + Assertions.assertEquals(AlarmCode.CHECKSUM_ALARM, extractedAlarms.get(0).getAlarmCode()); + Assertions.assertEquals(extractedAlarms.get(0).getFileID(), fileID); + addStep("Try to extract the alarms for the alarm code 'COMPONENT_FAILURE'.", "Should deliver one alarm."); extractedAlarms = database.extractAlarms(null, AlarmCode.COMPONENT_FAILURE, null, null, null, null, null, false); - Assert.assertEquals(extractedAlarms.size(), 1); - Assert.assertEquals(extractedAlarms.get(0).getAlarmRaiser(), component1); - Assert.assertEquals(extractedAlarms.get(0).getAlarmCode(), AlarmCode.COMPONENT_FAILURE); - Assert.assertNull(extractedAlarms.get(0).getFileID()); - + Assertions.assertEquals(1, extractedAlarms.size()); + Assertions.assertEquals(extractedAlarms.get(0).getAlarmRaiser(), component1); + Assertions.assertEquals(AlarmCode.COMPONENT_FAILURE, extractedAlarms.get(0).getAlarmCode()); + Assertions.assertNull(extractedAlarms.get(0).getFileID()); + addStep("Try to extract the alarms for the alarm code 'CHECKSUM_ALARM'.", "Should deliver one alarm."); extractedAlarms = database.extractAlarms(null, AlarmCode.CHECKSUM_ALARM, null, null, null, null, null, false); - Assert.assertEquals(extractedAlarms.size(), 1); - Assert.assertEquals(extractedAlarms.get(0).getAlarmRaiser(), component2); - Assert.assertEquals(extractedAlarms.get(0).getAlarmCode(), AlarmCode.CHECKSUM_ALARM); - Assert.assertEquals(extractedAlarms.get(0).getFileID(), fileID); - + Assertions.assertEquals(1, extractedAlarms.size()); + Assertions.assertEquals(extractedAlarms.get(0).getAlarmRaiser(), component2); + Assertions.assertEquals(AlarmCode.CHECKSUM_ALARM, extractedAlarms.get(0).getAlarmCode()); + Assertions.assertEquals(extractedAlarms.get(0).getFileID(), fileID); + addStep("Try to extract the new alarm.", "Should deliver one alarm."); extractedAlarms = database.extractAlarms(null, null, restrictionDate, null, null, null, null, false); - Assert.assertEquals(extractedAlarms.size(), 1); - Assert.assertEquals(extractedAlarms.get(0).getAlarmRaiser(), component2); - Assert.assertEquals(extractedAlarms.get(0).getAlarmCode(), AlarmCode.CHECKSUM_ALARM); - Assert.assertEquals(extractedAlarms.get(0).getFileID(), fileID); - + Assertions.assertEquals(1, extractedAlarms.size()); + Assertions.assertEquals(extractedAlarms.get(0).getAlarmRaiser(), component2); + Assertions.assertEquals(AlarmCode.CHECKSUM_ALARM, extractedAlarms.get(0).getAlarmCode()); + Assertions.assertEquals(extractedAlarms.get(0).getFileID(), fileID); + addStep("Try to extract the old alarm.", "Should deliver one alarm."); extractedAlarms = database.extractAlarms(null, null, null, restrictionDate, null, null, null, false); - Assert.assertEquals(extractedAlarms.size(), 1); - Assert.assertEquals(extractedAlarms.get(0).getAlarmRaiser(), component1); - Assert.assertEquals(extractedAlarms.get(0).getAlarmCode(), AlarmCode.COMPONENT_FAILURE); - Assert.assertNull(extractedAlarms.get(0).getFileID()); + Assertions.assertEquals(1, extractedAlarms.size()); + Assertions.assertEquals(extractedAlarms.get(0).getAlarmRaiser(), component1); + Assertions.assertEquals(AlarmCode.COMPONENT_FAILURE, extractedAlarms.get(0).getAlarmCode()); + Assertions.assertNull(extractedAlarms.get(0).getFileID()); addStep("Try to extract the alarms for the file id.", "Should deliver one alarm."); extractedAlarms = database.extractAlarms(null, null, null, null, fileID, null, null, false); - Assert.assertEquals(extractedAlarms.size(), 1); - Assert.assertEquals(extractedAlarms.get(0).getAlarmRaiser(), component2); - Assert.assertEquals(extractedAlarms.get(0).getAlarmCode(), AlarmCode.CHECKSUM_ALARM); - Assert.assertEquals(extractedAlarms.get(0).getFileID(), fileID); - + Assertions.assertEquals(1, extractedAlarms.size()); + Assertions.assertEquals(extractedAlarms.get(0).getAlarmRaiser(), component2); + Assertions.assertEquals(AlarmCode.CHECKSUM_ALARM, extractedAlarms.get(0).getAlarmCode()); + Assertions.assertEquals(extractedAlarms.get(0).getFileID(), fileID); + addStep("Try to extract the alarms for the collection id.", "Should deliver one alarm."); extractedAlarms = database.extractAlarms(null, null, null, null, null, collection1, null, false); - Assert.assertEquals(extractedAlarms.size(), 1); - Assert.assertEquals(extractedAlarms.get(0).getAlarmRaiser(), component1); - Assert.assertEquals(extractedAlarms.get(0).getCollectionID(), collection1); - Assert.assertEquals(extractedAlarms.get(0).getAlarmCode(), AlarmCode.COMPONENT_FAILURE); - + Assertions.assertEquals(1, extractedAlarms.size()); + Assertions.assertEquals(extractedAlarms.get(0).getAlarmRaiser(), component1); + Assertions.assertEquals(extractedAlarms.get(0).getCollectionID(), collection1); + Assertions.assertEquals(AlarmCode.COMPONENT_FAILURE, extractedAlarms.get(0).getAlarmCode()); + addStep("Try to extract the oldest alarm from the database.", "Should deliver one alarm."); extractedAlarms = database.extractAlarms(null, null, null, null, null, null, 1, true); - Assert.assertEquals(extractedAlarms.size(), 1); - Assert.assertEquals(extractedAlarms.get(0).getAlarmRaiser(), component1); - Assert.assertEquals(extractedAlarms.get(0).getAlarmCode(), AlarmCode.COMPONENT_FAILURE); - Assert.assertNull(extractedAlarms.get(0).getFileID()); - + Assertions.assertEquals(1, extractedAlarms.size()); + Assertions.assertEquals(extractedAlarms.get(0).getAlarmRaiser(), component1); + Assertions.assertEquals(AlarmCode.COMPONENT_FAILURE, extractedAlarms.get(0).getAlarmCode()); + Assertions.assertNull(extractedAlarms.get(0).getFileID()); + addStep("Try to extract the newest alarm from the database.", "Should deliver one alarm."); extractedAlarms = database.extractAlarms(null, null, null, null, null, null, 1, false); - Assert.assertEquals(extractedAlarms.size(), 1); - Assert.assertEquals(extractedAlarms.get(0).getAlarmRaiser(), component2); - Assert.assertEquals(extractedAlarms.get(0).getAlarmCode(), AlarmCode.CHECKSUM_ALARM); - Assert.assertEquals(extractedAlarms.get(0).getFileID(), fileID); + Assertions.assertEquals(1, extractedAlarms.size()); + Assertions.assertEquals(extractedAlarms.get(0).getAlarmRaiser(), component2); + Assertions.assertEquals(AlarmCode.CHECKSUM_ALARM, extractedAlarms.get(0).getAlarmCode()); + Assertions.assertEquals(extractedAlarms.get(0).getFileID(), fileID); } - @Test(groups = {"regressiontest", "databasetest"}) + @Test + @Tag("regressiontest") + @Tag("databasetest") public void AlarmDatabaseLargeIngestionTest() { addDescription("Testing the ingestion of a large texts into the database"); addStep("Setup and create alarm", ""); AlarmDAOFactory alarmDAOFactory = new AlarmDAOFactory(); AlarmServiceDAO database = alarmDAOFactory.getAlarmServiceDAOInstance( settings.getReferenceSettings().getAlarmServiceSettings().getAlarmServiceDatabase()); - + Alarm alarm = new Alarm(); alarm.setAlarmCode(AlarmCode.CHECKSUM_ALARM); alarm.setAlarmRaiser("TEST"); alarm.setFileID(fileID); alarm.setOrigDateTime(CalendarUtils.getEpoch()); - + StringBuilder text = new StringBuilder(); - for(int i = 0; i < 10; i++) { + for (int i = 0; i < 10; i++) { text.append(settings.getRepositorySettings().toString()); text.append("\n"); text.append(settings.getReferenceSettings().toString()); text.append("\n"); } alarm.setAlarmText(text.toString()); - + addStep("Insert the data into the database", "Should be extractable again."); database.addAlarm(alarm); - + List extractedAlarms = database.extractAlarms(null, null, null, null, null, null, null, true); - Assert.assertEquals(extractedAlarms.size(), 1); - Assert.assertEquals(extractedAlarms.get(0), alarm); + Assertions.assertEquals(1, extractedAlarms.size()); + Assertions.assertEquals(extractedAlarms.get(0), alarm); } - - @Test(groups = {"regressiontest", "databasetest"}) + + @Test + @Tag("regressiontest") + @Tag("databasetest") public void alarmDatabaseCorrectTimestampTest() throws ParseException { addDescription("Testing the correct ingest and extraction of alarm dates"); AlarmDAOFactory alarmDAOFactory = new AlarmDAOFactory(); AlarmServiceDAO database = alarmDAOFactory.getAlarmServiceDAOInstance( settings.getReferenceSettings().getAlarmServiceSettings().getAlarmServiceDatabase()); - + addStep("Prepare, check and ingest alarms", ""); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX", Locale.ROOT); Date summertimeTS = sdf.parse("2015-10-25T02:59:54.000+02:00"); Date summertimeUnix = new Date(1445734794000L); - Assert.assertEquals(summertimeTS, summertimeUnix); - + Assertions.assertEquals(summertimeTS, summertimeUnix); + Date wintertimeTS = sdf.parse("2015-10-25T02:59:54.000+01:00"); Date wintertimeUnix = new Date(1445738394000L); - Assert.assertEquals(wintertimeTS, wintertimeUnix); - + Assertions.assertEquals(wintertimeTS, wintertimeUnix); + Alarm summertimeAlarm = new Alarm(); summertimeAlarm.setAlarmCode(AlarmCode.CHECKSUM_ALARM); summertimeAlarm.setAlarmRaiser("TEST"); summertimeAlarm.setFileID("summertime"); summertimeAlarm.setAlarmText("Date summertime test alarm"); summertimeAlarm.setOrigDateTime(CalendarUtils.getXmlGregorianCalendar(summertimeTS)); - + Alarm wintertimeAlarm = new Alarm(); wintertimeAlarm.setAlarmCode(AlarmCode.CHECKSUM_ALARM); wintertimeAlarm.setAlarmRaiser("TEST"); wintertimeAlarm.setFileID("wintertime"); wintertimeAlarm.setAlarmText("Date wintertime test alarm"); wintertimeAlarm.setOrigDateTime(CalendarUtils.getXmlGregorianCalendar(wintertimeTS)); - + database.addAlarm(summertimeAlarm); database.addAlarm(wintertimeAlarm); - + addStep("Extract and check alarms", ""); List summertimeAlarms = database.extractAlarms(null, null, null, null, "summertime", null, null, true); - Assert.assertEquals(summertimeAlarms.size(), 1); - Assert.assertEquals( + Assertions.assertEquals(1, summertimeAlarms.size()); + Assertions.assertEquals( CalendarUtils.convertFromXMLGregorianCalendar(summertimeAlarms.get(0).getOrigDateTime()), summertimeUnix); - + List wintertimeAlarms = database.extractAlarms(null, null, null, null, "wintertime", null, null, true); - Assert.assertEquals(wintertimeAlarms.size(), 1); - Assert.assertEquals( + Assertions.assertEquals(1, wintertimeAlarms.size()); + Assertions.assertEquals( CalendarUtils.convertFromXMLGregorianCalendar(wintertimeAlarms.get(0).getOrigDateTime()), wintertimeUnix); - + } private List makeAlarms() { List res = new ArrayList<>(); - + Alarm alarm1 = new Alarm(); alarm1.setAlarmCode(AlarmCode.COMPONENT_FAILURE); alarm1.setAlarmRaiser(component1); diff --git a/bitrepository-audit-trail-service/src/main/java/org/bitrepository/audittrails/store/AuditTrailServiceDatabaseMigrator.java b/bitrepository-audit-trail-service/src/main/java/org/bitrepository/audittrails/store/AuditTrailServiceDatabaseMigrator.java index 5872024c9..783bd7ba2 100644 --- a/bitrepository-audit-trail-service/src/main/java/org/bitrepository/audittrails/store/AuditTrailServiceDatabaseMigrator.java +++ b/bitrepository-audit-trail-service/src/main/java/org/bitrepository/audittrails/store/AuditTrailServiceDatabaseMigrator.java @@ -127,10 +127,6 @@ public boolean needsMigration() { + "' table as required."); } - if (versions.get(DATABASE_VERSION_ENTRY) < currentVersion) { - return true; - } else { - return false; - } + return versions.get(DATABASE_VERSION_ENTRY) < currentVersion; } } diff --git a/bitrepository-audit-trail-service/src/test/java/org/bitrepository/audittrails/AuditTrailServiceTest.java b/bitrepository-audit-trail-service/src/test/java/org/bitrepository/audittrails/AuditTrailServiceTest.java index f4798bbf7..4c1c04086 100644 --- a/bitrepository-audit-trail-service/src/test/java/org/bitrepository/audittrails/AuditTrailServiceTest.java +++ b/bitrepository-audit-trail-service/src/test/java/org/bitrepository/audittrails/AuditTrailServiceTest.java @@ -38,9 +38,11 @@ import org.bitrepository.service.contributor.ContributorMediator; import org.bitrepository.settings.repositorysettings.Collection; import org.jaccept.structure.ExtendedTestCase; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; import org.mockito.ArgumentCaptor; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; import javax.xml.datatype.DatatypeFactory; import java.util.concurrent.ThreadFactory; @@ -53,6 +55,7 @@ import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class AuditTrailServiceTest extends ExtendedTestCase { /** The settings for the tests. Should be instantiated in the setup. */ Settings settings; @@ -61,8 +64,7 @@ public class AuditTrailServiceTest extends ExtendedTestCase { public static final String DEFAULT_CONTRIBUTOR = "Contributor1"; private ThreadFactory threadFactory; - - @BeforeClass(alwaysRun = true) + @BeforeAll public void setup() { settings = TestSettingsProvider.reloadSettings("AuditTrailServiceUnderTest"); Collection c = settings.getRepositorySettings().getCollections().getCollection().get(0); @@ -72,7 +74,8 @@ public void setup() { threadFactory = new DefaultThreadFactory(this.getClass().getSimpleName(), Thread.NORM_PRIORITY); } - @Test(groups = {"unstable"}) + @Test + @Tag("unstable") public void auditTrailServiceTest() throws Exception { addDescription("Test the Audit Trail Service"); DatatypeFactory factory = DatatypeFactory.newInstance(); @@ -124,7 +127,6 @@ public void auditTrailServiceTest() throws Exception { service.shutdown(); } - public static class CollectionRunner implements Runnable { private final AuditTrailService service; boolean finished = false; diff --git a/bitrepository-audit-trail-service/src/test/java/org/bitrepository/audittrails/collector/AuditCollectorTest.java b/bitrepository-audit-trail-service/src/test/java/org/bitrepository/audittrails/collector/AuditCollectorTest.java index 9032fd6b7..3a91b744e 100644 --- a/bitrepository-audit-trail-service/src/test/java/org/bitrepository/audittrails/collector/AuditCollectorTest.java +++ b/bitrepository-audit-trail-service/src/test/java/org/bitrepository/audittrails/collector/AuditCollectorTest.java @@ -34,10 +34,12 @@ import org.bitrepository.service.AlarmDispatcher; import org.bitrepository.settings.repositorysettings.Collection; import org.jaccept.structure.ExtendedTestCase; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; import org.mockito.ArgumentCaptor; -import org.testng.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; import javax.xml.datatype.DatatypeFactory; @@ -48,6 +50,7 @@ import static org.mockito.Mockito.timeout; import static org.mockito.Mockito.verify; +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class AuditCollectorTest extends ExtendedTestCase { /** The settings for the tests. Should be instantiated in the setup.*/ Settings settings; @@ -55,7 +58,7 @@ public class AuditCollectorTest extends ExtendedTestCase { public static final String TEST_COLLECTION = "dummy-collection"; public static final String DEFAULT_CONTRIBUTOR = "Contributor1"; - @BeforeClass (alwaysRun = true) + @BeforeAll public void setup() throws Exception { settings = TestSettingsProvider.reloadSettings("AuditCollectorUnderTest"); Collection c = settings.getRepositorySettings().getCollections().getCollection().get(0); @@ -64,7 +67,8 @@ public void setup() throws Exception { settings.getRepositorySettings().getCollections().getCollection().add(c); } - @Test(groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public void auditCollectorIntervalTest() throws Exception { addDescription("Test that the collector calls the AuditClient at the correct intervals."); DatatypeFactory factory = DatatypeFactory.newInstance(); @@ -85,7 +89,7 @@ public void auditCollectorIntervalTest() throws Exception { isNull(), isNull(), eventHandlerCaptor.capture(), any(String.class)); EventHandler eventHandler = eventHandlerCaptor.getValue(); - Assert.assertNotNull(eventHandler, "Should have an event handler"); + Assertions.assertNotNull(eventHandler, "Should have an event handler"); eventHandler.handleEvent(new AuditTrailResult(DEFAULT_CONTRIBUTOR, TEST_COLLECTION, new ResultingAuditTrails(), false)); eventHandler.handleEvent(new CompleteEvent(TEST_COLLECTION, null)); diff --git a/bitrepository-audit-trail-service/src/test/java/org/bitrepository/audittrails/collector/IncrementalCollectorTest.java b/bitrepository-audit-trail-service/src/test/java/org/bitrepository/audittrails/collector/IncrementalCollectorTest.java index 93a755ba8..0959f035b 100644 --- a/bitrepository-audit-trail-service/src/test/java/org/bitrepository/audittrails/collector/IncrementalCollectorTest.java +++ b/bitrepository-audit-trail-service/src/test/java/org/bitrepository/audittrails/collector/IncrementalCollectorTest.java @@ -39,10 +39,12 @@ import org.bitrepository.common.utils.CalendarUtils; import org.bitrepository.service.AlarmDispatcher; import org.jaccept.structure.ExtendedTestCase; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; import org.mockito.ArgumentCaptor; -import org.testng.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; import javax.xml.datatype.XMLGregorianCalendar; import java.math.BigInteger; @@ -60,6 +62,7 @@ import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class IncrementalCollectorTest extends ExtendedTestCase{ public static final String TEST_COLLECTION = "dummy-collection"; @@ -67,12 +70,13 @@ public class IncrementalCollectorTest extends ExtendedTestCase{ public static final String TEST_CONTRIBUTOR2 = "Contributor2"; private DefaultThreadFactory threadFactory; - @BeforeClass(alwaysRun = true) + @BeforeAll public void setup() throws Exception { threadFactory = new DefaultThreadFactory(this.getClass().getSimpleName(), Thread.NORM_PRIORITY, false); } - @Test(groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public void singleIncrementTest() throws InterruptedException { addDescription("Verifies the behaviour in the simplest case with just one result set "); AuditTrailClient client = mock(AuditTrailClient.class); @@ -116,14 +120,15 @@ public void singleIncrementTest() throws InterruptedException { verify(store, timeout(3000).times(1)) .addAuditTrails(any(AuditTrailEvents.class), eq(TEST_COLLECTION), eq(TEST_CONTRIBUTOR2)); - Assert.assertTrue(collectionRunner.finished, "The collector should have finished after the complete event, as " + + Assertions.assertTrue(collectionRunner.finished, "The collector should have finished after the complete event, as " + "no partialResults where received"); verifyNoMoreInteractions(store); verifyNoMoreInteractions(client); verifyNoInteractions(alarmDispatcher); } - @Test(groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public void multipleIncrementTest() throws Exception { addDescription("Verifies the behaviour in the case where the adit trails needs to be reteived in multiple " + "requests because of MaxNumberOfResults limits."); @@ -166,7 +171,7 @@ public void multipleIncrementTest() throws Exception { verify(store, timeout(3000).times(1)) .addAuditTrails(any(AuditTrailEvents.class), eq(TEST_COLLECTION), eq(TEST_CONTRIBUTOR2)); - Assert.assertFalse(collectionRunner.finished, "The collector should not have finished after the complete " + + Assertions.assertFalse(collectionRunner.finished, "The collector should not have finished after the complete " + "event, as partialResults where received"); addStep("Send another audit trail result from the contributors, now with PartialResults set to false", @@ -190,7 +195,7 @@ public void multipleIncrementTest() throws Exception { .addAuditTrails(any(AuditTrailEvents.class), eq(TEST_COLLECTION), eq(TEST_CONTRIBUTOR2)); Thread.sleep(100); - Assert.assertTrue(collectionRunner.finished, "The collector should have finished after the complete event, as " + + Assertions.assertTrue(collectionRunner.finished, "The collector should have finished after the complete event, as " + "no partialResults where received in the second increment."); verifyNoMoreInteractions(store); @@ -198,7 +203,8 @@ public void multipleIncrementTest() throws Exception { verifyNoInteractions(alarmDispatcher); } - @Test(groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public void contributorFailureTest() throws Exception { addDescription("Tests that the collector is able to collect from the remaining contributors if a " + "contributor fails."); @@ -242,7 +248,7 @@ public void contributorFailureTest() throws Exception { .addAuditTrails(any(AuditTrailEvents.class), eq(TEST_COLLECTION), eq(TEST_CONTRIBUTOR2)); eventHandler.handleEvent(new OperationFailedEvent(TEST_COLLECTION, "", null)); - Assert.assertFalse(collectionRunner.finished, "The collector should not have finished after the complete " + + Assertions.assertFalse(collectionRunner.finished, "The collector should not have finished after the complete " + "event, as partialResults where received"); addStep("Send another audit trail result from contributor 2 with PartialResults set to false", @@ -263,12 +269,13 @@ public void contributorFailureTest() throws Exception { verify(alarmDispatcher, timeout(3000)).error(any(Alarm.class)); Thread.sleep(100); - Assert.assertTrue(collectionRunner.finished); + Assertions.assertTrue(collectionRunner.finished); verifyNoMoreInteractions(store); verifyNoMoreInteractions(client); } - @Test(groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public void collectionIDFailureTest() throws Exception { addDescription("Tests what happens when a wrong collection id is received."); String FALSE_COLLECTION = "FalseCollection" + new Date().getTime(); diff --git a/bitrepository-audit-trail-service/src/test/java/org/bitrepository/audittrails/preserver/AuditPackerTest.java b/bitrepository-audit-trail-service/src/test/java/org/bitrepository/audittrails/preserver/AuditPackerTest.java index f2ec094e3..9e6208a0c 100644 --- a/bitrepository-audit-trail-service/src/test/java/org/bitrepository/audittrails/preserver/AuditPackerTest.java +++ b/bitrepository-audit-trail-service/src/test/java/org/bitrepository/audittrails/preserver/AuditPackerTest.java @@ -6,26 +6,29 @@ import org.bitrepository.common.utils.SettingsUtils; import org.bitrepository.settings.referencesettings.AuditTrailPreservation; import org.jaccept.structure.ExtendedTestCase; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; import java.io.IOException; import java.util.List; import java.util.Map; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; -import static org.testng.Assert.assertEquals; +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class AuditPackerTest extends ExtendedTestCase { private String collectionID; private AuditTrailPreservation preservationSettings; private AuditTrailStore store; - @BeforeClass(alwaysRun = true) + @BeforeAll public void setup() { Settings settings = TestSettingsProvider.reloadSettings("LocalAuditPreservationUnderTest"); preservationSettings = settings.getReferenceSettings().getAuditTrailServiceSettings().getAuditTrailPreservation(); @@ -38,8 +41,8 @@ public void setup() { public void testCreateNewPackage() throws IOException { AuditPacker packer = new AuditPacker(store, preservationSettings, collectionID); Map seqNumsReached = packer.getSequenceNumbersReached(); - assertEquals(seqNumsReached.entrySet().size(), 3); - assertEquals(packer.getPackedAuditCount(), 0); + assertEquals(3, seqNumsReached.size()); + assertEquals(0, packer.getPackedAuditCount()); // Create a stubbed event iterator for each expected contributor containing only one event. List iterators = List.of( @@ -52,12 +55,12 @@ public void testCreateNewPackage() throws IOException { // Do the actual call to createNewPackage - this will fetch first event from the iterators. packer.createNewPackage(); Long[] expectedSeqNums = {1L, 1L, 1L}; - assertEquals(packer.getPackedAuditCount(), 3); - assertEquals(packer.getSequenceNumbersReached().values().toArray(new Long[0]), expectedSeqNums); + assertEquals(3, packer.getPackedAuditCount()); + assertArrayEquals(expectedSeqNums, packer.getSequenceNumbersReached().values().toArray(new Long[0])); // As the iterators have no new audits there should be no newly packed audits on a new call. packer.createNewPackage(); - assertEquals(packer.getPackedAuditCount(), 0); - assertEquals(packer.getSequenceNumbersReached().values().toArray(new Long[0]), expectedSeqNums); + assertEquals(0, packer.getPackedAuditCount()); + assertArrayEquals(expectedSeqNums, packer.getSequenceNumbersReached().values().toArray(new Long[0])); } } diff --git a/bitrepository-audit-trail-service/src/test/java/org/bitrepository/audittrails/preserver/AuditPreservationEventHandlerTest.java b/bitrepository-audit-trail-service/src/test/java/org/bitrepository/audittrails/preserver/AuditPreservationEventHandlerTest.java index 611e83e11..7903455ff 100644 --- a/bitrepository-audit-trail-service/src/test/java/org/bitrepository/audittrails/preserver/AuditPreservationEventHandlerTest.java +++ b/bitrepository-audit-trail-service/src/test/java/org/bitrepository/audittrails/preserver/AuditPreservationEventHandlerTest.java @@ -24,7 +24,8 @@ import org.bitrepository.audittrails.store.AuditTrailStore; import org.bitrepository.client.eventhandler.CompleteEvent; import org.jaccept.structure.ExtendedTestCase; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; import java.util.HashMap; import java.util.Map; @@ -40,7 +41,8 @@ public class AuditPreservationEventHandlerTest extends ExtendedTestCase { String PILLARID = "pillarID"; public static final String TEST_COLLECTION = "dummy-collection"; - @Test(groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public void auditPreservationEventHandlerTest() throws Exception { addDescription("Test the handling of the audit trail event handler."); addStep("Setup", ""); diff --git a/bitrepository-audit-trail-service/src/test/java/org/bitrepository/audittrails/preserver/LocalAuditPreservationTest.java b/bitrepository-audit-trail-service/src/test/java/org/bitrepository/audittrails/preserver/LocalAuditPreservationTest.java index a0e726b7a..12a5a460a 100644 --- a/bitrepository-audit-trail-service/src/test/java/org/bitrepository/audittrails/preserver/LocalAuditPreservationTest.java +++ b/bitrepository-audit-trail-service/src/test/java/org/bitrepository/audittrails/preserver/LocalAuditPreservationTest.java @@ -36,10 +36,13 @@ import org.bitrepository.protocol.FileExchange; import org.bitrepository.settings.repositorysettings.Collection; import org.jaccept.structure.ExtendedTestCase; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; import javax.xml.datatype.DatatypeFactory; import javax.xml.datatype.Duration; @@ -47,6 +50,7 @@ import java.net.URL; import java.sql.Date; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.doAnswer; @@ -55,10 +59,12 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; -import static org.testng.Assert.assertEquals; +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class LocalAuditPreservationTest extends ExtendedTestCase { - /** The settings for the tests. Should be instantiated in the setup. */ + /** + * The settings for the tests. Should be instantiated in the setup. + */ Settings settings; String PILLAR_ID = "pillarID"; @@ -66,8 +72,7 @@ public class LocalAuditPreservationTest extends ExtendedTestCase { private URL testUploadUrl; private DefaultThreadFactory threadFactory; - - @BeforeClass(alwaysRun = true) + @BeforeAll public void setup() throws Exception { settings = TestSettingsProvider.reloadSettings("LocalAuditPreservationUnderTest"); @@ -82,7 +87,8 @@ public void setup() throws Exception { } - @Test(enabled = false) + @Test + @Disabled // Fragile test, fails occasionally. @SuppressWarnings("rawtypes") public void auditPreservationSchedulingTest() throws Exception { @@ -105,12 +111,12 @@ public void auditPreservationSchedulingTest() throws Exception { LocalAuditTrailPreserver preserver = new LocalAuditTrailPreserver(settings, store, client, fileExchangeMock); - /*Assert.assertEquals(store.getCallsToAddAuditTrails(), 0); - Assert.assertEquals(store.getCallsToGetAuditTrails(), 0); - Assert.assertEquals(store.getCallsToGetPreservationSequenceNumber(), 1); - Assert.assertEquals(store.getCallsToLargestSequenceNumber(), 0); - Assert.assertEquals(store.getCallsToSetPreservationSequenceNumber(), 0); - Assert.assertEquals(client.getCallsToPutFile(), 0);*/ + /*Assertions.assertEquals(store.getCallsToAddAuditTrails(), 0); + Assertions.assertEquals(store.getCallsToGetAuditTrails(), 0); + Assertions.assertEquals(store.getCallsToGetPreservationSequenceNumber(), 1); + Assertions.assertEquals(store.getCallsToLargestSequenceNumber(), 0); + Assertions.assertEquals(store.getCallsToSetPreservationSequenceNumber(), 0); + Assertions.assertEquals(client.getCallsToPutFile(), 0);*/ verify(store).getPreservationSequenceNumber(PILLAR_ID, collectionID); verifyNoMoreInteractions(store); @@ -138,13 +144,14 @@ public AuditEventIterator answer(InvocationOnMock invocation) { null, null, PILLAR_ID, 0L, null, null, null, null, null, null, null); verify(iterator).getNextAuditTrailEvent(); - //Assert.assertEquals(store.getCallsToGetAuditTrails(), settings.getRepositorySettings().getGetAuditTrailSettings().getNonPillarContributorIDs().size()); + //Assertions.assertEquals(store.getCallsToGetAuditTrails(), settings.getRepositorySettings().getGetAuditTrailSettings().getNonPillarContributorIDs().size()); - //Assert.assertEquals(store.getCallsToGetPreservationSequenceNumber(), 2); - assertEquals(client.getCallsToPutFile(), 1); + //Assertions.assertEquals(store.getCallsToGetPreservationSequenceNumber(), 2); + assertEquals(1, client.getCallsToPutFile()); } - @Test(groups = {"regressiontest"}) + @Test + @Tag("regressiontest") @SuppressWarnings("rawtypes") public void auditPreservationIngestTest() throws Exception { addDescription("Tests the ingest of the audit trail preservation."); @@ -188,7 +195,7 @@ public void auditPreservationIngestTest() throws Exception { verify(store).getAuditTrailsByIterator(null, collectionID, PILLAR_ID, 1L, null, null, null, null, null, null, null); - assertEquals(client.getCallsToPutFile(), 1); + assertEquals(1, client.getCallsToPutFile()); verify(fileExchange).putFile(any(FileInputStream.class), any(URL.class)); } diff --git a/bitrepository-audit-trail-service/src/test/java/org/bitrepository/audittrails/store/AuditDatabaseTest.java b/bitrepository-audit-trail-service/src/test/java/org/bitrepository/audittrails/store/AuditDatabaseTest.java index c2f0b220e..74ff121e3 100644 --- a/bitrepository-audit-trail-service/src/test/java/org/bitrepository/audittrails/store/AuditDatabaseTest.java +++ b/bitrepository-audit-trail-service/src/test/java/org/bitrepository/audittrails/store/AuditDatabaseTest.java @@ -5,16 +5,16 @@ * Copyright (C) 2010 - 2012 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% @@ -30,9 +30,10 @@ import org.bitrepository.service.database.DatabaseManager; import org.bitrepository.service.database.DerbyDatabaseDestroyer; import org.jaccept.structure.ExtendedTestCase; -import org.testng.Assert; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; import javax.xml.datatype.XMLGregorianCalendar; import java.math.BigInteger; @@ -44,7 +45,9 @@ import java.util.Locale; public class AuditDatabaseTest extends ExtendedTestCase { - /** The settings for the tests. Should be instantiated in the setup.*/ + /** + * The settings for the tests. Should be instantiated in the setup. + */ Settings settings; String fileID = "TEST-FILE-ID-" + new Date().getTime(); String fileID2 = "ANOTHER-FILE-ID" + new Date().getTime(); @@ -57,8 +60,8 @@ public class AuditDatabaseTest extends ExtendedTestCase { static final String fingerprint2 = "baba"; static final String operationID2 = "4321"; - - @BeforeMethod (alwaysRun = true) + + @BeforeEach public void setup() throws Exception { settings = TestSettingsProvider.reloadSettings("AuditDatabaseUnderTest"); DerbyDatabaseDestroyer.deleteDatabase( @@ -66,125 +69,130 @@ public void setup() throws Exception { AuditTrailDatabaseCreator auditTrailDatabaseCreator = new AuditTrailDatabaseCreator(); auditTrailDatabaseCreator.createAuditTrailDatabase(settings, null); - + collectionID = settings.getCollections().get(0).getID(); } - - @Test(groups = {"regressiontest", "databasetest"}) + + + @Test + @Tag("regressiontest") + @Tag("databasetest") public void AuditDatabaseExtractionTest() throws Exception { addDescription("Testing the connection to the audit trail service database especially with regards to " + "extracting the data from it."); addStep("Setup the variables and constants.", "Should be ok."); Date restrictionDate = new Date(123456789); // Sometime between epoch and now! - + addStep("Adds the variables to the settings and instantaites the database cache", "Should be connected."); DatabaseManager dm = new AuditTrailDatabaseManager( settings.getReferenceSettings().getAuditTrailServiceSettings().getAuditTrailServiceDatabase()); AuditTrailServiceDAO database = new AuditTrailServiceDAO(dm); addStep("Validate that the database is empty and then populate it.", "Should be possible."); - Assert.assertEquals(database.largestSequenceNumber(pillarID, collectionID), 0); + Assertions.assertEquals(0, database.largestSequenceNumber(pillarID, collectionID)); database.addAuditTrails(createEvents(), collectionID, pillarID); - Assert.assertEquals(database.largestSequenceNumber(pillarID, collectionID), 10); - + Assertions.assertEquals(10, database.largestSequenceNumber(pillarID, collectionID)); + addStep("Extract the audit trails", ""); - List res = getEventsFromIterator(database.getAuditTrailsByIterator(null, null, null, null, + List res = getEventsFromIterator(database.getAuditTrailsByIterator(null, null, null, null, null, null, null, null, null, null, null)); - Assert.assertEquals(res.size(), 2, res.toString()); - + Assertions.assertEquals(2, res.size(), res.toString()); + addStep("Test the extraction of FileID", "Should be able to extract the audit of each file individually."); res = getEventsFromIterator(database.getAuditTrailsByIterator(fileID, null, null, null, null, null, null, null, null, null, null)); - Assert.assertEquals(res.size(), 1, res.toString()); - Assert.assertEquals(res.get(0).getFileID(), fileID); - + Assertions.assertEquals(1, res.size(), res.toString()); + Assertions.assertEquals(fileID, res.get(0).getFileID()); + res = getEventsFromIterator(database.getAuditTrailsByIterator(fileID2, null, null, null, null, null, null, null, null, null, null)); - Assert.assertEquals(res.size(), 1, res.toString()); - Assert.assertEquals(res.get(0).getFileID(), fileID2); - + Assertions.assertEquals(1, res.size(), res.toString()); + Assertions.assertEquals(fileID2, res.get(0).getFileID()); + addStep("Test the extraction of CollectionID", "Only results when the defined collection is used"); res = getEventsFromIterator(database.getAuditTrailsByIterator(null, collectionID, null, null, null, null, null, null, null, null, null)); - Assert.assertEquals(res.size(), 2, res.toString()); - - res = getEventsFromIterator(database.getAuditTrailsByIterator(null, - "NOT-THE-CORRECT-COLLECTION-ID" + System.currentTimeMillis(), null, null, null, null, null, + Assertions.assertEquals(2, res.size(), res.toString()); + + res = getEventsFromIterator(database.getAuditTrailsByIterator(null, + "NOT-THE-CORRECT-COLLECTION-ID" + System.currentTimeMillis(), null, null, null, null, null, null, null, null, null)); - Assert.assertEquals(res.size(), 0, res.toString()); - + Assertions.assertEquals(0, res.size(), res.toString()); + addStep("Perform extraction based on the component id.", ""); res = getEventsFromIterator(database.getAuditTrailsByIterator(null, null, pillarID, null, null, null, null, null, null, null, null)); - Assert.assertEquals(res.size(), 2, res.toString()); - res = getEventsFromIterator(database.getAuditTrailsByIterator(null, null, "NO COMPONENT", null, null, null, null, + Assertions.assertEquals(2, res.size(), res.toString()); + res = getEventsFromIterator(database.getAuditTrailsByIterator(null, null, "NO COMPONENT", null, null, null, null, null, null, null, null)); - Assert.assertEquals(res.size(), 0, res.toString()); - - addStep("Perform extraction based on the sequence number restriction", + Assertions.assertEquals(0, res.size(), res.toString()); + + addStep("Perform extraction based on the sequence number restriction", "Should be possible to have both lower and upper sequence number restrictions."); - res = getEventsFromIterator(database.getAuditTrailsByIterator(null, null, null, 5L, null, null, null, null, + res = getEventsFromIterator(database.getAuditTrailsByIterator(null, null, null, 5L, null, null, null, null, null, null, null)); - Assert.assertEquals(res.size(), 1, res.toString()); - Assert.assertEquals(res.get(0).getFileID(), fileID2); - res = getEventsFromIterator(database.getAuditTrailsByIterator(null, null, null, null, 5L, null, null, null, + Assertions.assertEquals(1, res.size(), res.toString()); + Assertions.assertEquals(res.get(0).getFileID(), fileID2); + res = getEventsFromIterator(database.getAuditTrailsByIterator(null, null, null, null, 5L, null, null, null, null, null, null)); - Assert.assertEquals(res.size(), 1, res.toString()); - Assert.assertEquals(res.get(0).getFileID(), fileID); - - addStep("Perform extraction based on actor id restriction.", + Assertions.assertEquals(1, res.size(), res.toString()); + Assertions.assertEquals(res.get(0).getFileID(), fileID); + + addStep("Perform extraction based on actor id restriction.", "Should be possible to restrict on the id of the actor."); - res = getEventsFromIterator(database.getAuditTrailsByIterator(null, null, null, null, null, actor1, null, + res = getEventsFromIterator(database.getAuditTrailsByIterator(null, null, null, null, null, actor1, null, null, null, null, null)); - Assert.assertEquals(res.size(), 1, res.toString()); - Assert.assertEquals(res.get(0).getActorOnFile(), actor1); - res = getEventsFromIterator(database.getAuditTrailsByIterator(null, null, null, null, null, actor2, null, + Assertions.assertEquals(1, res.size(), res.toString()); + Assertions.assertEquals(res.get(0).getActorOnFile(), actor1); + res = getEventsFromIterator(database.getAuditTrailsByIterator(null, null, null, null, null, actor2, null, null, null, null, null)); - Assert.assertEquals(res.size(), 1, res.toString()); - Assert.assertEquals(res.get(0).getActorOnFile(), actor2); - - addStep("Perform extraction based on operation restriction.", + Assertions.assertEquals(1, res.size(), res.toString()); + Assertions.assertEquals(res.get(0).getActorOnFile(), actor2); + + addStep("Perform extraction based on operation restriction.", "Should be possible to restrict on the FileAction operation."); - res = getEventsFromIterator(database.getAuditTrailsByIterator(null, null, null, null, null, null, + res = getEventsFromIterator(database.getAuditTrailsByIterator(null, null, null, null, null, null, FileAction.INCONSISTENCY, null, null, null, null)); - Assert.assertEquals(res.size(), 1, res.toString()); - Assert.assertEquals(res.get(0).getActionOnFile(), FileAction.INCONSISTENCY); - res = getEventsFromIterator(database.getAuditTrailsByIterator(null, null, null, null, null, null, + Assertions.assertEquals(1, res.size(), res.toString()); + Assertions.assertEquals(FileAction.INCONSISTENCY, res.get(0).getActionOnFile()); + res = getEventsFromIterator(database.getAuditTrailsByIterator(null, null, null, null, null, null, FileAction.FAILURE, null, null, null, null)); - Assert.assertEquals(res.size(), 1, res.toString()); - Assert.assertEquals(res.get(0).getActionOnFile(), FileAction.FAILURE); - - addStep("Perform extraction based on date restriction.", + Assertions.assertEquals(1, res.size(), res.toString()); + Assertions.assertEquals(FileAction.FAILURE, res.get(0).getActionOnFile()); + + addStep("Perform extraction based on date restriction.", "Should be possible to restrict on the date of the audit."); - res = getEventsFromIterator(database.getAuditTrailsByIterator(null, null, null, null, null, null, null, + res = getEventsFromIterator(database.getAuditTrailsByIterator(null, null, null, null, null, null, null, restrictionDate, null, null, null)); - Assert.assertEquals(res.size(), 1, res.toString()); - Assert.assertEquals(res.get(0).getFileID(), fileID2); - res = getEventsFromIterator(database.getAuditTrailsByIterator(null, null, null, null, null, null, null, + Assertions.assertEquals(1, res.size(), res.toString()); + Assertions.assertEquals(res.get(0).getFileID(), fileID2); + res = getEventsFromIterator(database.getAuditTrailsByIterator(null, null, null, null, null, null, null, null, restrictionDate, null, null)); - Assert.assertEquals(res.size(), 1, res.toString()); - Assert.assertEquals(res.get(0).getFileID(), fileID); + Assertions.assertEquals(1, res.size(), res.toString()); + Assertions.assertEquals(res.get(0).getFileID(), fileID); - addStep("Perform extraction based on fingerprint restriction.", + addStep("Perform extraction based on fingerprint restriction.", "Should be possible to restrict on the fingerprint of the audit."); - res = getEventsFromIterator(database.getAuditTrailsByIterator(null, null, null, null, null, null, null, + res = getEventsFromIterator(database.getAuditTrailsByIterator(null, null, null, null, null, null, null, null, null, fingerprint1, null)); - Assert.assertEquals(res.size(), 1, res.toString()); - Assert.assertEquals(res.get(0).getFileID(), fileID); - Assert.assertEquals(res.get(0).getCertificateID(), fingerprint1); - - addStep("Perform extraction based on operationID restriction.", + Assertions.assertEquals(1, res.size(), res.toString()); + Assertions.assertEquals(res.get(0).getFileID(), fileID); + Assertions.assertEquals(fingerprint1, res.get(0).getCertificateID()); + + addStep("Perform extraction based on operationID restriction.", "Should be possible to restrict on the operationID of the audit."); - res = getEventsFromIterator(database.getAuditTrailsByIterator(null, null, null, null, null, null, null, + res = getEventsFromIterator(database.getAuditTrailsByIterator(null, null, null, null, null, null, null, null, null, null, operationID2)); - Assert.assertEquals(res.size(), 1, res.toString()); - Assert.assertEquals(res.get(0).getFileID(), fileID2); - Assert.assertEquals(res.get(0).getOperationID(), operationID2); - + Assertions.assertEquals(1, res.size(), res.toString()); + Assertions.assertEquals(res.get(0).getFileID(), fileID2); + Assertions.assertEquals(operationID2, res.get(0).getOperationID()); + database.close(); } - @Test(groups = {"regressiontest", "databasetest"}) + @Test + @Tag("regressiontest") + @Tag("databasetest") public void AuditDatabasePreservationTest() throws Exception { addDescription("Tests the functions related to the preservation of the database."); addStep("Adds the variables to the settings and instantaites the database cache", "Should be connected."); @@ -192,64 +200,68 @@ public void AuditDatabasePreservationTest() throws Exception { settings.getReferenceSettings().getAuditTrailServiceSettings().getAuditTrailServiceDatabase()); AuditTrailServiceDAO database = new AuditTrailServiceDAO(dm); - Assert.assertEquals(database.largestSequenceNumber(pillarID, collectionID), 0); + Assertions.assertEquals(0, database.largestSequenceNumber(pillarID, collectionID)); database.addAuditTrails(createEvents(), collectionID, pillarID); - Assert.assertEquals(database.largestSequenceNumber(pillarID, collectionID), 10); + Assertions.assertEquals(10, database.largestSequenceNumber(pillarID, collectionID)); - addStep("Validate the preservation sequence number", + addStep("Validate the preservation sequence number", "Should be zero, since it has not been updated yet."); long pindex = database.getPreservationSequenceNumber(pillarID, collectionID); - Assert.assertEquals(pindex, 0); + Assertions.assertEquals(0, pindex); addStep("Validate the insertion of the preservation sequence number", "Should be the same value extracted afterwards."); long givenPreservationIndex = 123456789; database.setPreservationSequenceNumber(pillarID, collectionID, givenPreservationIndex); - Assert.assertEquals(database.getPreservationSequenceNumber(pillarID, collectionID), givenPreservationIndex); + Assertions.assertEquals(givenPreservationIndex, database.getPreservationSequenceNumber(pillarID, collectionID)); database.close(); } - - @Test(groups = {"regressiontest", "databasetest"}) - public void auditDatabaseCorrectTimestampTest() throws ParseException { + + @Test + @Tag("regressiontest") + @Tag("databasetest") + public void auditDatabaseCorrectTimestampTest() throws ParseException { addDescription("Testing the correct ingest and extraction of audittrail dates"); DatabaseManager dm = new AuditTrailDatabaseManager( settings.getReferenceSettings().getAuditTrailServiceSettings().getAuditTrailServiceDatabase()); AuditTrailServiceDAO database = new AuditTrailServiceDAO(dm); - + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX", Locale.ROOT); Date summertimeTS = sdf.parse("2015-10-25T02:59:54.000+02:00"); Date summertimeUnix = new Date(1445734794000L); - Assert.assertEquals(summertimeTS, summertimeUnix); - + Assertions.assertEquals(summertimeTS, summertimeUnix); + Date wintertimeTS = sdf.parse("2015-10-25T02:59:54.000+01:00"); Date wintertimeUnix = new Date(1445738394000L); - Assert.assertEquals(wintertimeTS, wintertimeUnix); - + Assertions.assertEquals(wintertimeTS, wintertimeUnix); + AuditTrailEvents events = new AuditTrailEvents(); - events.getAuditTrailEvent().add(createSingleEvent(CalendarUtils.getXmlGregorianCalendar(summertimeTS), - FileAction.CHECKSUM_CALCULATED, "actor", "auditInfo", "summertime", "info", pillarID, new BigInteger("1"), + events.getAuditTrailEvent().add(createSingleEvent(CalendarUtils.getXmlGregorianCalendar(summertimeTS), + FileAction.CHECKSUM_CALCULATED, "actor", "auditInfo", "summertime", "info", pillarID, new BigInteger("1"), operationID1, fingerprint1)); - events.getAuditTrailEvent().add(createSingleEvent(CalendarUtils.getXmlGregorianCalendar(wintertimeTS), - FileAction.CHECKSUM_CALCULATED, "actor", "auditInfo", "wintertime", "info", pillarID, new BigInteger("1"), + events.getAuditTrailEvent().add(createSingleEvent(CalendarUtils.getXmlGregorianCalendar(wintertimeTS), + FileAction.CHECKSUM_CALCULATED, "actor", "auditInfo", "wintertime", "info", pillarID, new BigInteger("1"), operationID1, fingerprint1)); database.addAuditTrails(events, collectionID, pillarID); - - List res = getEventsFromIterator(database.getAuditTrailsByIterator("summertime", null, null, null, + + List res = getEventsFromIterator(database.getAuditTrailsByIterator("summertime", null, null, null, null, null, null, null, null, null, null)); - Assert.assertEquals(res.size(), 1, res.toString()); - Assert.assertEquals( + Assertions.assertEquals(1, res.size(), res.toString()); + Assertions.assertEquals( CalendarUtils.convertFromXMLGregorianCalendar(res.get(0).getActionDateTime()), summertimeUnix); - - res = getEventsFromIterator(database.getAuditTrailsByIterator("wintertime", null, null, null, null, null, null, + + res = getEventsFromIterator(database.getAuditTrailsByIterator("wintertime", null, null, null, null, null, null, null, null, null, null)); - Assert.assertEquals(res.size(), 1, res.toString()); - Assert.assertEquals( + Assertions.assertEquals(1, res.size(), res.toString()); + Assertions.assertEquals( CalendarUtils.convertFromXMLGregorianCalendar(res.get(0).getActionDateTime()), wintertimeUnix); } - - @Test(groups = {"regressiontest", "databasetest"}) + + @Test + @Tag("regressiontest") + @Tag("databasetest") public void AuditDatabaseIngestTest() throws Exception { addDescription("Testing ingest of audittrails into the database"); addStep("Adds the variables to the settings and instantaites the database cache", "Should be connected."); @@ -258,153 +270,154 @@ public void AuditDatabaseIngestTest() throws Exception { AuditTrailServiceDAO database = new AuditTrailServiceDAO(dm); AuditTrailEvents events; String veryLongString = ""; - for(int i = 0; i < 255; i++) { + for (int i = 0; i < 255; i++) { veryLongString += i; } - + addStep("Test ingesting with all data", "No failure"); events = new AuditTrailEvents(); - events.getAuditTrailEvent().add(createSingleEvent(CalendarUtils.getNow(), FileAction.CHECKSUM_CALCULATED, + events.getAuditTrailEvent().add(createSingleEvent(CalendarUtils.getNow(), FileAction.CHECKSUM_CALCULATED, "actor", "auditInfo", "fileID", "info", pillarID, new BigInteger("1"), operationID1, fingerprint1)); database.addAuditTrails(events, collectionID, pillarID); - - + + addStep("Test ingesting with no timestamp", "No failure"); events = new AuditTrailEvents(); - events.getAuditTrailEvent().add(createSingleEvent(null, FileAction.CHECKSUM_CALCULATED, + events.getAuditTrailEvent().add(createSingleEvent(null, FileAction.CHECKSUM_CALCULATED, "actor", "auditInfo", "fileID", "info", pillarID, new BigInteger("2"), operationID1, fingerprint1)); try { database.addAuditTrails(events, collectionID, pillarID); - Assert.fail("Should throw an exception."); - } catch (IllegalArgumentException e) { + Assertions.fail("Should throw an exception."); + } catch (IllegalArgumentException e) { // expected } - + addStep("Test ingesting with no file action", "No failure"); events = new AuditTrailEvents(); - events.getAuditTrailEvent().add(createSingleEvent(CalendarUtils.getNow(), null, + events.getAuditTrailEvent().add(createSingleEvent(CalendarUtils.getNow(), null, "actor", "auditInfo", "fileID", "info", pillarID, new BigInteger("3"), operationID1, fingerprint1)); try { database.addAuditTrails(events, collectionID, pillarID); - Assert.fail("Should throw an exception."); + Assertions.fail("Should throw an exception."); } catch (IllegalStateException e) { //expected } - + addStep("Test ingesting with no actor", "Throws exception"); events = new AuditTrailEvents(); - events.getAuditTrailEvent().add(createSingleEvent(CalendarUtils.getNow(), FileAction.CHECKSUM_CALCULATED, + events.getAuditTrailEvent().add(createSingleEvent(CalendarUtils.getNow(), FileAction.CHECKSUM_CALCULATED, null, "auditInfo", "fileID", "info", pillarID, new BigInteger("4"), operationID1, fingerprint1)); try { database.addAuditTrails(events, collectionID, pillarID); - Assert.fail("Should throw an exception."); + Assertions.fail("Should throw an exception."); } catch (IllegalStateException e) { // expected } addStep("Test ingesting with no audit info", "No failure"); events = new AuditTrailEvents(); - events.getAuditTrailEvent().add(createSingleEvent(CalendarUtils.getNow(), FileAction.CHECKSUM_CALCULATED, + events.getAuditTrailEvent().add(createSingleEvent(CalendarUtils.getNow(), FileAction.CHECKSUM_CALCULATED, "actor", null, "fileID", "info", pillarID, new BigInteger("5"), operationID1, fingerprint1)); database.addAuditTrails(events, collectionID, pillarID); addStep("Test ingesting with no file id", "Throws exception"); events = new AuditTrailEvents(); - events.getAuditTrailEvent().add(createSingleEvent(CalendarUtils.getNow(), FileAction.CHECKSUM_CALCULATED, + events.getAuditTrailEvent().add(createSingleEvent(CalendarUtils.getNow(), FileAction.CHECKSUM_CALCULATED, "actor", "auditInfo", null, "info", pillarID, new BigInteger("6"), operationID1, fingerprint1)); try { database.addAuditTrails(events, collectionID, pillarID); - Assert.fail("Should throw an exception."); + Assertions.fail("Should throw an exception."); } catch (IllegalStateException e) { // expected - } + } addStep("Test ingesting with no info", "No failure"); events = new AuditTrailEvents(); - events.getAuditTrailEvent().add(createSingleEvent(CalendarUtils.getNow(), FileAction.CHECKSUM_CALCULATED, + events.getAuditTrailEvent().add(createSingleEvent(CalendarUtils.getNow(), FileAction.CHECKSUM_CALCULATED, "actor", "auditInfo", "fileID", null, pillarID, new BigInteger("7"), operationID1, fingerprint1)); database.addAuditTrails(events, collectionID, pillarID); addStep("Test ingesting with no component id", "Throws exception"); events = new AuditTrailEvents(); - events.getAuditTrailEvent().add(createSingleEvent(CalendarUtils.getNow(), FileAction.CHECKSUM_CALCULATED, + events.getAuditTrailEvent().add(createSingleEvent(CalendarUtils.getNow(), FileAction.CHECKSUM_CALCULATED, "actor", "auditInfo", "fileID", "info", null, new BigInteger("8"), operationID1, fingerprint1)); try { database.addAuditTrails(events, collectionID, pillarID); - Assert.fail("Should throw an exception."); + Assertions.fail("Should throw an exception."); } catch (IllegalStateException e) { // expected } - - + + // broken (null-pointer) addStep("Test ingesting with no sequence number", "Throws exception"); events = new AuditTrailEvents(); - events.getAuditTrailEvent().add(createSingleEvent(CalendarUtils.getNow(), FileAction.CHECKSUM_CALCULATED, + events.getAuditTrailEvent().add(createSingleEvent(CalendarUtils.getNow(), FileAction.CHECKSUM_CALCULATED, "actor", "auditInfo", "fileID", "info", pillarID, null, operationID1, fingerprint1)); try { database.addAuditTrails(events, collectionID, pillarID); - Assert.fail("Should throw an exception."); + Assertions.fail("Should throw an exception."); } catch (IllegalStateException e) { // expected } - + addStep("Test ingest with very long auditInfo (255+)", "Not failing any more"); events = new AuditTrailEvents(); - events.getAuditTrailEvent().add(createSingleEvent(CalendarUtils.getNow(), FileAction.CHECKSUM_CALCULATED, + events.getAuditTrailEvent().add(createSingleEvent(CalendarUtils.getNow(), FileAction.CHECKSUM_CALCULATED, "actor", veryLongString, "fileID", "info", pillarID, new BigInteger("9"), operationID1, fingerprint1)); database.addAuditTrails(events, collectionID, pillarID); - + addStep("Test ingest with very long info (255+)", "Not failing any more"); events = new AuditTrailEvents(); - events.getAuditTrailEvent().add(createSingleEvent(CalendarUtils.getNow(), FileAction.CHECKSUM_CALCULATED, + events.getAuditTrailEvent().add(createSingleEvent(CalendarUtils.getNow(), FileAction.CHECKSUM_CALCULATED, "actor", "auditInfo", "fileID", veryLongString, pillarID, new BigInteger("10"), operationID1, fingerprint1)); database.addAuditTrails(events, collectionID, pillarID); } - - - @Test(groups = {"regressiontest", "databasetest"}) + + + @Test + @Tag("regressiontest") + @Tag("databasetest") public void AuditDatabaseGoodIngestTest() throws Exception { addDescription("Testing good case ingest of audittrails into the database"); addStep("Adds the variables to the settings and instantaites the database cache", "Should be connected."); DatabaseManager dm = new AuditTrailDatabaseManager( settings.getReferenceSettings().getAuditTrailServiceSettings().getAuditTrailServiceDatabase()); AuditTrailServiceDAO database = new AuditTrailServiceDAO(dm); - + addStep("Build test data", "No failure"); AuditTrailEvents events = new AuditTrailEvents(); - events.getAuditTrailEvent().add(createSingleEvent(CalendarUtils.getNow(), FileAction.PUT_FILE, + events.getAuditTrailEvent().add(createSingleEvent(CalendarUtils.getNow(), FileAction.PUT_FILE, "actor", "auditInfo", "fileID", "info", pillarID, new BigInteger("1"), operationID1, fingerprint1)); - events.getAuditTrailEvent().add(createSingleEvent(CalendarUtils.getNow(), FileAction.CHECKSUM_CALCULATED, + events.getAuditTrailEvent().add(createSingleEvent(CalendarUtils.getNow(), FileAction.CHECKSUM_CALCULATED, "actor", "auditInfo", "fileID", "info", pillarID, new BigInteger("2"), operationID1, null)); - events.getAuditTrailEvent().add(createSingleEvent(CalendarUtils.getNow(), FileAction.REPLACE_FILE, + events.getAuditTrailEvent().add(createSingleEvent(CalendarUtils.getNow(), FileAction.REPLACE_FILE, "actor", "auditInfo", "fileID", "info", pillarID, new BigInteger("3"), null, fingerprint1)); - events.getAuditTrailEvent().add(createSingleEvent(CalendarUtils.getNow(), FileAction.CHECKSUM_CALCULATED, + events.getAuditTrailEvent().add(createSingleEvent(CalendarUtils.getNow(), FileAction.CHECKSUM_CALCULATED, "actor", "auditInfo", "fileID", "info", pillarID, new BigInteger("4"), null, null)); - + database.addAuditTrails(events, collectionID, pillarID); - - - + + } - + private AuditTrailEvents createEvents() { AuditTrailEvents events = new AuditTrailEvents(); - - AuditTrailEvent event1 = createSingleEvent(CalendarUtils.getEpoch(), FileAction.INCONSISTENCY, actor1, + + AuditTrailEvent event1 = createSingleEvent(CalendarUtils.getEpoch(), FileAction.INCONSISTENCY, actor1, "I AM AUDIT", fileID, null, pillarID, new BigInteger("1"), operationID1, fingerprint1); events.getAuditTrailEvent().add(event1); - + AuditTrailEvent event2 = createSingleEvent(CalendarUtils.getNow(), FileAction.FAILURE, actor2, null, fileID2, "WHAT AM I DOING?", pillarID, new BigInteger("10"), operationID2, fingerprint2); events.getAuditTrailEvent().add(event2); return events; } - - private AuditTrailEvent createSingleEvent(XMLGregorianCalendar datetime, FileAction action, String actor, - String auditInfo, String fileID, String info, String component, BigInteger seqNumber, String operationID, - String fingerprint) { + + private AuditTrailEvent createSingleEvent(XMLGregorianCalendar datetime, FileAction action, String actor, + String auditInfo, String fileID, String info, String component, BigInteger seqNumber, String operationID, + String fingerprint) { AuditTrailEvent res = new AuditTrailEvent(); res.setActionDateTime(datetime); res.setActionOnFile(action); @@ -418,14 +431,14 @@ private AuditTrailEvent createSingleEvent(XMLGregorianCalendar datetime, FileAct res.setCertificateID(fingerprint); return res; } - + private List getEventsFromIterator(AuditEventIterator it) { List events = new ArrayList<>(); AuditTrailEvent event; - while((event = it.getNextAuditTrailEvent()) != null) { + while ((event = it.getNextAuditTrailEvent()) != null) { events.add(event); } - + return events; } } diff --git a/bitrepository-audit-trail-service/src/test/java/org/bitrepository/audittrails/store/AuditServiceDatabaseMigrationTest.java b/bitrepository-audit-trail-service/src/test/java/org/bitrepository/audittrails/store/AuditServiceDatabaseMigrationTest.java index a7b76f976..bddd2795e 100644 --- a/bitrepository-audit-trail-service/src/test/java/org/bitrepository/audittrails/store/AuditServiceDatabaseMigrationTest.java +++ b/bitrepository-audit-trail-service/src/test/java/org/bitrepository/audittrails/store/AuditServiceDatabaseMigrationTest.java @@ -29,15 +29,17 @@ import org.bitrepository.service.database.DerbyDatabaseDestroyer; import org.bitrepository.settings.referencesettings.DatabaseSpecifics; import org.jaccept.structure.ExtendedTestCase; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; import java.io.File; import static org.bitrepository.audittrails.store.AuditDatabaseConstants.AUDIT_TRAIL_TABLE; import static org.bitrepository.audittrails.store.AuditDatabaseConstants.DATABASE_VERSION_ENTRY; -import static org.testng.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; + // TODO: cannot test migration of version 1 to 2, since it requires a collection id. // Therefore this is only tested with version 2 of the database. @@ -49,7 +51,7 @@ public class AuditServiceDatabaseMigrationTest extends ExtendedTestCase { static final String FILE_ID = "default-file-id"; - @BeforeMethod (alwaysRun = true) + @BeforeEach public void setup() throws Exception { settings = TestSettingsProvider.reloadSettings("ReferencePillarTest"); @@ -63,12 +65,14 @@ public void setup() throws Exception { FileUtils.unzip(new File(PATH_TO_DATABASE_JAR_FILE), FileUtils.retrieveDirectory(PATH_TO_DATABASE_UNPACKED)); } - @AfterMethod (alwaysRun = true) + @AfterEach public void cleanup() throws Exception { FileUtils.deleteDirIfExists(new File(PATH_TO_DATABASE_UNPACKED)); } - @Test( groups = {"regressiontest", "databasetest"}) + @Test + @Tag("regressiontest") + @Tag("databasetest") public void testMigratingAuditServiceDatabase() { addDescription("Tests that the database can be migrated to latest version with the provided scripts."); DBConnector connector = new DBConnector( @@ -77,16 +81,16 @@ public void testMigratingAuditServiceDatabase() { addStep("Validate setup", "audit table has version 2 and database version 2"); String extractVersionSql = "SELECT version FROM tableversions WHERE tablename = ?"; int auditTableVersionBefore = DatabaseUtils.selectIntValue(connector, extractVersionSql, AUDIT_TRAIL_TABLE); - assertEquals(auditTableVersionBefore, 2, "Table version before migration"); + assertEquals(2, auditTableVersionBefore, "Table version before migration"); int dbTableVersionBefore = DatabaseUtils.selectIntValue(connector, extractVersionSql, DATABASE_VERSION_ENTRY); - assertEquals(dbTableVersionBefore, 2, "Table version before migration"); + assertEquals(2, dbTableVersionBefore, "Table version before migration"); addStep("Perform migration", "audit table version 5 and database-version is 6"); AuditTrailServiceDatabaseMigrator migrator = new AuditTrailServiceDatabaseMigrator(connector); migrator.migrate(); int auditTableVersionAfter = DatabaseUtils.selectIntValue(connector, extractVersionSql, AUDIT_TRAIL_TABLE); - assertEquals(auditTableVersionAfter, 5, "Table version after migration"); + assertEquals(5, auditTableVersionAfter, "Table version after migration"); int dbTableVersionAfter = DatabaseUtils.selectIntValue(connector, extractVersionSql, DATABASE_VERSION_ENTRY); - assertEquals(dbTableVersionAfter, 6, "Table version after migration"); + assertEquals(6, dbTableVersionAfter, "Table version after migration"); } } diff --git a/bitrepository-audit-trail-service/src/test/java/org/bitrepository/audittrails/store/AuditTrailReadDAO.java b/bitrepository-audit-trail-service/src/test/java/org/bitrepository/audittrails/store/AuditTrailReadDAO.java index 1a316d4d3..636310849 100644 --- a/bitrepository-audit-trail-service/src/test/java/org/bitrepository/audittrails/store/AuditTrailReadDAO.java +++ b/bitrepository-audit-trail-service/src/test/java/org/bitrepository/audittrails/store/AuditTrailReadDAO.java @@ -43,7 +43,7 @@ */ public class AuditTrailReadDAO { - private DBConnector dbConnector; + private final DBConnector dbConnector; public AuditTrailReadDAO(DatabaseManager databaseManager) { dbConnector = databaseManager.getConnector(); @@ -52,7 +52,7 @@ public AuditTrailReadDAO(DatabaseManager databaseManager) { public List getCollectionIDs() { String selectSql = "SELECT " + COLLECTION_ID + " FROM " + COLLECTION_TABLE; - return DatabaseUtils.selectStringList(dbConnector, selectSql, new Object[0]); + return DatabaseUtils.selectStringList(dbConnector, selectSql); } public List getFileIDs(String collectionID) { @@ -67,12 +67,12 @@ public List getFileIDs(String collectionID) { public List getContributorIDs() { String selectSql = "SELECT " + CONTRIBUTOR_ID + " FROM " + CONTRIBUTOR_TABLE; - return DatabaseUtils.selectStringList(dbConnector, selectSql, new Object[0]); + return DatabaseUtils.selectStringList(dbConnector, selectSql); } public List getActorNames() { String selectSql = "SELECT " + ACTOR_NAME + " FROM " + ACTOR_TABLE; - return DatabaseUtils.selectStringList(dbConnector, selectSql, new Object[0]); + return DatabaseUtils.selectStringList(dbConnector, selectSql); } } diff --git a/bitrepository-client/README.md b/bitrepository-client/README.md index 38852c244..a6cacf89a 100644 --- a/bitrepository-client/README.md +++ b/bitrepository-client/README.md @@ -197,7 +197,7 @@ public class BitrepositoryClientExample { public OperationEventType waitForFinish() throws InterruptedException { synchronized (finishLock) { - if(finished == false) { + if(!finished) { finishLock.wait(); } return finishEventType; @@ -260,4 +260,4 @@ public class BitrepositoryClientExample { } } -``` +``` diff --git a/bitrepository-client/src/main/java/org/bitrepository/client/conversation/FinishedState.java b/bitrepository-client/src/main/java/org/bitrepository/client/conversation/FinishedState.java index 7d0823d9d..b9538ee2f 100644 --- a/bitrepository-client/src/main/java/org/bitrepository/client/conversation/FinishedState.java +++ b/bitrepository-client/src/main/java/org/bitrepository/client/conversation/FinishedState.java @@ -25,7 +25,6 @@ package org.bitrepository.client.conversation; import org.bitrepository.bitrepositorymessages.MessageResponse; -import org.bitrepository.common.exceptions.UnableToFinishException; import java.time.Duration; import java.util.LinkedList; diff --git a/bitrepository-client/src/main/java/org/bitrepository/client/conversation/GeneralConversationState.java b/bitrepository-client/src/main/java/org/bitrepository/client/conversation/GeneralConversationState.java index c4dcfc827..354e66b16 100644 --- a/bitrepository-client/src/main/java/org/bitrepository/client/conversation/GeneralConversationState.java +++ b/bitrepository-client/src/main/java/org/bitrepository/client/conversation/GeneralConversationState.java @@ -42,7 +42,6 @@ import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; -import java.util.concurrent.TimeUnit; /** * Implements the generic conversation state functionality, @@ -73,6 +72,7 @@ protected GeneralConversationState(Collection expectedContributors) { */ public void start() { try { + System.out.println("DEBUG: " + getClass().getSimpleName() + ".start() - Expected contributors: " + responseStatus.getComponentsWhichShouldRespond()); if (!responseStatus.getOutstandingComponents().isEmpty()) { if (getTimeoutValue().compareTo(Duration.ZERO) > 0) { // TODO From Java 18 use: getTimeoutValue().isPositive() CountAndTimeUnit delay = TimeUtils.durationToCountAndTimeUnit(getTimeoutValue()); @@ -111,8 +111,11 @@ public final void handleMessage(Message message) { } try { + System.out.println("DEBUG: " + getClass().getSimpleName() + " processMessage from: " + message.getFrom()); if (processMessage(response)) { responseStatus.responseReceived(response); + System.out.println("DEBUG: Outstanding components: " + responseStatus.getOutstandingComponents()); + System.out.println("DEBUG: Have all responded: " + responseStatus.haveAllComponentsResponded(response)); if (responseStatus.haveAllComponentsResponded(response)) { scheduledTimeout.cancel(true); changeState(); diff --git a/bitrepository-client/src/main/java/org/bitrepository/client/conversation/mediator/CollectionBasedConversationMediator.java b/bitrepository-client/src/main/java/org/bitrepository/client/conversation/mediator/CollectionBasedConversationMediator.java index aa49b6ced..c61bae53e 100644 --- a/bitrepository-client/src/main/java/org/bitrepository/client/conversation/mediator/CollectionBasedConversationMediator.java +++ b/bitrepository-client/src/main/java/org/bitrepository/client/conversation/mediator/CollectionBasedConversationMediator.java @@ -26,7 +26,6 @@ import org.bitrepository.bitrepositorymessages.Message; import org.bitrepository.client.conversation.Conversation; -import org.bitrepository.client.eventhandler.ContributorEvent; import org.bitrepository.client.eventhandler.OperationFailedEvent; import org.bitrepository.common.DefaultThreadFactory; import org.bitrepository.common.settings.Settings; @@ -131,9 +130,12 @@ private void handleUnknownConversation(Message message) { @Override public void onMessage(Message message, MessageContext messageContext) { + System.out.println("DEBUG: ConversationMediator.onMessage - messageType: " + message.getClass().getSimpleName() + ", correlationID: " + message.getCorrelationID() + ", from: " + message.getFrom()); + System.out.println("DEBUG: ConversationMediator - Active conversations: " + conversations.keySet()); String messageCorrelationID = message.getCorrelationID(); Conversation conversation = conversations.get(messageCorrelationID); if (conversation != null) { + System.out.println("DEBUG: ConversationMediator - Delivering message to conversation: " + messageCorrelationID); conversation.onMessage(message, messageContext); } else { handleUnknownConversation(message); @@ -197,7 +199,7 @@ private static class FailingConversation implements Runnable { @Override public void run() { - OperationFailedEvent failedEvent = new OperationFailedEvent(null, message, Collections.emptyList()); + OperationFailedEvent failedEvent = new OperationFailedEvent(null, message, Collections.emptyList()); failedEvent.setConversationID(conversation.getConversationID()); conversation.failConversation(failedEvent); } diff --git a/bitrepository-client/src/main/java/org/bitrepository/commandline/eventhandler/CompleteEventAwaiter.java b/bitrepository-client/src/main/java/org/bitrepository/commandline/eventhandler/CompleteEventAwaiter.java index 793c528ae..c8916195a 100644 --- a/bitrepository-client/src/main/java/org/bitrepository/commandline/eventhandler/CompleteEventAwaiter.java +++ b/bitrepository-client/src/main/java/org/bitrepository/commandline/eventhandler/CompleteEventAwaiter.java @@ -32,7 +32,6 @@ import java.time.Duration; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; -import java.util.concurrent.TimeUnit; /** * EventHandler for awaiting an operation to be complete. diff --git a/bitrepository-client/src/main/java/org/bitrepository/commandline/eventhandler/PagingEventHandler.java b/bitrepository-client/src/main/java/org/bitrepository/commandline/eventhandler/PagingEventHandler.java index 0b34ff188..903898dc0 100644 --- a/bitrepository-client/src/main/java/org/bitrepository/commandline/eventhandler/PagingEventHandler.java +++ b/bitrepository-client/src/main/java/org/bitrepository/commandline/eventhandler/PagingEventHandler.java @@ -34,7 +34,6 @@ import java.util.Objects; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; -import java.util.concurrent.TimeUnit; /** * Event handler for operations that need paging functionality. diff --git a/bitrepository-client/src/test/java/org/bitrepository/access/getaudittrails/AuditTrailClientComponentTest.java b/bitrepository-client/src/test/java/org/bitrepository/access/getaudittrails/AuditTrailClientComponentTest.java index e16eeda11..98f7d21b1 100644 --- a/bitrepository-client/src/test/java/org/bitrepository/access/getaudittrails/AuditTrailClientComponentTest.java +++ b/bitrepository-client/src/test/java/org/bitrepository/access/getaudittrails/AuditTrailClientComponentTest.java @@ -5,16 +5,16 @@ * Copyright (C) 2010 - 2012 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% @@ -42,16 +42,17 @@ import org.bitrepository.common.utils.CalendarUtils; import org.bitrepository.protocol.bus.MessageReceiver; import org.bitrepository.settings.repositorysettings.Collection; -import org.testng.Assert; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; import javax.xml.datatype.DatatypeConfigurationException; import javax.xml.datatype.DatatypeFactory; import java.math.BigInteger; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; /** * Test the default AuditTrailClient. @@ -60,49 +61,49 @@ public class AuditTrailClientComponentTest extends DefaultClientTest { private GetAuditTrailsMessageFactory testMessageFactory; private DatatypeFactory datatypeFactory; - @BeforeMethod(alwaysRun=true) + @BeforeEach public void beforeMethodSetup() throws DatatypeConfigurationException { testMessageFactory = new GetAuditTrailsMessageFactory(settingsForTestClient.getComponentID()); - + Collection c = settingsForCUT.getRepositorySettings().getCollections().getCollection().get(0); c.setID(collectionID); c.getPillarIDs().getPillarID().clear(); c.getPillarIDs().getPillarID().add(PILLAR1_ID); c.getPillarIDs().getPillarID().add(PILLAR2_ID); - + settingsForCUT.getRepositorySettings().getCollections().getCollection().clear(); settingsForCUT.getRepositorySettings().getCollections().getCollection().add(c); - + settingsForCUT.getRepositorySettings().getGetAuditTrailSettings().getNonPillarContributorIDs().clear(); datatypeFactory = DatatypeFactory.newInstance(); } - @Test(groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public void verifyAuditTrailClientFromFactory() { - Assert.assertTrue(AccessComponentFactory.getInstance().createAuditTrailClient( - settingsForCUT, securityManager, settingsForTestClient.getComponentID()) - instanceof ConversationBasedAuditTrailClient, - "The default AuditTrailClient from the Access factory should be of the type '" + + Assertions.assertInstanceOf(ConversationBasedAuditTrailClient.class, AccessComponentFactory.getInstance().createAuditTrailClient( + settingsForCUT, securityManager, settingsForTestClient.getComponentID()), "The default AuditTrailClient from the Access factory should be of the type '" + ConversationBasedAuditTrailClient.class.getName() + "'."); } - @Test(groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public void getAllAuditTrailsTest() throws InterruptedException { addDescription("Tests the simplest case of getting all audit trail event for all contributors."); - + addStep("Create a AuditTrailClient.", ""); TestEventHandler testEventHandler = new TestEventHandler(testEventManager); AuditTrailClient client = createAuditTrailClient(); addStep("Retrieve all audit trails from the collection by calling with a null componentQueries array", "This should be interpreted as a request for all audit trails from all the collection settings " + - "defined contributors."); + "defined contributors."); client.getAuditTrails(collectionID, null, DEFAULT_FILE_ID, null, testEventHandler, null); - assertEquals(testEventHandler.waitForEvent().getEventType(), - OperationEvent.OperationEventType.IDENTIFY_REQUEST_SENT); + assertEquals(OperationEvent.OperationEventType.IDENTIFY_REQUEST_SENT, + testEventHandler.waitForEvent().getEventType()); IdentifyContributorsForGetAuditTrailsRequest receivedIdentifyRequest = - collectionReceiver.waitForMessage(IdentifyContributorsForGetAuditTrailsRequest.class); + collectionReceiver.waitForMessage(IdentifyContributorsForGetAuditTrailsRequest.class); assertEquals(receivedIdentifyRequest.getCollectionID(), collectionID); assertNotNull(receivedIdentifyRequest.getCorrelationID()); assertEquals(receivedIdentifyRequest.getReplyTo(), settingsForCUT.getReceiverDestinationID()); @@ -111,31 +112,31 @@ public void getAllAuditTrailsTest() throws InterruptedException { addStep("Send a identifyResponse from each pillar", "Two COMPONENT_IDENTIFIED events and a IDENTIFICATION_COMPLETE event should be received." + - "Rights after this a REQUEST_SENT should be received and a GetAuditTrailsRequest should " + - "be sent to each pillar"); + "Rights after this a REQUEST_SENT should be received and a GetAuditTrailsRequest should " + + "be sent to each pillar"); IdentifyContributorsForGetAuditTrailsResponse responsePillar1 = - testMessageFactory.createIdentifyContributorsForGetAuditTrailsResponse(receivedIdentifyRequest, - PILLAR1_ID, pillar1DestinationId); + testMessageFactory.createIdentifyContributorsForGetAuditTrailsResponse(receivedIdentifyRequest, + PILLAR1_ID, pillar1DestinationId); messageBus.sendMessage(responsePillar1); - assertEquals(testEventHandler.waitForEvent().getEventType(), - OperationEvent.OperationEventType.COMPONENT_IDENTIFIED); + assertEquals(OperationEvent.OperationEventType.COMPONENT_IDENTIFIED, + testEventHandler.waitForEvent().getEventType()); IdentifyContributorsForGetAuditTrailsResponse responsePillar2 = - testMessageFactory.createIdentifyContributorsForGetAuditTrailsResponse(receivedIdentifyRequest, - PILLAR2_ID, pillar2DestinationId); + testMessageFactory.createIdentifyContributorsForGetAuditTrailsResponse(receivedIdentifyRequest, + PILLAR2_ID, pillar2DestinationId); messageBus.sendMessage(responsePillar2); - assertEquals(testEventHandler.waitForEvent().getEventType(), - OperationEvent.OperationEventType.COMPONENT_IDENTIFIED); - assertEquals(testEventHandler.waitForEvent().getEventType(), - OperationEvent.OperationEventType.IDENTIFICATION_COMPLETE); + assertEquals(OperationEvent.OperationEventType.COMPONENT_IDENTIFIED, + testEventHandler.waitForEvent().getEventType()); + assertEquals(OperationEvent.OperationEventType.IDENTIFICATION_COMPLETE, + testEventHandler.waitForEvent().getEventType()); - assertEquals(testEventHandler.waitForEvent().getEventType(), - OperationEvent.OperationEventType.REQUEST_SENT); + assertEquals(OperationEvent.OperationEventType.REQUEST_SENT, + testEventHandler.waitForEvent().getEventType()); GetAuditTrailsRequest requestPillar1 = pillar1Receiver.waitForMessage(GetAuditTrailsRequest.class); assertEquals(requestPillar1.getCollectionID(), collectionID); assertEquals(requestPillar1.getCorrelationID(), receivedIdentifyRequest.getCorrelationID()); assertEquals(requestPillar1.getReplyTo(), settingsForCUT.getReceiverDestinationID()); - assertEquals(requestPillar1.getFileID(), DEFAULT_FILE_ID); + assertEquals(DEFAULT_FILE_ID, requestPillar1.getFileID()); assertEquals(requestPillar1.getFrom(), settingsForTestClient.getComponentID()); assertEquals(requestPillar1.getDestination(), pillar1DestinationId); @@ -143,39 +144,40 @@ public void getAllAuditTrailsTest() throws InterruptedException { assertEquals(requestPillar2.getCollectionID(), collectionID); assertEquals(requestPillar2.getCorrelationID(), receivedIdentifyRequest.getCorrelationID()); assertEquals(requestPillar2.getReplyTo(), settingsForCUT.getReceiverDestinationID()); - assertEquals(requestPillar2.getFileID(), DEFAULT_FILE_ID); + assertEquals(DEFAULT_FILE_ID, requestPillar2.getFileID()); assertEquals(requestPillar2.getFrom(), settingsForTestClient.getComponentID()); assertEquals(requestPillar2.getDestination(), pillar2DestinationId); addStep("Send a final response from pillar 1", - "A COMPONENT_COMPLETE event should be generated with the audit trail results."); + "A COMPONENT_COMPLETE event should be generated with the audit trail results."); ResultingAuditTrails result1 = createTestResultingAuditTrails(PILLAR1_ID); GetAuditTrailsFinalResponse resultPillar1 = - testMessageFactory.createGetAuditTrailsFinalResponse(requestPillar1, - PILLAR1_ID, pillar1DestinationId, result1); + testMessageFactory.createGetAuditTrailsFinalResponse(requestPillar1, + PILLAR1_ID, pillar1DestinationId, result1); messageBus.sendMessage(resultPillar1); - AuditTrailResult result1Event = (AuditTrailResult)testEventHandler.waitForEvent(); - assertEquals(result1Event.getEventType(), OperationEvent.OperationEventType.COMPONENT_COMPLETE); + AuditTrailResult result1Event = (AuditTrailResult) testEventHandler.waitForEvent(); + assertEquals(OperationEvent.OperationEventType.COMPONENT_COMPLETE, result1Event.getEventType()); assertEquals(result1Event.getAuditTrailEvents(), result1); addStep("Send a final response from pillar 2", "A COMPONENT_COMPLETE event should be generated with the audit trail results." + - "This should be followed by a COMPLETE event"); + "This should be followed by a COMPLETE event"); ResultingAuditTrails result2 = createTestResultingAuditTrails(PILLAR2_ID); GetAuditTrailsFinalResponse resultPillar2 = - testMessageFactory.createGetAuditTrailsFinalResponse(requestPillar1, - PILLAR2_ID, pillar2DestinationId, result2); + testMessageFactory.createGetAuditTrailsFinalResponse(requestPillar1, + PILLAR2_ID, pillar2DestinationId, result2); messageBus.sendMessage(resultPillar2); - AuditTrailResult result2Event = (AuditTrailResult)testEventHandler.waitForEvent(); - assertEquals(result2Event.getEventType(), OperationEvent.OperationEventType.COMPONENT_COMPLETE); + AuditTrailResult result2Event = (AuditTrailResult) testEventHandler.waitForEvent(); + assertEquals(OperationEvent.OperationEventType.COMPONENT_COMPLETE, result2Event.getEventType()); assertEquals(result2Event.getAuditTrailEvents(), result2); - assertEquals(testEventHandler.waitForEvent().getEventType(), - OperationEvent.OperationEventType.COMPLETE); + assertEquals(OperationEvent.OperationEventType.COMPLETE, + testEventHandler.waitForEvent().getEventType()); } - @Test(groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public void getSomeAuditTrailsTest() throws InterruptedException { addDescription("Tests the client maps a AuditTrail query correctly to a GetAuditTrail request."); @@ -183,61 +185,62 @@ public void getSomeAuditTrailsTest() throws InterruptedException { AuditTrailClient client = createAuditTrailClient(); addStep("Request audit trails from pillar 1 with both min and max sequence number set.", - "A identify request is sent."); + "A identify request is sent."); AuditTrailQuery query1 = new AuditTrailQuery(PILLAR1_ID, 1L, 3L, 10000); - client.getAuditTrails(collectionID, new AuditTrailQuery[] { query1 }, null, null, testEventHandler, null); + client.getAuditTrails(collectionID, new AuditTrailQuery[]{query1}, null, null, testEventHandler, null); IdentifyContributorsForGetAuditTrailsRequest identifyRequest = - collectionReceiver.waitForMessage(IdentifyContributorsForGetAuditTrailsRequest.class); - assertEquals(testEventHandler.waitForEvent().getEventType(), - OperationEvent.OperationEventType.IDENTIFY_REQUEST_SENT); + collectionReceiver.waitForMessage(IdentifyContributorsForGetAuditTrailsRequest.class); + assertEquals(OperationEvent.OperationEventType.IDENTIFY_REQUEST_SENT, + testEventHandler.waitForEvent().getEventType()); addStep("Send a identifyResponse from pillar1", "A COMPONENT_IDENTIFIED event and a IDENTIFICATION_COMPLETE event should be received." + - "Rights after this a REQUEST_SENT should be received and a GetAuditTrailsRequest should " + - "be sent to pillar1"); + "Rights after this a REQUEST_SENT should be received and a GetAuditTrailsRequest should " + + "be sent to pillar1"); IdentifyContributorsForGetAuditTrailsResponse responsePillar1 = - testMessageFactory.createIdentifyContributorsForGetAuditTrailsResponse(identifyRequest, - PILLAR1_ID, pillar1DestinationId); + testMessageFactory.createIdentifyContributorsForGetAuditTrailsResponse(identifyRequest, + PILLAR1_ID, pillar1DestinationId); messageBus.sendMessage(responsePillar1); IdentifyContributorsForGetAuditTrailsResponse responsePillar2 = - testMessageFactory.createIdentifyContributorsForGetAuditTrailsResponse(identifyRequest, - PILLAR2_ID, pillar2DestinationId); + testMessageFactory.createIdentifyContributorsForGetAuditTrailsResponse(identifyRequest, + PILLAR2_ID, pillar2DestinationId); messageBus.sendMessage(responsePillar2); - assertEquals(testEventHandler.waitForEvent().getEventType(), - OperationEvent.OperationEventType.COMPONENT_IDENTIFIED); - assertEquals(testEventHandler.waitForEvent().getEventType(), - OperationEvent.OperationEventType.IDENTIFICATION_COMPLETE); + assertEquals(OperationEvent.OperationEventType.COMPONENT_IDENTIFIED, + testEventHandler.waitForEvent().getEventType()); + assertEquals(OperationEvent.OperationEventType.IDENTIFICATION_COMPLETE, + testEventHandler.waitForEvent().getEventType()); - assertEquals(testEventHandler.waitForEvent().getEventType(), - OperationEvent.OperationEventType.REQUEST_SENT); + assertEquals(OperationEvent.OperationEventType.REQUEST_SENT, + testEventHandler.waitForEvent().getEventType()); GetAuditTrailsRequest requestPillar1 = pillar1Receiver.waitForMessage(GetAuditTrailsRequest.class); - assertEquals(requestPillar1.getMaxNumberOfResults().intValue(), 10000); - assertEquals(requestPillar1.getMinSequenceNumber().intValue(), 1); - assertEquals(requestPillar1.getMaxSequenceNumber().intValue(), 3); + assertEquals(10000, requestPillar1.getMaxNumberOfResults().intValue()); + assertEquals(1, requestPillar1.getMinSequenceNumber().intValue()); + assertEquals(3, requestPillar1.getMaxSequenceNumber().intValue()); addStep("Verify no request is sent to pillar2", ""); pillar2Receiver.checkNoMessageIsReceived(GetAuditTrailsRequest.class); addStep("Send a final response from pillar 1", "A COMPONENT_COMPLETE event should be generated with the audit trail results." + - "This should be followed by a COMPLETE event"); + "This should be followed by a COMPLETE event"); ResultingAuditTrails result = createTestResultingAuditTrails(PILLAR1_ID); GetAuditTrailsFinalResponse resultResponse = - testMessageFactory.createGetAuditTrailsFinalResponse(requestPillar1, - PILLAR1_ID, pillar1DestinationId, result); + testMessageFactory.createGetAuditTrailsFinalResponse(requestPillar1, + PILLAR1_ID, pillar1DestinationId, result); messageBus.sendMessage(resultResponse); - AuditTrailResult resultEvent = (AuditTrailResult)testEventHandler.waitForEvent(); - assertEquals(resultEvent.getEventType(), OperationEvent.OperationEventType.COMPONENT_COMPLETE); + AuditTrailResult resultEvent = (AuditTrailResult) testEventHandler.waitForEvent(); + assertEquals(OperationEvent.OperationEventType.COMPONENT_COMPLETE, resultEvent.getEventType()); assertEquals(resultEvent.getAuditTrailEvents(), result); - assertEquals(testEventHandler.waitForEvent().getEventType(), - OperationEvent.OperationEventType.COMPLETE); + assertEquals(OperationEvent.OperationEventType.COMPLETE, + testEventHandler.waitForEvent().getEventType()); } - @Test(groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public void negativeGetAuditTrailsResponseTest() throws InterruptedException { addDescription("Verify that the GetAuditTrail client works correct when receiving a negative " + - "GetAuditTrails response from one contributors."); + "GetAuditTrails response from one contributors."); addStep("Create a AuditTrailClient.", ""); TestEventHandler testEventHandler = new TestEventHandler(testEventManager); @@ -245,71 +248,72 @@ public void negativeGetAuditTrailsResponseTest() throws InterruptedException { addStep("Retrieve all audit trails from the collection by calling with a null componentQueries array", "This should be interpreted as a request for all audit trails from all the collection settings " + - "defined contributors."); + "defined contributors."); client.getAuditTrails(collectionID, null, null, null, testEventHandler, null); IdentifyContributorsForGetAuditTrailsRequest identifyRequest = - collectionReceiver.waitForMessage(IdentifyContributorsForGetAuditTrailsRequest.class); - assertEquals(testEventHandler.waitForEvent().getEventType(), - OperationEvent.OperationEventType.IDENTIFY_REQUEST_SENT); + collectionReceiver.waitForMessage(IdentifyContributorsForGetAuditTrailsRequest.class); + assertEquals(OperationEvent.OperationEventType.IDENTIFY_REQUEST_SENT, + testEventHandler.waitForEvent().getEventType()); addStep("Send a identifyResponse from each of the two pillars", "COMPONENT_IDENTIFIED events and a IDENTIFICATION_COMPLETE event should be received." + - "Rights after this a REQUEST_SENT should be received and a GetAuditTrailsRequest should " + - "be sent to each pillar"); + "Rights after this a REQUEST_SENT should be received and a GetAuditTrailsRequest should " + + "be sent to each pillar"); IdentifyContributorsForGetAuditTrailsResponse responsePillar1 = - testMessageFactory.createIdentifyContributorsForGetAuditTrailsResponse(identifyRequest, - PILLAR1_ID, pillar1DestinationId); + testMessageFactory.createIdentifyContributorsForGetAuditTrailsResponse(identifyRequest, + PILLAR1_ID, pillar1DestinationId); messageBus.sendMessage(responsePillar1); IdentifyContributorsForGetAuditTrailsResponse responsePillar2 = - testMessageFactory.createIdentifyContributorsForGetAuditTrailsResponse(identifyRequest, - PILLAR2_ID, pillar2DestinationId); + testMessageFactory.createIdentifyContributorsForGetAuditTrailsResponse(identifyRequest, + PILLAR2_ID, pillar2DestinationId); messageBus.sendMessage(responsePillar2); - assertEquals(testEventHandler.waitForEvent().getEventType(), - OperationEvent.OperationEventType.COMPONENT_IDENTIFIED); - assertEquals(testEventHandler.waitForEvent().getEventType(), - OperationEvent.OperationEventType.COMPONENT_IDENTIFIED); - assertEquals(testEventHandler.waitForEvent().getEventType(), - OperationEvent.OperationEventType.IDENTIFICATION_COMPLETE); + assertEquals(OperationEvent.OperationEventType.COMPONENT_IDENTIFIED, + testEventHandler.waitForEvent().getEventType()); + assertEquals(OperationEvent.OperationEventType.COMPONENT_IDENTIFIED, + testEventHandler.waitForEvent().getEventType()); + assertEquals(OperationEvent.OperationEventType.IDENTIFICATION_COMPLETE, + testEventHandler.waitForEvent().getEventType()); - assertEquals(testEventHandler.waitForEvent().getEventType(), - OperationEvent.OperationEventType.REQUEST_SENT); + assertEquals(OperationEvent.OperationEventType.REQUEST_SENT, + testEventHandler.waitForEvent().getEventType()); GetAuditTrailsRequest requestPillar1 = pillar1Receiver.waitForMessage(GetAuditTrailsRequest.class); assertNotNull(requestPillar1); GetAuditTrailsRequest requestPillar2 = pillar2Receiver.waitForMessage(GetAuditTrailsRequest.class); assertNotNull(requestPillar2); addStep("Send a failed response from pillar 1", - "A COMPONENT_FAILED event should be generated."); + "A COMPONENT_FAILED event should be generated."); ResultingAuditTrails result1 = createTestResultingAuditTrails(PILLAR1_ID); GetAuditTrailsFinalResponse failedResponsePillar1 = - testMessageFactory.createGetAuditTrailsFinalResponse(requestPillar1, - PILLAR1_ID, pillar1DestinationId, result1); + testMessageFactory.createGetAuditTrailsFinalResponse(requestPillar1, + PILLAR1_ID, pillar1DestinationId, result1); ResponseInfo failedInfo = new ResponseInfo(); failedInfo.setResponseText("GetAuditTrails failed"); failedInfo.setResponseCode(ResponseCode.FAILURE); failedResponsePillar1.setResponseInfo(failedInfo); messageBus.sendMessage(failedResponsePillar1); - assertEquals(testEventHandler.waitForEvent().getEventType(), - OperationEvent.OperationEventType.COMPONENT_FAILED); + assertEquals(OperationEvent.OperationEventType.COMPONENT_FAILED, + testEventHandler.waitForEvent().getEventType()); addStep("Send a final response from pillar 2", "A COMPONENT_COMPLETE event should be generated with the audit trail results." + - "This should be followed by a COMPLETE event"); + "This should be followed by a COMPLETE event"); ResultingAuditTrails result2 = createTestResultingAuditTrails(PILLAR2_ID); GetAuditTrailsFinalResponse resultPillar2 = - testMessageFactory.createGetAuditTrailsFinalResponse(requestPillar1, - PILLAR2_ID, pillar2DestinationId, result2); + testMessageFactory.createGetAuditTrailsFinalResponse(requestPillar1, + PILLAR2_ID, pillar2DestinationId, result2); messageBus.sendMessage(resultPillar2); - AuditTrailResult result2Event = (AuditTrailResult)testEventHandler.waitForEvent(); - assertEquals(result2Event.getEventType(), OperationEvent.OperationEventType.COMPONENT_COMPLETE); + AuditTrailResult result2Event = (AuditTrailResult) testEventHandler.waitForEvent(); + assertEquals(OperationEvent.OperationEventType.COMPONENT_COMPLETE, result2Event.getEventType()); assertEquals(result2Event.getAuditTrailEvents(), result2); - assertEquals(testEventHandler.waitForEvent().getEventType(), - OperationEvent.OperationEventType.FAILED); + assertEquals(OperationEvent.OperationEventType.FAILED, + testEventHandler.waitForEvent().getEventType()); } - @Test(groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public void progressEventsTest() throws InterruptedException { addDescription("Tests that progress events are handled correctly."); @@ -319,69 +323,70 @@ public void progressEventsTest() throws InterruptedException { addStep("Retrieve all audit trails from the collection by calling with a null componentQueries array", "This should be interpreted as a request for all audit trails from all the collection settings " + - "defined contributors."); + "defined contributors."); client.getAuditTrails(collectionID, null, null, null, testEventHandler, null); IdentifyContributorsForGetAuditTrailsRequest identifyRequest = - collectionReceiver.waitForMessage(IdentifyContributorsForGetAuditTrailsRequest.class); - assertEquals(testEventHandler.waitForEvent().getEventType(), - OperationEvent.OperationEventType.IDENTIFY_REQUEST_SENT); + collectionReceiver.waitForMessage(IdentifyContributorsForGetAuditTrailsRequest.class); + assertEquals(OperationEvent.OperationEventType.IDENTIFY_REQUEST_SENT, + testEventHandler.waitForEvent().getEventType()); addStep("Send a identifyResponse from each of the two pillars", "COMPONENT_IDENTIFIED events and a IDENTIFICATION_COMPLETE event should be received." + - "Rights after this a REQUEST_SENT should be received and a GetAuditTrailsRequest should " + - "be sent to each pillar"); + "Rights after this a REQUEST_SENT should be received and a GetAuditTrailsRequest should " + + "be sent to each pillar"); IdentifyContributorsForGetAuditTrailsResponse responsePillar1 = - testMessageFactory.createIdentifyContributorsForGetAuditTrailsResponse(identifyRequest, - PILLAR1_ID, pillar1DestinationId); + testMessageFactory.createIdentifyContributorsForGetAuditTrailsResponse(identifyRequest, + PILLAR1_ID, pillar1DestinationId); messageBus.sendMessage(responsePillar1); - IdentifyContributorsForGetAuditTrailsResponse responsePillar2 = - testMessageFactory.createIdentifyContributorsForGetAuditTrailsResponse(identifyRequest, - PILLAR2_ID, pillar2DestinationId); + IdentifyContributorsForGetAuditTrailsResponse responsePillar2 = + testMessageFactory.createIdentifyContributorsForGetAuditTrailsResponse(identifyRequest, + PILLAR2_ID, pillar2DestinationId); messageBus.sendMessage(responsePillar2); - assertEquals(testEventHandler.waitForEvent().getEventType(), - OperationEvent.OperationEventType.COMPONENT_IDENTIFIED); - assertEquals(testEventHandler.waitForEvent().getEventType(), - OperationEvent.OperationEventType.COMPONENT_IDENTIFIED); - assertEquals(testEventHandler.waitForEvent().getEventType(), - OperationEvent.OperationEventType.IDENTIFICATION_COMPLETE); + assertEquals(OperationEvent.OperationEventType.COMPONENT_IDENTIFIED, + testEventHandler.waitForEvent().getEventType()); + assertEquals(OperationEvent.OperationEventType.COMPONENT_IDENTIFIED, + testEventHandler.waitForEvent().getEventType()); + assertEquals(OperationEvent.OperationEventType.IDENTIFICATION_COMPLETE, + testEventHandler.waitForEvent().getEventType()); - assertEquals(testEventHandler.waitForEvent().getEventType(), - OperationEvent.OperationEventType.REQUEST_SENT); + assertEquals(OperationEvent.OperationEventType.REQUEST_SENT, + testEventHandler.waitForEvent().getEventType()); GetAuditTrailsRequest requestPillar1 = pillar1Receiver.waitForMessage(GetAuditTrailsRequest.class); GetAuditTrailsRequest requestPillar2 = pillar2Receiver.waitForMessage(GetAuditTrailsRequest.class); addStep("Send a progress accepted response from pillar 1", - "A PROGRESS event should be generated."); + "A PROGRESS event should be generated."); GetAuditTrailsProgressResponse progressResponse1 = - testMessageFactory.createGetAuditTrailsProgressResponse(requestPillar1, - PILLAR1_ID, pillar1DestinationId); + testMessageFactory.createGetAuditTrailsProgressResponse(requestPillar1, + PILLAR1_ID, pillar1DestinationId); ResponseInfo progressInfo1 = new ResponseInfo(); progressInfo1.setResponseText("GetAuditTrails request accepted"); progressInfo1.setResponseCode(ResponseCode.OPERATION_ACCEPTED_PROGRESS); progressResponse1.setResponseInfo(progressInfo1); messageBus.sendMessage(progressResponse1); - assertEquals(testEventHandler.waitForEvent().getEventType(), - OperationEvent.OperationEventType.PROGRESS); + assertEquals(OperationEvent.OperationEventType.PROGRESS, + testEventHandler.waitForEvent().getEventType()); addStep("Send a general progress response from pillar 2", - "A PROGRESS event should be generated with the audit trail results."); + "A PROGRESS event should be generated with the audit trail results."); GetAuditTrailsProgressResponse progressResponse2 = - testMessageFactory.createGetAuditTrailsProgressResponse(requestPillar2, - PILLAR2_ID, pillar2DestinationId); + testMessageFactory.createGetAuditTrailsProgressResponse(requestPillar2, + PILLAR2_ID, pillar2DestinationId); ResponseInfo progressInfo2 = new ResponseInfo(); progressInfo2.setResponseText("Still progressing"); progressInfo2.setResponseCode(ResponseCode.OPERATION_PROGRESS); progressResponse2.setResponseInfo(progressInfo2); messageBus.sendMessage(progressResponse2); - assertEquals(testEventHandler.waitForEvent().getEventType(), - OperationEvent.OperationEventType.PROGRESS); + assertEquals(OperationEvent.OperationEventType.PROGRESS, + testEventHandler.waitForEvent().getEventType()); } - @Test(groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public void incompleteSetOfFinalResponsesTest() throws Exception { addDescription("Verify that the GetAuditTrail client works correct without receiving responses from all " + - "contributors."); + "contributors."); addStep("Configure 500 ms second timeout for the operation itself. " + "The default 2 contributors collection is used", ""); @@ -391,37 +396,38 @@ public void incompleteSetOfFinalResponsesTest() throws Exception { client.getAuditTrails(collectionID, null, null, null, testEventHandler, null); IdentifyContributorsForGetAuditTrailsRequest identifyRequest = - collectionReceiver.waitForMessage(IdentifyContributorsForGetAuditTrailsRequest.class); - assertEquals(testEventHandler.waitForEvent().getEventType(), - OperationEvent.OperationEventType.IDENTIFY_REQUEST_SENT); + collectionReceiver.waitForMessage(IdentifyContributorsForGetAuditTrailsRequest.class); + assertEquals(OperationEvent.OperationEventType.IDENTIFY_REQUEST_SENT, + testEventHandler.waitForEvent().getEventType()); addStep("Send a identifyResponse from each of the two pillars", "COMPONENT_IDENTIFIED events and a IDENTIFICATION_COMPLETE event should be received." + - "Rights after this a REQUEST_SENT should be received and a GetAuditTrails request should " + - "be sent to each pillar"); + "Rights after this a REQUEST_SENT should be received and a GetAuditTrails request should " + + "be sent to each pillar"); IdentifyContributorsForGetAuditTrailsResponse responsePillar1 = - testMessageFactory.createIdentifyContributorsForGetAuditTrailsResponse(identifyRequest, - PILLAR1_ID, pillar1DestinationId); + testMessageFactory.createIdentifyContributorsForGetAuditTrailsResponse(identifyRequest, + PILLAR1_ID, pillar1DestinationId); messageBus.sendMessage(responsePillar1); IdentifyContributorsForGetAuditTrailsResponse responsePillar2 = - testMessageFactory.createIdentifyContributorsForGetAuditTrailsResponse(identifyRequest, - PILLAR2_ID, pillar2DestinationId); + testMessageFactory.createIdentifyContributorsForGetAuditTrailsResponse(identifyRequest, + PILLAR2_ID, pillar2DestinationId); messageBus.sendMessage(responsePillar2); - assertEquals(testEventHandler.waitForEvent().getEventType(), - OperationEvent.OperationEventType.COMPONENT_IDENTIFIED); - assertEquals(testEventHandler.waitForEvent().getEventType(), - OperationEvent.OperationEventType.COMPONENT_IDENTIFIED); - assertEquals(testEventHandler.waitForEvent().getEventType(), - OperationEvent.OperationEventType.IDENTIFICATION_COMPLETE); + assertEquals(OperationEvent.OperationEventType.COMPONENT_IDENTIFIED, + testEventHandler.waitForEvent().getEventType()); + assertEquals(OperationEvent.OperationEventType.COMPONENT_IDENTIFIED, + testEventHandler.waitForEvent().getEventType()); + assertEquals(OperationEvent.OperationEventType.IDENTIFICATION_COMPLETE, + testEventHandler.waitForEvent().getEventType()); - assertEquals(testEventHandler.waitForEvent().getEventType(), - OperationEvent.OperationEventType.REQUEST_SENT); + assertEquals(OperationEvent.OperationEventType.REQUEST_SENT, + testEventHandler.waitForEvent().getEventType()); GetAuditTrailsRequest requestPillar1 = pillar1Receiver.waitForMessage(GetAuditTrailsRequest.class); assertNotNull(requestPillar1); } - @Test(groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public void noFinalResponsesTest() throws Exception { addDescription("Tests the the AuditTrailClient handles lack of Final Responses gracefully "); addStep("Set a 100 ms timeout for the operation.", ""); @@ -430,51 +436,52 @@ public void noFinalResponsesTest() throws Exception { AuditTrailClient client = createAuditTrailClient(); addStep("Make the client ask for all audit trails.", - "It should send a identify message"); + "It should send a identify message"); TestEventHandler testEventHandler = new TestEventHandler(testEventManager); client.getAuditTrails(collectionID, null, null, null, testEventHandler, null); IdentifyContributorsForGetAuditTrailsRequest identifyRequest = - collectionReceiver.waitForMessage(IdentifyContributorsForGetAuditTrailsRequest.class); - assertEquals(testEventHandler.waitForEvent().getEventType(), - OperationEvent.OperationEventType.IDENTIFY_REQUEST_SENT); + collectionReceiver.waitForMessage(IdentifyContributorsForGetAuditTrailsRequest.class); + assertEquals(OperationEvent.OperationEventType.IDENTIFY_REQUEST_SENT, + testEventHandler.waitForEvent().getEventType()); addStep("Send a identifyResponse from each of the two pillars", "COMPONENT_IDENTIFIED events and a IDENTIFICATION_COMPLETE event should be received." + - "Rights after this a REQUEST_SENT should be received."); + "Rights after this a REQUEST_SENT should be received."); IdentifyContributorsForGetAuditTrailsResponse responsePillar1 = - testMessageFactory.createIdentifyContributorsForGetAuditTrailsResponse(identifyRequest, - PILLAR1_ID, pillar1DestinationId); + testMessageFactory.createIdentifyContributorsForGetAuditTrailsResponse(identifyRequest, + PILLAR1_ID, pillar1DestinationId); messageBus.sendMessage(responsePillar1); IdentifyContributorsForGetAuditTrailsResponse responsePillar2 = - testMessageFactory.createIdentifyContributorsForGetAuditTrailsResponse(identifyRequest, - PILLAR2_ID, pillar2DestinationId); + testMessageFactory.createIdentifyContributorsForGetAuditTrailsResponse(identifyRequest, + PILLAR2_ID, pillar2DestinationId); messageBus.sendMessage(responsePillar2); - assertEquals(testEventHandler.waitForEvent().getEventType(), - OperationEvent.OperationEventType.COMPONENT_IDENTIFIED); - assertEquals(testEventHandler.waitForEvent().getEventType(), - OperationEvent.OperationEventType.COMPONENT_IDENTIFIED); - assertEquals(testEventHandler.waitForEvent().getEventType(), - OperationEvent.OperationEventType.IDENTIFICATION_COMPLETE); + assertEquals(OperationEvent.OperationEventType.COMPONENT_IDENTIFIED, + testEventHandler.waitForEvent().getEventType()); + assertEquals(OperationEvent.OperationEventType.COMPONENT_IDENTIFIED, + testEventHandler.waitForEvent().getEventType()); + assertEquals(OperationEvent.OperationEventType.IDENTIFICATION_COMPLETE, + testEventHandler.waitForEvent().getEventType()); - assertEquals(testEventHandler.waitForEvent().getEventType(), - OperationEvent.OperationEventType.REQUEST_SENT); + assertEquals(OperationEvent.OperationEventType.REQUEST_SENT, + testEventHandler.waitForEvent().getEventType()); addStep("Wait for 1 second", "An failed event should be received"); - assertEquals(testEventHandler.waitForEvent().getEventType(), - OperationEvent.OperationEventType.FAILED); + assertEquals(OperationEvent.OperationEventType.FAILED, + testEventHandler.waitForEvent().getEventType()); } /** * Creates a new test AuditTrailClient based on the supplied settings. - * + *

* Note that the normal way of creating client through the module factory would reuse components with settings from * previous tests. + * * @return A new AuditTrailClient(Wrapper). */ private AuditTrailClient createAuditTrailClient() { return new AuditTrailClientTestWrapper(new ConversationBasedAuditTrailClient( - settingsForCUT, conversationMediator, messageBus, settingsForTestClient.getComponentID()) , testEventManager); + settingsForCUT, conversationMediator, messageBus, settingsForTestClient.getComponentID()), testEventManager); } private ResultingAuditTrails createTestResultingAuditTrails(String componentID) { @@ -522,7 +529,7 @@ protected MessageResponse createIdentifyResponse( @Override protected MessageResponse createFinalResponse(MessageRequest request, String from, String to) { - MessageResponse response = testMessageFactory.createGetAuditTrailsFinalResponse( + MessageResponse response = testMessageFactory.createGetAuditTrailsFinalResponse( (GetAuditTrailsRequest) request, from, to, null); return response; } diff --git a/bitrepository-client/src/test/java/org/bitrepository/access/getaudittrails/AuditTrailClientTestWrapper.java b/bitrepository-client/src/test/java/org/bitrepository/access/getaudittrails/AuditTrailClientTestWrapper.java index 8b33472c0..cfe94ba35 100644 --- a/bitrepository-client/src/test/java/org/bitrepository/access/getaudittrails/AuditTrailClientTestWrapper.java +++ b/bitrepository-client/src/test/java/org/bitrepository/access/getaudittrails/AuditTrailClientTestWrapper.java @@ -27,8 +27,8 @@ import java.util.Arrays; public class AuditTrailClientTestWrapper implements AuditTrailClient { - private AuditTrailClient auditTrailClient; - private TestEventManager testEventManager; + private final AuditTrailClient auditTrailClient; + private final TestEventManager testEventManager; public AuditTrailClientTestWrapper(AuditTrailClient auditTrailClient, @@ -43,8 +43,7 @@ public void getAuditTrails(String collectionID, AuditTrailQuery[] componentQueri testEventManager.addStimuli( "Calling getAuditTrails(" + (componentQueries == null ? "null" : Arrays.asList(componentQueries)) + - ", " + fileID + ", " + - "" + urlForResult + ")"); + ", " + fileID + ", " + urlForResult + ")"); auditTrailClient.getAuditTrails(collectionID, componentQueries, fileID, urlForResult, eventHandler, auditTrailInformation); } diff --git a/bitrepository-client/src/test/java/org/bitrepository/access/getaudittrails/AuditTrailQueryTest.java b/bitrepository-client/src/test/java/org/bitrepository/access/getaudittrails/AuditTrailQueryTest.java index 769a7eeca..730adf578 100644 --- a/bitrepository-client/src/test/java/org/bitrepository/access/getaudittrails/AuditTrailQueryTest.java +++ b/bitrepository-client/src/test/java/org/bitrepository/access/getaudittrails/AuditTrailQueryTest.java @@ -5,16 +5,16 @@ * Copyright (C) 2010 - 2012 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% @@ -22,17 +22,21 @@ package org.bitrepository.access.getaudittrails; import org.jaccept.structure.ExtendedTestCase; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertNull; public class AuditTrailQueryTest extends ExtendedTestCase { private static final int DEFAULT_MAX_NUMBER_OF_RESULTS = 10000; String componentId = "componentId"; - - @Test(groups = {"regressiontest"}) + + @Test + @Tag("regressiontest") public void testNoSequenceNumbers() throws Exception { addDescription("Test that a AuditTrailQuery can be created without any sequence numbers."); AuditTrailQuery query = new AuditTrailQuery(componentId, null, null, DEFAULT_MAX_NUMBER_OF_RESULTS); @@ -41,32 +45,37 @@ public void testNoSequenceNumbers() throws Exception { assertNull(query.getMinSequenceNumber()); } - @Test(groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public void testOnlyMinSequenceNumber() throws Exception { addDescription("Test the creation of a AuditTrailQuery with only the minSequenceNumber"); Long minSeq = 1L; AuditTrailQuery query = new AuditTrailQuery(componentId, minSeq, null, DEFAULT_MAX_NUMBER_OF_RESULTS); assertEquals(query.getComponentID(), componentId); - assertEquals(query.getMinSequenceNumber(), minSeq); + assertEquals(minSeq, query.getMinSequenceNumber()); assertNull(query.getMaxSequenceNumber()); } - @Test(groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public void testBothSequenceNumberSuccess() throws Exception { addDescription("Test the creation of a AuditTrailQuery with both SequenceNumber, where max is larger than min."); Long minSeq = 1L; Long maxSeq = 2L; AuditTrailQuery query = new AuditTrailQuery(componentId, minSeq, maxSeq, DEFAULT_MAX_NUMBER_OF_RESULTS); assertEquals(query.getComponentID(), componentId); - assertEquals(query.getMinSequenceNumber(), minSeq); - assertEquals(query.getMaxSequenceNumber(), maxSeq); + assertEquals(minSeq, query.getMinSequenceNumber()); + assertEquals(maxSeq, query.getMaxSequenceNumber()); } - - @Test(groups = {"regressiontest"}, expectedExceptions=IllegalArgumentException.class) + + @Test + @Tag("regressiontest") public void testBothSequenceNumberFailure() throws Exception { - addDescription("Test the creation of a AuditTrailQuery with both SequenceNumber, where max is smalle than min."); - Long minSeq = 2L; - Long maxSeq = 1L; - new AuditTrailQuery(componentId, minSeq, maxSeq, DEFAULT_MAX_NUMBER_OF_RESULTS); + assertThrows(IllegalArgumentException.class, () -> { + addDescription("Test the creation of a AuditTrailQuery with both SequenceNumber, where max is smalle than min."); + Long minSeq = 2L; + Long maxSeq = 1L; + new AuditTrailQuery(componentId, minSeq, maxSeq, DEFAULT_MAX_NUMBER_OF_RESULTS); + }); } } diff --git a/bitrepository-client/src/test/java/org/bitrepository/access/getchecksums/GetChecksumsClientComponentTest.java b/bitrepository-client/src/test/java/org/bitrepository/access/getchecksums/GetChecksumsClientComponentTest.java index 0828000cd..30b055678 100644 --- a/bitrepository-client/src/test/java/org/bitrepository/access/getchecksums/GetChecksumsClientComponentTest.java +++ b/bitrepository-client/src/test/java/org/bitrepository/access/getchecksums/GetChecksumsClientComponentTest.java @@ -5,16 +5,16 @@ * Copyright (C) 2010 - 2012 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% @@ -23,16 +23,16 @@ * Copyright (C) 2010 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% @@ -57,9 +57,10 @@ import org.bitrepository.client.eventhandler.OperationEvent.OperationEventType; import org.bitrepository.common.utils.CalendarUtils; import org.bitrepository.protocol.bus.MessageReceiver; -import org.testng.Assert; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; import java.math.BigInteger; import java.net.URL; @@ -67,8 +68,6 @@ import java.util.Date; import java.util.LinkedList; -import static org.testng.Assert.assertEquals; - /** * Test class for the 'GetFileClient'. */ @@ -76,26 +75,28 @@ public class GetChecksumsClientComponentTest extends DefaultClientTest { private TestGetChecksumsMessageFactory messageFactory; private static final ChecksumSpecTYPE DEFAULT_CHECKSUM_SPECS; + static { DEFAULT_CHECKSUM_SPECS = new ChecksumSpecTYPE(); DEFAULT_CHECKSUM_SPECS.setChecksumSalt(null); DEFAULT_CHECKSUM_SPECS.setChecksumType(ChecksumType.MD5); } - @BeforeMethod (alwaysRun=true) + @BeforeEach public void beforeMethodSetup() throws Exception { messageFactory = new TestGetChecksumsMessageFactory(settingsForTestClient.getComponentID()); } - @Test(groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public void verifyGetChecksumsClientFromFactory() throws Exception { - Assert.assertTrue(AccessComponentFactory.getInstance().createGetChecksumsClient(settingsForCUT, securityManager, - settingsForTestClient.getComponentID()) instanceof ConversationBasedGetChecksumsClient, - "The default GetFileClient from the Access factory should be of the type '" + - ConversationBasedGetChecksumsClient.class.getName() + "'."); + Assertions.assertInstanceOf(ConversationBasedGetChecksumsClient.class, AccessComponentFactory.getInstance().createGetChecksumsClient(settingsForCUT, securityManager, + settingsForTestClient.getComponentID()), "The default GetFileClient from the Access factory should be of the type '" + + ConversationBasedGetChecksumsClient.class.getName() + "'."); } - @Test(groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public void getChecksumsFromSinglePillar() throws Exception { addDescription("Tests that the client can retrieve checksums from a single pillar."); @@ -107,16 +108,16 @@ public void getChecksumsFromSinglePillar() throws Exception { "should be generated."); Collection pillar1AsCollection = new LinkedList<>(); pillar1AsCollection.add(PILLAR1_ID); - getChecksumsClient.getChecksums(collectionID, new ContributorQuery[] {new ContributorQuery(PILLAR1_ID, null, - null, - null)}, + getChecksumsClient.getChecksums(collectionID, new ContributorQuery[]{new ContributorQuery(PILLAR1_ID, null, + null, + null)}, DEFAULT_FILE_ID, DEFAULT_CHECKSUM_SPECS, null, testEventHandler, "TEST-AUDIT"); IdentifyPillarsForGetChecksumsRequest receivedIdentifyRequestMessage = collectionReceiver.waitForMessage( IdentifyPillarsForGetChecksumsRequest.class); - assertEquals(receivedIdentifyRequestMessage.getFileIDs().getFileID(), DEFAULT_FILE_ID); - assertEquals(receivedIdentifyRequestMessage.getChecksumRequestForExistingFile(), DEFAULT_CHECKSUM_SPECS); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.IDENTIFY_REQUEST_SENT); + Assertions.assertEquals(DEFAULT_FILE_ID, receivedIdentifyRequestMessage.getFileIDs().getFileID()); + Assertions.assertEquals(DEFAULT_CHECKSUM_SPECS, receivedIdentifyRequestMessage.getChecksumRequestForExistingFile()); + Assertions.assertEquals(OperationEventType.IDENTIFY_REQUEST_SENT, testEventHandler.waitForEvent().getEventType()); addStep("Sends a response from pillar2.", "This should be ignored."); @@ -134,9 +135,9 @@ public void getChecksumsFromSinglePillar() throws Exception { messageBus.sendMessage(identifyResponse); GetChecksumsRequest receivedGetChecksumsRequest = pillar1Receiver.waitForMessage(GetChecksumsRequest.class); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.COMPONENT_IDENTIFIED); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.IDENTIFICATION_COMPLETE); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.REQUEST_SENT); + Assertions.assertEquals(OperationEventType.COMPONENT_IDENTIFIED, testEventHandler.waitForEvent().getEventType()); + Assertions.assertEquals(OperationEventType.IDENTIFICATION_COMPLETE, testEventHandler.waitForEvent().getEventType()); + Assertions.assertEquals(OperationEventType.REQUEST_SENT, testEventHandler.waitForEvent().getEventType()); addStep("Send a GetChecksumsFinalResponse to the client from pillar1", "A COMPONENT_COMPLETE event should be generated with the resulting checksum. Finally a COMPLETE event" + @@ -150,11 +151,12 @@ public void getChecksumsFromSinglePillar() throws Exception { messageBus.sendMessage(completeMsg); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.COMPONENT_COMPLETE); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.COMPLETE); + Assertions.assertEquals(OperationEventType.COMPONENT_COMPLETE, testEventHandler.waitForEvent().getEventType()); + Assertions.assertEquals(OperationEventType.COMPLETE, testEventHandler.waitForEvent().getEventType()); } - @Test(groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public void getChecksumsDeliveredAtUrl() throws Exception { addDescription("Tests the delivery of checksums from all pillars at a given URL."); @@ -175,7 +177,7 @@ public void getChecksumsDeliveredAtUrl() throws Exception { IdentifyPillarsForGetChecksumsRequest receivedIdentifyRequestMessage = null; receivedIdentifyRequestMessage = collectionReceiver.waitForMessage( IdentifyPillarsForGetChecksumsRequest.class); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.IDENTIFY_REQUEST_SENT); + Assertions.assertEquals(OperationEventType.IDENTIFY_REQUEST_SENT, testEventHandler.waitForEvent().getEventType()); addStep("The pillar sends a response to the identify message.", "The callback listener should notify of the response and the client should send a GetChecksumsRequest " @@ -189,11 +191,11 @@ public void getChecksumsDeliveredAtUrl() throws Exception { messageBus.sendMessage(identifyResponse2); GetChecksumsRequest receivedGetChecksumsRequest1 = pillar1Receiver.waitForMessage(GetChecksumsRequest.class); - for(int i = 0; i < settingsForCUT.getRepositorySettings().getCollections().getCollection().get(0).getPillarIDs().getPillarID().size(); i++) { - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.COMPONENT_IDENTIFIED); + for (int i = 0; i < settingsForCUT.getRepositorySettings().getCollections().getCollection().get(0).getPillarIDs().getPillarID().size(); i++) { + Assertions.assertEquals(OperationEventType.COMPONENT_IDENTIFIED, testEventHandler.waitForEvent().getEventType()); } - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.IDENTIFICATION_COMPLETE); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.REQUEST_SENT); + Assertions.assertEquals(OperationEventType.IDENTIFICATION_COMPLETE, testEventHandler.waitForEvent().getEventType()); + Assertions.assertEquals(OperationEventType.REQUEST_SENT, testEventHandler.waitForEvent().getEventType()); addStep("Sends a final response from each pillar", "The GetChecksumsClient notifies that the file is ready through the callback listener and the uploaded file is present."); @@ -203,17 +205,18 @@ public void getChecksumsDeliveredAtUrl() throws Exception { res.setResultAddress(receivedGetChecksumsRequest1.getResultAddress()); completeMsg1.setResultingChecksums(res); messageBus.sendMessage(completeMsg1); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.COMPONENT_COMPLETE); + Assertions.assertEquals(OperationEventType.COMPONENT_COMPLETE, testEventHandler.waitForEvent().getEventType()); GetChecksumsFinalResponse completeMsg2 = messageFactory.createGetChecksumsFinalResponse( receivedGetChecksumsRequest1, PILLAR2_ID, pillar2DestinationId); completeMsg2.setResultingChecksums(res); messageBus.sendMessage(completeMsg2); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.COMPONENT_COMPLETE); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.COMPLETE); + Assertions.assertEquals(OperationEventType.COMPONENT_COMPLETE, testEventHandler.waitForEvent().getEventType()); + Assertions.assertEquals(OperationEventType.COMPLETE, testEventHandler.waitForEvent().getEventType()); } - @Test(groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public void testNoSuchFile() throws Exception { addDescription("Testing how a request for a non-existing file is handled."); addStep("Setting up variables and such.", "Should be OK."); @@ -231,7 +234,7 @@ public void testNoSuchFile() throws Exception { IdentifyPillarsForGetChecksumsRequest receivedIdentifyRequestMessage = null; receivedIdentifyRequestMessage = collectionReceiver.waitForMessage(IdentifyPillarsForGetChecksumsRequest.class); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.IDENTIFY_REQUEST_SENT); + Assertions.assertEquals(OperationEventType.IDENTIFY_REQUEST_SENT, testEventHandler.waitForEvent().getEventType()); addStep("The pillar sends a response to the identify message.", "The callback listener should notify of the response and the client should send a GetChecksumsRequest " @@ -244,11 +247,11 @@ public void testNoSuchFile() throws Exception { messageBus.sendMessage(identifyResponse); receivedGetChecksumsRequest = pillar1Receiver.waitForMessage(GetChecksumsRequest.class); - for(int i = 0; i < settingsForCUT.getRepositorySettings().getCollections().getCollection().get(0).getPillarIDs().getPillarID().size(); i++) { - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.COMPONENT_IDENTIFIED); + for (int i = 0; i < settingsForCUT.getRepositorySettings().getCollections().getCollection().get(0).getPillarIDs().getPillarID().size(); i++) { + Assertions.assertEquals(OperationEventType.COMPONENT_IDENTIFIED, testEventHandler.waitForEvent().getEventType()); } - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.IDENTIFICATION_COMPLETE); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.REQUEST_SENT); + Assertions.assertEquals(OperationEventType.IDENTIFICATION_COMPLETE, testEventHandler.waitForEvent().getEventType()); + Assertions.assertEquals(OperationEventType.REQUEST_SENT, testEventHandler.waitForEvent().getEventType()); addStep("Send a error that the file cannot be found.", "Should trigger a 'event failed'."); GetChecksumsFinalResponse completeMsg = messageFactory.createGetChecksumsFinalResponse( @@ -262,12 +265,13 @@ public void testNoSuchFile() throws Exception { messageBus.sendMessage(completeMsg); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.COMPONENT_FAILED); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.FAILED); + Assertions.assertEquals(OperationEventType.COMPONENT_FAILED, testEventHandler.waitForEvent().getEventType()); + Assertions.assertEquals(OperationEventType.FAILED, testEventHandler.waitForEvent().getEventType()); } - @Test(groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public void testPaging() throws Exception { addDescription("Tests the GetChecksums client correctly handles functionality for limiting results, either by " + "timestamp or result count."); @@ -276,8 +280,8 @@ public void testPaging() throws Exception { addStep("Request checksums from with MinTimestamp, MaxTimestamp, MaxNumberOfResults set for both pillars .", "A IdentifyPillarsForGetChecksumsRequest should be sent."); Date timestamp3 = new Date(); - Date timestamp2 = new Date(timestamp3.getTime() - 100); - Date timestamp1 = new Date(timestamp3.getTime() - 1000); + Date timestamp2 = new Date(timestamp3.getTime() - 100); + Date timestamp1 = new Date(timestamp3.getTime() - 1000); ContributorQuery query1 = new ContributorQuery(PILLAR1_ID, timestamp1, timestamp2, 1); ContributorQuery query2 = new ContributorQuery(PILLAR2_ID, timestamp2, timestamp3, 2); getChecksumsClient.getChecksums(collectionID, new ContributorQuery[]{query1, query2}, null, null, null, @@ -295,29 +299,30 @@ public void testPaging() throws Exception { receivedIdentifyRequestMessage, PILLAR2_ID, pillar2DestinationId)); GetChecksumsRequest receivedGetChecksumsRequest1 = pillar1Receiver.waitForMessage(GetChecksumsRequest.class); - assertEquals(receivedGetChecksumsRequest1.getMinTimestamp(), + Assertions.assertEquals(receivedGetChecksumsRequest1.getMinTimestamp(), CalendarUtils.getXmlGregorianCalendar(query1.getMinTimestamp()), "Unexpected MinTimestamp in GetChecksumsRequest to pillar1."); - assertEquals(receivedGetChecksumsRequest1.getMaxTimestamp(), + Assertions.assertEquals(receivedGetChecksumsRequest1.getMaxTimestamp(), CalendarUtils.getXmlGregorianCalendar(query1.getMaxTimestamp()), "Unexpected MaxTimestamp in GetChecksumsRequest to pillar1."); - assertEquals(receivedGetChecksumsRequest1.getMaxNumberOfResults(), + Assertions.assertEquals(receivedGetChecksumsRequest1.getMaxNumberOfResults(), BigInteger.valueOf(query1.getMaxNumberOfResults()), "Unexpected MaxNumberOfResults in GetChecksumsRequest to pillar1."); GetChecksumsRequest receivedGetChecksumsRequest2 = pillar2Receiver.waitForMessage(GetChecksumsRequest.class); - assertEquals(receivedGetChecksumsRequest2.getMinTimestamp(), + Assertions.assertEquals(receivedGetChecksumsRequest2.getMinTimestamp(), CalendarUtils.getXmlGregorianCalendar((query2.getMinTimestamp())), "Unexpected MinTimestamp in GetChecksumsRequest to pillar2."); - assertEquals(receivedGetChecksumsRequest2.getMaxTimestamp(), + Assertions.assertEquals(receivedGetChecksumsRequest2.getMaxTimestamp(), CalendarUtils.getXmlGregorianCalendar(query2.getMaxTimestamp()), "Unexpected MaxTimestamp in GetChecksumsRequest to pillar2."); - assertEquals(receivedGetChecksumsRequest2.getMaxNumberOfResults(), + Assertions.assertEquals(receivedGetChecksumsRequest2.getMaxNumberOfResults(), BigInteger.valueOf(query2.getMaxNumberOfResults()), "Unexpected MaxNumberOfResults in GetChecksumsRequest to pillar2."); } - @Test(groups={"regressiontest"}) + @Test + @Tag("regressiontest") public void getChecksumsFromOtherCollection() throws Exception { addDescription("Tests the getChecksums client will correctly try to get from a second collection if required"); addFixture("Configure collection1 to contain both pillars and collection 2 to only contain pillar2"); @@ -327,7 +332,7 @@ public void getChecksumsFromOtherCollection() throws Exception { settingsForCUT.getRepositorySettings().getCollections().getCollection().get(0).getPillarIDs().getPillarID().add(PILLAR2_ID); settingsForCUT.getRepositorySettings().getCollections().getCollection().get(1).getPillarIDs().getPillarID().clear(); settingsForCUT.getRepositorySettings().getCollections().getCollection().get(1).getPillarIDs().getPillarID().add(PILLAR2_ID); - String otherCollection = settingsForCUT.getRepositorySettings().getCollections().getCollection().get(1).getID(); + String otherCollection = settingsForCUT.getRepositorySettings().getCollections().getCollection().get(1).getID(); TestEventHandler testEventHandler = new TestEventHandler(testEventManager); GetChecksumsClient client = createGetChecksumsClient(); @@ -335,37 +340,38 @@ public void getChecksumsFromOtherCollection() throws Exception { "A identification request should be dispatched."); client.getChecksums(otherCollection, null, null, null, null, testEventHandler, null); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.IDENTIFY_REQUEST_SENT); + Assertions.assertEquals(OperationEventType.IDENTIFY_REQUEST_SENT, testEventHandler.waitForEvent().getEventType()); IdentifyPillarsForGetChecksumsRequest receivedIdentifyRequestMessage = collectionReceiver.waitForMessage(IdentifyPillarsForGetChecksumsRequest.class); - assertEquals(receivedIdentifyRequestMessage.getCollectionID(), otherCollection); + Assertions.assertEquals(receivedIdentifyRequestMessage.getCollectionID(), otherCollection); addStep("Send an identification response from pillar2.", "An COMPONENT_IDENTIFIED event should be generate folled by a IDENTIFICATION_COMPLETE and a " + "REQUEST_SENT. A GetChecksumsFileRequest should be sent to pillar2"); messageBus.sendMessage(messageFactory.createIdentifyPillarsForGetChecksumsResponse( receivedIdentifyRequestMessage, PILLAR2_ID, pillar2DestinationId)); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.COMPONENT_IDENTIFIED); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.IDENTIFICATION_COMPLETE); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.REQUEST_SENT); + Assertions.assertEquals(OperationEventType.COMPONENT_IDENTIFIED, testEventHandler.waitForEvent().getEventType()); + Assertions.assertEquals(OperationEventType.IDENTIFICATION_COMPLETE, testEventHandler.waitForEvent().getEventType()); + Assertions.assertEquals(OperationEventType.REQUEST_SENT, testEventHandler.waitForEvent().getEventType()); GetChecksumsRequest receivedRequest = pillar2Receiver.waitForMessage(GetChecksumsRequest.class); - assertEquals(receivedRequest.getCollectionID(), otherCollection); + Assertions.assertEquals(receivedRequest.getCollectionID(), otherCollection); addStep("Send a complete event from the pillar", "The client generates " + "a COMPONENT_COMPLETE, followed by a COMPLETE event."); GetChecksumsFinalResponse putFileFinalResponse1 = messageFactory.createGetChecksumsFinalResponse( receivedRequest, PILLAR2_ID, pillar2DestinationId); messageBus.sendMessage(putFileFinalResponse1); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.COMPONENT_COMPLETE); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.COMPLETE); + Assertions.assertEquals(OperationEventType.COMPONENT_COMPLETE, testEventHandler.waitForEvent().getEventType()); + Assertions.assertEquals(OperationEventType.COMPLETE, testEventHandler.waitForEvent().getEventType()); } /** - * Creates a new test GetCheckSumsClient based on the supplied settings. - * + * Creates a new test GetCheckSumsClient based on the supplied settings. + *

* Note that the normal way of creating client through the module factory would reuse components with settings from * previous tests. + * * @return A new GetFileClient(Wrapper). */ private GetChecksumsClient createGetChecksumsClient() { @@ -383,7 +389,7 @@ protected MessageResponse createIdentifyResponse(MessageRequest identifyRequest, @Override protected MessageResponse createFinalResponse(MessageRequest request, String from, String to) { - MessageResponse response = messageFactory.createGetChecksumsFinalResponse( + MessageResponse response = messageFactory.createGetChecksumsFinalResponse( (GetChecksumsRequest) request, from, to); return response; } diff --git a/bitrepository-client/src/test/java/org/bitrepository/access/getchecksums/GetChecksumsClientTestWrapper.java b/bitrepository-client/src/test/java/org/bitrepository/access/getchecksums/GetChecksumsClientTestWrapper.java index e00e0aae4..b474699a2 100644 --- a/bitrepository-client/src/test/java/org/bitrepository/access/getchecksums/GetChecksumsClientTestWrapper.java +++ b/bitrepository-client/src/test/java/org/bitrepository/access/getchecksums/GetChecksumsClientTestWrapper.java @@ -36,8 +36,8 @@ * Wraps the GetFileClient adding test event logging and functionality for handling blocking calls. */ public class GetChecksumsClientTestWrapper implements GetChecksumsClient { - private GetChecksumsClient getChecksumsClientInstance; - private TestEventManager testEventManager; + private final GetChecksumsClient getChecksumsClientInstance; + private final TestEventManager testEventManager; public GetChecksumsClientTestWrapper(GetChecksumsClient createGetChecksumsClient, TestEventManager testEventManager) { diff --git a/bitrepository-client/src/test/java/org/bitrepository/access/getfile/AbstractGetFileClientTest.java b/bitrepository-client/src/test/java/org/bitrepository/access/getfile/AbstractGetFileClientTest.java index f02b1f14f..af7d6c969 100644 --- a/bitrepository-client/src/test/java/org/bitrepository/access/getfile/AbstractGetFileClientTest.java +++ b/bitrepository-client/src/test/java/org/bitrepository/access/getfile/AbstractGetFileClientTest.java @@ -40,7 +40,8 @@ package org.bitrepository.access.getfile; import org.bitrepository.client.DefaultFixtureClientTest; -import org.testng.annotations.BeforeMethod; +import org.junit.jupiter.api.BeforeEach; + /** * Runs the DefaultFixtureClient test using a TestGetFileMessageFactory as the message factory. @@ -49,7 +50,7 @@ public abstract class AbstractGetFileClientTest extends DefaultFixtureClientTest { protected TestGetFileMessageFactory messageFactory; - @BeforeMethod(alwaysRun = true) + @BeforeEach public void beforeMethodSetup() throws Exception { messageFactory = new TestGetFileMessageFactory(settingsForTestClient.getComponentID()); } diff --git a/bitrepository-client/src/test/java/org/bitrepository/access/getfile/GetFileClientComponentTest.java b/bitrepository-client/src/test/java/org/bitrepository/access/getfile/GetFileClientComponentTest.java index 4d2f65834..b1ec002b2 100644 --- a/bitrepository-client/src/test/java/org/bitrepository/access/getfile/GetFileClientComponentTest.java +++ b/bitrepository-client/src/test/java/org/bitrepository/access/getfile/GetFileClientComponentTest.java @@ -1,23 +1,23 @@ /* * #%L * bitrepository-access-client - * + * * $Id$ * $HeadURL$ * %% * Copyright (C) 2010 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% @@ -38,16 +38,18 @@ import org.bitrepository.client.eventhandler.ContributorEvent; import org.bitrepository.client.eventhandler.IdentificationCompleteEvent; import org.bitrepository.client.eventhandler.OperationEvent.OperationEventType; -import org.testng.Assert; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; import javax.xml.datatype.DatatypeConfigurationException; import javax.xml.datatype.DatatypeFactory; import java.math.BigInteger; import java.net.URL; -import static org.testng.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; + /** * Test class for the 'GetFileClient'. @@ -58,21 +60,21 @@ public class GetFileClientComponentTest extends AbstractGetFileClientTest { private DatatypeFactory datatypeFactory; - @BeforeMethod(alwaysRun = true) + @BeforeEach public void setUpFactory() throws DatatypeConfigurationException { datatypeFactory = DatatypeFactory.newInstance(); } - @Test(groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public void verifyGetFileClientFromFactory() { - Assert.assertTrue(AccessComponentFactory.getInstance().createGetFileClient( - settingsForCUT, securityManager, settingsForTestClient.getComponentID()) - instanceof ConversationBasedGetFileClient, - "The default GetFileClient from the Access factory should be of the type '" + - ConversationBasedGetFileClient.class.getName() + "'."); + Assertions.assertInstanceOf(ConversationBasedGetFileClient.class, AccessComponentFactory.getInstance().createGetFileClient( + settingsForCUT, securityManager, settingsForTestClient.getComponentID()), "The default GetFileClient from the Access factory should be of the type '" + + ConversationBasedGetFileClient.class.getName() + "'."); } - @Test(groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public void getFileFromSpecificPillar() throws Exception { addDescription("Tests that the GetClient client works correctly when requesting a file from a specific pillar"); @@ -86,14 +88,14 @@ public void getFileFromSpecificPillar() throws Exception { PILLAR2_ID, testEventHandler, auditTrailInformation); IdentifyPillarsForGetFileRequest receivedIdentifyRequestMessage = collectionReceiver.waitForMessage(IdentifyPillarsForGetFileRequest.class); assertEquals(receivedIdentifyRequestMessage.getCollectionID(), collectionID); - Assert.assertNotNull(receivedIdentifyRequestMessage.getCorrelationID()); + Assertions.assertNotNull(receivedIdentifyRequestMessage.getCorrelationID()); assertEquals(receivedIdentifyRequestMessage.getReplyTo(), settingsForCUT.getReceiverDestinationID()); - assertEquals(receivedIdentifyRequestMessage.getFileID(), DEFAULT_FILE_ID); + assertEquals(DEFAULT_FILE_ID, receivedIdentifyRequestMessage.getFileID()); assertEquals(receivedIdentifyRequestMessage.getFrom(), settingsForTestClient.getComponentID()); assertEquals(receivedIdentifyRequestMessage.getDestination(), settingsForTestClient.getCollectionDestination()); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.IDENTIFY_REQUEST_SENT); + assertEquals(OperationEventType.IDENTIFY_REQUEST_SENT, testEventHandler.waitForEvent().getEventType()); - addStep("Send a response from pillar1", "Should be ignored, eg. nothing should happen" ); + addStep("Send a response from pillar1", "Should be ignored, eg. nothing should happen"); IdentifyPillarsForGetFileResponse identifyResponse1 = messageFactory.createIdentifyPillarsForGetFileResponse( receivedIdentifyRequestMessage, PILLAR1_ID, pillar1DestinationId); messageBus.sendMessage(identifyResponse1); @@ -106,29 +108,29 @@ public void getFileFromSpecificPillar() throws Exception { IdentifyPillarsForGetFileResponse identifyResponse2 = messageFactory.createIdentifyPillarsForGetFileResponse( receivedIdentifyRequestMessage, PILLAR2_ID, pillar2DestinationId); messageBus.sendMessage(identifyResponse2); - ContributorEvent componentIdentifiedEvent2 = (ContributorEvent)testEventHandler.waitForEvent(); - assertEquals(componentIdentifiedEvent2.getEventType(), OperationEventType.COMPONENT_IDENTIFIED); - assertEquals(componentIdentifiedEvent2.getContributorID(), PILLAR2_ID); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.IDENTIFICATION_COMPLETE); + ContributorEvent componentIdentifiedEvent2 = (ContributorEvent) testEventHandler.waitForEvent(); + assertEquals(OperationEventType.COMPONENT_IDENTIFIED, componentIdentifiedEvent2.getEventType()); + assertEquals(PILLAR2_ID, componentIdentifiedEvent2.getContributorID()); + assertEquals(OperationEventType.IDENTIFICATION_COMPLETE, testEventHandler.waitForEvent().getEventType()); GetFileRequest receivedGetFileRequest = pillar2Receiver.waitForMessage(GetFileRequest.class); assertEquals(receivedGetFileRequest.getCollectionID(), collectionID); assertEquals(receivedGetFileRequest.getCorrelationID(), identifyResponse2.getCorrelationID()); assertEquals(receivedGetFileRequest.getReplyTo(), settingsForCUT.getReceiverDestinationID()); - assertEquals(receivedGetFileRequest.getFileID(), DEFAULT_FILE_ID); - assertEquals(receivedGetFileRequest.getAuditTrailInformation(), auditTrailInformation); + assertEquals(DEFAULT_FILE_ID, receivedGetFileRequest.getFileID()); + assertEquals(auditTrailInformation, receivedGetFileRequest.getAuditTrailInformation()); assertEquals(receivedGetFileRequest.getFrom(), settingsForTestClient.getComponentID()); assertEquals(receivedGetFileRequest.getDestination(), pillar2DestinationId); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.REQUEST_SENT); + assertEquals(OperationEventType.REQUEST_SENT, testEventHandler.waitForEvent().getEventType()); addStep("Send a GetFileProgressResponse.", "The client should generating a PROGRESS event."); GetFileProgressResponse getFileProgressResponse = messageFactory.createGetFileProgressResponse( receivedGetFileRequest, PILLAR2_ID, pillar2DestinationId); messageBus.sendMessage(getFileProgressResponse); - ContributorEvent componentProgressEvent2 = (ContributorEvent)testEventHandler.waitForEvent(); - assertEquals(componentProgressEvent2.getEventType(), OperationEventType.PROGRESS); - assertEquals(componentProgressEvent2.getContributorID(), PILLAR2_ID); + ContributorEvent componentProgressEvent2 = (ContributorEvent) testEventHandler.waitForEvent(); + assertEquals(OperationEventType.PROGRESS, componentProgressEvent2.getEventType()); + assertEquals(PILLAR2_ID, componentProgressEvent2.getContributorID()); addStep("Send a GetFileFinalResponse.", "The GetFileClient generates a COMPONENT_COMPLETE event followed by a COMPLETE event."); @@ -136,13 +138,14 @@ public void getFileFromSpecificPillar() throws Exception { GetFileFinalResponse completeMsg = messageFactory.createGetFileFinalResponse( receivedGetFileRequest, PILLAR2_ID, pillar2DestinationId); messageBus.sendMessage(completeMsg); - ContributorEvent componentCompleteEvent2 = (ContributorEvent)testEventHandler.waitForEvent(); - assertEquals(componentCompleteEvent2.getEventType(), OperationEventType.COMPONENT_COMPLETE); - assertEquals(componentCompleteEvent2.getContributorID(), PILLAR2_ID); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.COMPLETE); + ContributorEvent componentCompleteEvent2 = (ContributorEvent) testEventHandler.waitForEvent(); + assertEquals(OperationEventType.COMPONENT_COMPLETE, componentCompleteEvent2.getEventType()); + assertEquals(PILLAR2_ID, componentCompleteEvent2.getContributorID()); + assertEquals(OperationEventType.COMPLETE, testEventHandler.waitForEvent().getEventType()); } - @Test(groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public void getFileFromSpecificPillarWithFilePart() throws Exception { addDescription("Tests that the GetClient client works for a single pillar " + "participates. Also validate, that the 'FilePart' can be used."); @@ -166,7 +169,7 @@ public void getFileFromSpecificPillarWithFilePart() throws Exception { chosenPillar, testEventHandler, null); IdentifyPillarsForGetFileRequest receivedIdentifyRequestMessage = collectionReceiver.waitForMessage(IdentifyPillarsForGetFileRequest.class); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.IDENTIFY_REQUEST_SENT); + assertEquals(OperationEventType.IDENTIFY_REQUEST_SENT, testEventHandler.waitForEvent().getEventType()); addStep("The pillar sends a response to the identify message.", "The callback listener should notify of the response and the client should send a GetFileRequest message to " + @@ -177,11 +180,11 @@ public void getFileFromSpecificPillarWithFilePart() throws Exception { messageBus.sendMessage(identifyResponse); GetFileRequest receivedGetFileRequest = pillar1Receiver.waitForMessage(GetFileRequest.class); - for(int i = 0; i < settingsForCUT.getRepositorySettings().getCollections().getCollection().get(0).getPillarIDs().getPillarID().size(); i++) { - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.COMPONENT_IDENTIFIED); + for (int i = 0; i < settingsForCUT.getRepositorySettings().getCollections().getCollection().get(0).getPillarIDs().getPillarID().size(); i++) { + assertEquals(OperationEventType.COMPONENT_IDENTIFIED, testEventHandler.waitForEvent().getEventType()); } - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.IDENTIFICATION_COMPLETE); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.REQUEST_SENT); + assertEquals(OperationEventType.IDENTIFICATION_COMPLETE, testEventHandler.waitForEvent().getEventType()); + assertEquals(OperationEventType.REQUEST_SENT, testEventHandler.waitForEvent().getEventType()); addStep("The pillar sends a getFile response to the GetClient.", "The GetClient should notify about the response through the callback interface."); @@ -189,7 +192,7 @@ public void getFileFromSpecificPillarWithFilePart() throws Exception { receivedGetFileRequest, chosenPillar, pillar1DestinationId); messageBus.sendMessage(getFileProgressResponse); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.PROGRESS); + assertEquals(OperationEventType.PROGRESS, testEventHandler.waitForEvent().getEventType()); addStep("The file is uploaded to the indicated url and the pillar sends a final response upload message", "The GetFileClient notifies that the file is ready through the callback listener and the uploaded " + @@ -199,11 +202,12 @@ public void getFileFromSpecificPillarWithFilePart() throws Exception { receivedGetFileRequest, chosenPillar, pillar1DestinationId); messageBus.sendMessage(completeMsg); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.COMPONENT_COMPLETE); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.COMPLETE); + assertEquals(OperationEventType.COMPONENT_COMPLETE, testEventHandler.waitForEvent().getEventType()); + assertEquals(OperationEventType.COMPLETE, testEventHandler.waitForEvent().getEventType()); } - @Test(groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public void chooseFastestPillarGetFileClient() throws Exception { addDescription("Set the GetClient to retrieve a file as fast as " + "possible, where it has to choose between to pillars with " @@ -231,7 +235,7 @@ public void chooseFastestPillarGetFileClient() throws Exception { testEventHandler, null); IdentifyPillarsForGetFileRequest receivedIdentifyRequestMessage = collectionReceiver.waitForMessage(IdentifyPillarsForGetFileRequest.class); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.IDENTIFY_REQUEST_SENT); + assertEquals(OperationEventType.IDENTIFY_REQUEST_SENT, testEventHandler.waitForEvent().getEventType()); addStep("Three pillars send responses. First an average timeToDeliver, then a fast timeToDeliver and last a" + " slow timeToDeliver.", "The client should send a getFileRequest to the fast pillar. " + @@ -262,17 +266,18 @@ public void chooseFastestPillarGetFileClient() throws Exception { slowReply.setTimeToDeliver(slowTime); messageBus.sendMessage(slowReply); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.COMPONENT_IDENTIFIED); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.COMPONENT_IDENTIFIED); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.COMPONENT_IDENTIFIED); + assertEquals(OperationEventType.COMPONENT_IDENTIFIED, testEventHandler.waitForEvent().getEventType()); + assertEquals(OperationEventType.COMPONENT_IDENTIFIED, testEventHandler.waitForEvent().getEventType()); + assertEquals(OperationEventType.COMPONENT_IDENTIFIED, testEventHandler.waitForEvent().getEventType()); IdentificationCompleteEvent event = (IdentificationCompleteEvent) testEventHandler.waitForEvent(); - assertEquals(event.getEventType(), OperationEventType.IDENTIFICATION_COMPLETE); - assertEquals(event.getContributorIDs().get(0), fastPillarID); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.REQUEST_SENT); + assertEquals(OperationEventType.IDENTIFICATION_COMPLETE, event.getEventType()); + assertEquals(fastPillarID, event.getContributorIDs().get(0)); + assertEquals(OperationEventType.REQUEST_SENT, testEventHandler.waitForEvent().getEventType()); pillar1Receiver.waitForMessage(GetFileRequest.class); } - @Test(groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public void getFileClientWithIdentifyTimeout() throws Exception { addDescription("Verify that the GetFile works correct without receiving responses from all pillars."); addFixture("Set the identification timeout to 500ms"); @@ -289,7 +294,7 @@ public void getFileClientWithIdentifyTimeout() throws Exception { testEventHandler, null); IdentifyPillarsForGetFileRequest receivedIdentifyRequestMessage = collectionReceiver.waitForMessage(IdentifyPillarsForGetFileRequest.class); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.IDENTIFY_REQUEST_SENT); + assertEquals(OperationEventType.IDENTIFY_REQUEST_SENT, testEventHandler.waitForEvent().getEventType()); addStep("Send an identification response from pillar1.", "A COMPONENT_IDENTIFIED event should be generated."); @@ -297,30 +302,31 @@ public void getFileClientWithIdentifyTimeout() throws Exception { IdentifyPillarsForGetFileResponse identificationResponse1 = messageFactory.createIdentifyPillarsForGetFileResponse( receivedIdentifyRequestMessage, PILLAR1_ID, pillar1DestinationId); messageBus.sendMessage(identificationResponse1); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.COMPONENT_IDENTIFIED); + assertEquals(OperationEventType.COMPONENT_IDENTIFIED, testEventHandler.waitForEvent().getEventType()); addStep("Wait 1 second.", "A IDENTIFY_TIMEOUT event should be generated, followed by an IDENTIFICATION_COMPLETE."); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.IDENTIFY_TIMEOUT); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.COMPONENT_FAILED); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.IDENTIFICATION_COMPLETE); + assertEquals(OperationEventType.IDENTIFY_TIMEOUT, testEventHandler.waitForEvent().getEventType()); + assertEquals(OperationEventType.COMPONENT_FAILED, testEventHandler.waitForEvent().getEventType()); + assertEquals(OperationEventType.IDENTIFICATION_COMPLETE, testEventHandler.waitForEvent().getEventType()); addStep("Verify that the client continues to the performing phase.", "A REQUEST_SENT event should be generated and a GetFileRequest should be sent to pillar1."); GetFileRequest getFileRequest = pillar1Receiver.waitForMessage(GetFileRequest.class); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.REQUEST_SENT); + assertEquals(OperationEventType.REQUEST_SENT, testEventHandler.waitForEvent().getEventType()); addStep("Send a final response upload message", "A COMPONENT_COMPLETE event should be generated followed by at COMPLETE event."); GetFileFinalResponse completeMsg = messageFactory.createGetFileFinalResponse( getFileRequest, PILLAR1_ID, pillar1DestinationId); messageBus.sendMessage(completeMsg); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.COMPONENT_COMPLETE); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.COMPLETE); + assertEquals(OperationEventType.COMPONENT_COMPLETE, testEventHandler.waitForEvent().getEventType()); + assertEquals(OperationEventType.COMPLETE, testEventHandler.waitForEvent().getEventType()); } - @Test(groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public void noIdentifyResponse() throws Exception { addDescription("Tests the the GetFileClient handles lack of IdentifyPillarResponses gracefully "); addStep("Set a 500 ms timeout for identifying pillar.", ""); @@ -336,16 +342,17 @@ public void noIdentifyResponse() throws Exception { httpServerConfiguration.getURL(DEFAULT_FILE_ID), testEventHandler, null); collectionReceiver.waitForMessage(IdentifyPillarsForGetFileRequest.class); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.IDENTIFY_REQUEST_SENT); + assertEquals(OperationEventType.IDENTIFY_REQUEST_SENT, testEventHandler.waitForEvent().getEventType()); addStep("Wait for 1 seconds", "An IdentifyPillarTimeout event should be received followed by a FAILED event"); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.IDENTIFY_TIMEOUT); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.COMPONENT_FAILED); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.COMPONENT_FAILED); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.FAILED); + assertEquals(OperationEventType.IDENTIFY_TIMEOUT, testEventHandler.waitForEvent().getEventType()); + assertEquals(OperationEventType.COMPONENT_FAILED, testEventHandler.waitForEvent().getEventType()); + assertEquals(OperationEventType.COMPONENT_FAILED, testEventHandler.waitForEvent().getEventType()); + assertEquals(OperationEventType.FAILED, testEventHandler.waitForEvent().getEventType()); } - @Test(groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public void conversationTimeout() throws Exception { addDescription("Tests the the GetFileClient handles lack of IdentifyPillarResponses gracefully "); addStep("Set the number of pillars to 100ms and a 300 ms timeout for the conversation.", ""); @@ -364,7 +371,7 @@ public void conversationTimeout() throws Exception { PILLAR1_ID, testEventHandler, null); IdentifyPillarsForGetFileRequest receivedIdentifyRequestMessage = collectionReceiver.waitForMessage(IdentifyPillarsForGetFileRequest.class); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.IDENTIFY_REQUEST_SENT); + assertEquals(OperationEventType.IDENTIFY_REQUEST_SENT, testEventHandler.waitForEvent().getEventType()); addStep("The pillar sends a response to the identify message.", "The callback listener should notify of the response and the client should send a GetFileRequest message to " + @@ -376,15 +383,16 @@ public void conversationTimeout() throws Exception { messageBus.sendMessage(identifyResponse); pillar1Receiver.waitForMessage(GetFileRequest.class); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.COMPONENT_IDENTIFIED); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.IDENTIFICATION_COMPLETE); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.REQUEST_SENT); + assertEquals(OperationEventType.COMPONENT_IDENTIFIED, testEventHandler.waitForEvent().getEventType()); + assertEquals(OperationEventType.IDENTIFICATION_COMPLETE, testEventHandler.waitForEvent().getEventType()); + assertEquals(OperationEventType.REQUEST_SENT, testEventHandler.waitForEvent().getEventType()); addStep("Wait for 1 second", "An failed event should be generated followed by a FAILED event"); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.FAILED); + assertEquals(OperationEventType.FAILED, testEventHandler.waitForEvent().getEventType()); } - @Test(groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public void testNoSuchFileSpecificPillar() throws Exception { addDescription("Testing how a request for a non-existing file is handled on a specific pillar request."); addStep("Define 1 pillar.", ""); @@ -402,7 +410,7 @@ public void testNoSuchFileSpecificPillar() throws Exception { null); IdentifyPillarsForGetFileRequest receivedIdentifyRequestMessage = collectionReceiver.waitForMessage(IdentifyPillarsForGetFileRequest.class); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.IDENTIFY_REQUEST_SENT); + assertEquals(OperationEventType.IDENTIFY_REQUEST_SENT, testEventHandler.waitForEvent().getEventType()); addStep("The specified pillars sends a FILE_NOT_FOUND response", "The client should generate 1 PillarIdentified event followed by an operation failed event."); @@ -413,11 +421,12 @@ public void testNoSuchFileSpecificPillar() throws Exception { receivedIdentifyRequestMessage.getFileID() + " not present on this pillar " + PILLAR1_ID); messageBus.sendMessage(pillar1Response); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.COMPONENT_FAILED); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.FAILED); + assertEquals(OperationEventType.COMPONENT_FAILED, testEventHandler.waitForEvent().getEventType()); + assertEquals(OperationEventType.FAILED, testEventHandler.waitForEvent().getEventType()); } - @Test(groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public void testNoSuchFileMultiplePillars() throws Exception { addDescription("Testing how a request for a non-existing file is handled when all pillars miss the file."); @@ -433,7 +442,7 @@ public void testNoSuchFileMultiplePillars() throws Exception { client.getFileFromFastestPillar(collectionID, fileName, NO_FILE_PART, url, testEventHandler, null); IdentifyPillarsForGetFileRequest receivedIdentifyRequestMessage = collectionReceiver.waitForMessage(IdentifyPillarsForGetFileRequest.class); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.IDENTIFY_REQUEST_SENT); + assertEquals(OperationEventType.IDENTIFY_REQUEST_SENT, testEventHandler.waitForEvent().getEventType()); addStep("Both pillars sends a FILE_NOT_FOUND response", "The client should generate 2 PillarIdentified events followed by a Failed event."); @@ -449,15 +458,16 @@ public void testNoSuchFileMultiplePillars() throws Exception { receivedIdentifyRequestMessage, PILLAR2_ID, pillar2DestinationId); pillar2Response.getResponseInfo().setResponseCode(ResponseCode.FILE_NOT_FOUND_FAILURE); pillar2Response.getResponseInfo().setResponseText("File " + - receivedIdentifyRequestMessage.getFileID() + "not present on this pillar " ); + receivedIdentifyRequestMessage.getFileID() + "not present on this pillar "); messageBus.sendMessage(pillar2Response); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.COMPONENT_FAILED); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.COMPONENT_FAILED); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.FAILED); + assertEquals(OperationEventType.COMPONENT_FAILED, testEventHandler.waitForEvent().getEventType()); + assertEquals(OperationEventType.COMPONENT_FAILED, testEventHandler.waitForEvent().getEventType()); + assertEquals(OperationEventType.FAILED, testEventHandler.waitForEvent().getEventType()); } - @Test(groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public void getFileClientWithChecksumPillarInvolved() throws Exception { addDescription("Verify that the GetFile works correctly when a checksum pillar respond."); @@ -470,7 +480,7 @@ public void getFileClientWithChecksumPillarInvolved() throws Exception { testEventHandler, null); IdentifyPillarsForGetFileRequest receivedIdentifyRequestMessage = collectionReceiver.waitForMessage(IdentifyPillarsForGetFileRequest.class); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.IDENTIFY_REQUEST_SENT); + assertEquals(OperationEventType.IDENTIFY_REQUEST_SENT, testEventHandler.waitForEvent().getEventType()); addStep("Send an identification response from pillar1 with a REQUEST_NOT_SUPPORTED response code.", "No events should be generated."); @@ -486,24 +496,25 @@ public void getFileClientWithChecksumPillarInvolved() throws Exception { IdentifyPillarsForGetFileResponse identificationResponse2 = messageFactory.createIdentifyPillarsForGetFileResponse( receivedIdentifyRequestMessage, PILLAR2_ID, pillar2DestinationId); messageBus.sendMessage(identificationResponse2); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.COMPONENT_IDENTIFIED); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.IDENTIFICATION_COMPLETE); + assertEquals(OperationEventType.COMPONENT_IDENTIFIED, testEventHandler.waitForEvent().getEventType()); + assertEquals(OperationEventType.IDENTIFICATION_COMPLETE, testEventHandler.waitForEvent().getEventType()); addStep("Verify that the client continues to the performing phase.", "A REQUEST_SENT event should be generated and a GetFileRequest should be sent to pillar2."); GetFileRequest getFileRequest = pillar2Receiver.waitForMessage(GetFileRequest.class); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.REQUEST_SENT); + assertEquals(OperationEventType.REQUEST_SENT, testEventHandler.waitForEvent().getEventType()); addStep("Send a final response upload message", "A COMPONENT_COMPLETE event should be generated followed by at COMPLETE event."); GetFileFinalResponse completeMsg = messageFactory.createGetFileFinalResponse( getFileRequest, PILLAR2_ID, pillar1DestinationId); messageBus.sendMessage(completeMsg); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.COMPONENT_COMPLETE); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.COMPLETE); + assertEquals(OperationEventType.COMPONENT_COMPLETE, testEventHandler.waitForEvent().getEventType()); + assertEquals(OperationEventType.COMPLETE, testEventHandler.waitForEvent().getEventType()); } - @Test(groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public void singleComponentFailureDuringIdentify() throws Exception { addDescription("Verify that the GetFile reports a complete (not failed), in case of a component failing " + "during the identify phase."); @@ -517,7 +528,7 @@ public void singleComponentFailureDuringIdentify() throws Exception { testEventHandler, null); IdentifyPillarsForGetFileRequest receivedIdentifyRequestMessage = collectionReceiver.waitForMessage(IdentifyPillarsForGetFileRequest.class); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.IDENTIFY_REQUEST_SENT); + assertEquals(OperationEventType.IDENTIFY_REQUEST_SENT, testEventHandler.waitForEvent().getEventType()); addStep("Send an identification response from pillar1 with an IDENTIFICATION_NEGATIVE response code .", "No events should be generated."); @@ -526,31 +537,32 @@ public void singleComponentFailureDuringIdentify() throws Exception { receivedIdentifyRequestMessage, PILLAR1_ID, pillar1DestinationId); identificationResponse1.getResponseInfo().setResponseCode(ResponseCode.IDENTIFICATION_NEGATIVE); messageBus.sendMessage(identificationResponse1); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.COMPONENT_FAILED); + assertEquals(OperationEventType.COMPONENT_FAILED, testEventHandler.waitForEvent().getEventType()); addStep("Send an identification response from pillar2 with an IDENTIFICATION_POSITIVE response code .", "A component COMPONENT_IDENTIFIED event should be generated followed by an IDENTIFICATION_COMPLETE."); IdentifyPillarsForGetFileResponse identificationResponse2 = messageFactory.createIdentifyPillarsForGetFileResponse( receivedIdentifyRequestMessage, PILLAR2_ID, pillar2DestinationId); messageBus.sendMessage(identificationResponse2); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.COMPONENT_IDENTIFIED); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.IDENTIFICATION_COMPLETE); + assertEquals(OperationEventType.COMPONENT_IDENTIFIED, testEventHandler.waitForEvent().getEventType()); + assertEquals(OperationEventType.IDENTIFICATION_COMPLETE, testEventHandler.waitForEvent().getEventType()); addStep("Verify that the client continues to the performing phase.", "A REQUEST_SENT event should be generated and a GetFileRequest should be sent to pillar2."); GetFileRequest getFileRequest = pillar2Receiver.waitForMessage(GetFileRequest.class); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.REQUEST_SENT); + assertEquals(OperationEventType.REQUEST_SENT, testEventHandler.waitForEvent().getEventType()); addStep("Send a final response upload message", "A COMPONENT_COMPLETE event should be generated followed by at COMPLETE event."); GetFileFinalResponse completeMsg = messageFactory.createGetFileFinalResponse( getFileRequest, PILLAR2_ID, pillar1DestinationId); messageBus.sendMessage(completeMsg); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.COMPONENT_COMPLETE); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.COMPLETE); + assertEquals(OperationEventType.COMPONENT_COMPLETE, testEventHandler.waitForEvent().getEventType()); + assertEquals(OperationEventType.COMPLETE, testEventHandler.waitForEvent().getEventType()); } - @Test(groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public void failureDuringPerform() throws Exception { addDescription("Verify that the GetFile reports a failed operation, in case of a component failing " + "during the performing phase."); @@ -586,12 +598,13 @@ public void failureDuringPerform() throws Exception { getFileRequest, PILLAR1_ID, pillar1DestinationId); completeMsg.getResponseInfo().setResponseCode(ResponseCode.FAILURE); messageBus.sendMessage(completeMsg); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.COMPONENT_FAILED); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.FAILED); + assertEquals(OperationEventType.COMPONENT_FAILED, testEventHandler.waitForEvent().getEventType()); + assertEquals(OperationEventType.FAILED, testEventHandler.waitForEvent().getEventType()); } - @Test(groups={"regressiontest"}) + @Test + @Tag("regressiontest") public void getFileFromOtherCollection() throws Exception { addDescription("Tests the getFiles client will correctly try to get from a second collection if required"); addFixture("Configure collection1 to contain both pillars and collection 2 to only contain pillar2"); @@ -601,7 +614,7 @@ public void getFileFromOtherCollection() throws Exception { settingsForCUT.getRepositorySettings().getCollections().getCollection().get(0).getPillarIDs().getPillarID().add(PILLAR2_ID); settingsForCUT.getRepositorySettings().getCollections().getCollection().get(1).getPillarIDs().getPillarID().clear(); settingsForCUT.getRepositorySettings().getCollections().getCollection().get(1).getPillarIDs().getPillarID().add(PILLAR2_ID); - String otherCollection = settingsForCUT.getRepositorySettings().getCollections().getCollection().get(1).getID(); + String otherCollection = settingsForCUT.getRepositorySettings().getCollections().getCollection().get(1).getID(); TestEventHandler testEventHandler = new TestEventHandler(testEventManager); GetFileClient client = createGetFileClient(); @@ -611,7 +624,7 @@ public void getFileFromOtherCollection() throws Exception { client.getFileFromFastestPillar(otherCollection, DEFAULT_FILE_ID, NO_FILE_PART, httpServerConfiguration.getURL(DEFAULT_FILE_ID), testEventHandler, null); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.IDENTIFY_REQUEST_SENT); + assertEquals(OperationEventType.IDENTIFY_REQUEST_SENT, testEventHandler.waitForEvent().getEventType()); IdentifyPillarsForGetFileRequest receivedIdentifyRequestMessage = collectionReceiver.waitForMessage(IdentifyPillarsForGetFileRequest.class); assertEquals(receivedIdentifyRequestMessage.getCollectionID(), otherCollection); @@ -621,9 +634,9 @@ public void getFileFromOtherCollection() throws Exception { "REQUEST_SENT. A GetFileIdsFileRequest should be sent to pillar2"); messageBus.sendMessage(messageFactory.createIdentifyPillarsForGetFileResponse( receivedIdentifyRequestMessage, PILLAR2_ID, pillar2DestinationId)); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.COMPONENT_IDENTIFIED); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.IDENTIFICATION_COMPLETE); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.REQUEST_SENT); + assertEquals(OperationEventType.COMPONENT_IDENTIFIED, testEventHandler.waitForEvent().getEventType()); + assertEquals(OperationEventType.IDENTIFICATION_COMPLETE, testEventHandler.waitForEvent().getEventType()); + assertEquals(OperationEventType.REQUEST_SENT, testEventHandler.waitForEvent().getEventType()); GetFileRequest receivedRequest = pillar2Receiver.waitForMessage(GetFileRequest.class); assertEquals(receivedRequest.getCollectionID(), otherCollection); @@ -632,15 +645,16 @@ public void getFileFromOtherCollection() throws Exception { GetFileFinalResponse putFileFinalResponse1 = messageFactory.createGetFileFinalResponse( receivedRequest, PILLAR2_ID, pillar2DestinationId); messageBus.sendMessage(putFileFinalResponse1); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.COMPONENT_COMPLETE); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.COMPLETE); + assertEquals(OperationEventType.COMPONENT_COMPLETE, testEventHandler.waitForEvent().getEventType()); + assertEquals(OperationEventType.COMPLETE, testEventHandler.waitForEvent().getEventType()); } /** * Creates a new test GetFileClient based on the supplied settings. - * + *

* Note that the normal way of creating client through the module factory would reuse components with settings from * previous tests. + * * @return A new GetFileClient(Wrapper). */ private GetFileClient createGetFileClient() { diff --git a/bitrepository-client/src/test/java/org/bitrepository/access/getfile/GetFileClientTestWrapper.java b/bitrepository-client/src/test/java/org/bitrepository/access/getfile/GetFileClientTestWrapper.java index 7b1bdf662..f22d8eeca 100644 --- a/bitrepository-client/src/test/java/org/bitrepository/access/getfile/GetFileClientTestWrapper.java +++ b/bitrepository-client/src/test/java/org/bitrepository/access/getfile/GetFileClientTestWrapper.java @@ -34,8 +34,8 @@ * Wraps the GetFileClient adding test event logging and functionality for handling blocking calls. */ public class GetFileClientTestWrapper implements GetFileClient { - private GetFileClient createGetFileClient; - private TestEventManager testEventManager; + private final GetFileClient createGetFileClient; + private final TestEventManager testEventManager; public GetFileClientTestWrapper(GetFileClient createGetFileClient, TestEventManager testEventManager) { diff --git a/bitrepository-client/src/test/java/org/bitrepository/access/getfileids/GetFileIDsClientComponentTest.java b/bitrepository-client/src/test/java/org/bitrepository/access/getfileids/GetFileIDsClientComponentTest.java index 66ea0c8fa..bb5666ac8 100644 --- a/bitrepository-client/src/test/java/org/bitrepository/access/getfileids/GetFileIDsClientComponentTest.java +++ b/bitrepository-client/src/test/java/org/bitrepository/access/getfileids/GetFileIDsClientComponentTest.java @@ -8,16 +8,16 @@ * Copyright (C) 2010 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% @@ -46,16 +46,18 @@ import org.bitrepository.client.eventhandler.OperationEvent.OperationEventType; import org.bitrepository.common.utils.CalendarUtils; import org.bitrepository.protocol.bus.MessageReceiver; -import org.testng.Assert; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; import javax.xml.bind.JAXBException; import java.math.BigInteger; import java.net.URL; import java.util.Date; -import static org.testng.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; + /** * Test class for the 'GetFileIDsClient'. @@ -66,23 +68,25 @@ public class GetFileIDsClientComponentTest extends DefaultClientTest { /** * Set up the test scenario before running the tests in this class. + * * @throws javax.xml.bind.JAXBException */ - @BeforeMethod(alwaysRun = true) + @BeforeEach public void setUp() throws JAXBException { // TODO getFileIDsFromFastestPillar settings messageFactory = new TestGetFileIDsMessageFactory(settingsForTestClient.getComponentID()); } - @Test(groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public void verifyGetFileIDsClientFromFactory() throws Exception { - Assert.assertTrue(AccessComponentFactory.getInstance().createGetFileIDsClient(settingsForCUT, securityManager, - settingsForTestClient.getComponentID()) instanceof ConversationBasedGetFileIDsClient, - "The default GetFileClient from the Access factory should be of the type '" + - ConversationBasedGetFileIDsClient.class.getName() + "'."); + Assertions.assertInstanceOf(ConversationBasedGetFileIDsClient.class, AccessComponentFactory.getInstance().createGetFileIDsClient(settingsForCUT, securityManager, + settingsForTestClient.getComponentID()), "The default GetFileClient from the Access factory should be of the type '" + + ConversationBasedGetFileIDsClient.class.getName() + "'."); } - @Test(groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public void getFileIDsDeliveredAtUrl() throws Exception { addDescription("Tests the delivery of fileIDs from a pillar at a given URL."); addStep("Initialise the variables for this test.", @@ -99,17 +103,17 @@ public void getFileIDsDeliveredAtUrl() throws Exception { addStep("Request the delivery of the file ids of a file from the pillar(s). A callback listener should be supplied.", "A IdentifyPillarsForGetFileIDsRequest will be sent to the pillar(s)."); - getFileIDsClient.getFileIDs(collectionID, null, DEFAULT_FILE_ID,deliveryUrl, testEventHandler); + getFileIDsClient.getFileIDs(collectionID, null, DEFAULT_FILE_ID, deliveryUrl, testEventHandler); - IdentifyPillarsForGetFileIDsRequest receivedIdentifyRequestMessage = collectionReceiver.waitForMessage( + IdentifyPillarsForGetFileIDsRequest receivedIdentifyRequestMessage = collectionReceiver.waitForMessage( IdentifyPillarsForGetFileIDsRequest.class); assertEquals(receivedIdentifyRequestMessage.getCollectionID(), collectionID); - Assert.assertNotNull(receivedIdentifyRequestMessage.getCorrelationID()); + Assertions.assertNotNull(receivedIdentifyRequestMessage.getCorrelationID()); assertEquals(receivedIdentifyRequestMessage.getReplyTo(), settingsForCUT.getReceiverDestinationID()); - assertEquals(receivedIdentifyRequestMessage.getTo(), PILLAR1_ID); + assertEquals(PILLAR1_ID, receivedIdentifyRequestMessage.getTo()); assertEquals(receivedIdentifyRequestMessage.getFrom(), settingsForTestClient.getComponentID()); assertEquals(receivedIdentifyRequestMessage.getDestination(), settingsForTestClient.getCollectionDestination()); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.IDENTIFY_REQUEST_SENT); + assertEquals(OperationEventType.IDENTIFY_REQUEST_SENT, testEventHandler.waitForEvent().getEventType()); addStep("The pillar sends a response to the identify message.", "The callback listener should notify of the response and the client should send a GetFileIDsRequest " @@ -117,10 +121,10 @@ public void getFileIDsDeliveredAtUrl() throws Exception { IdentifyPillarsForGetFileIDsResponse identifyResponse = messageFactory.createIdentifyPillarsForGetFileIDsResponse( receivedIdentifyRequestMessage, PILLAR1_ID, pillar1DestinationId); messageBus.sendMessage(identifyResponse); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.COMPONENT_IDENTIFIED); + assertEquals(OperationEventType.COMPONENT_IDENTIFIED, testEventHandler.waitForEvent().getEventType()); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.IDENTIFICATION_COMPLETE); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.REQUEST_SENT); + assertEquals(OperationEventType.IDENTIFICATION_COMPLETE, testEventHandler.waitForEvent().getEventType()); + assertEquals(OperationEventType.REQUEST_SENT, testEventHandler.waitForEvent().getEventType()); GetFileIDsRequest receivedGetFileIDsRequest = pillar1Receiver.waitForMessage(GetFileIDsRequest.class); assertEquals(receivedGetFileIDsRequest.getCollectionID(), collectionID); assertEquals(receivedGetFileIDsRequest.getCorrelationID(), receivedIdentifyRequestMessage.getCorrelationID()); @@ -133,7 +137,7 @@ public void getFileIDsDeliveredAtUrl() throws Exception { GetFileIDsProgressResponse getFileIDsProgressResponse = messageFactory.createGetFileIDsProgressResponse( receivedGetFileIDsRequest, PILLAR1_ID, pillar1DestinationId); messageBus.sendMessage(getFileIDsProgressResponse); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.PROGRESS); + assertEquals(OperationEventType.PROGRESS, testEventHandler.waitForEvent().getEventType()); addStep("The resulting file is uploaded to the indicated url and the pillar sends a final response upload message", "The GetFileIDsClient notifies that the file is ready through the callback listener and the uploaded file is present."); @@ -149,17 +153,18 @@ public void getFileIDsDeliveredAtUrl() throws Exception { addStep("Receive and validate event results for the pillar.", "Should be a FileIDsCompletePillarEvent with the ResultingFileIDs containing only the URL."); FileIDsCompletePillarEvent event = (FileIDsCompletePillarEvent) testEventHandler.waitForEvent(); - assertEquals(event.getEventType(), OperationEventType.COMPONENT_COMPLETE); + assertEquals(OperationEventType.COMPONENT_COMPLETE, event.getEventType()); ResultingFileIDs resFileIDs = event.getFileIDs(); - Assert.assertNotNull(resFileIDs, "The ResultingFileIDs may not be null."); - Assert.assertTrue(resFileIDs.getResultAddress().contains(deliveryUrl.toExternalForm()), + Assertions.assertNotNull(resFileIDs, "The ResultingFileIDs may not be null."); + Assertions.assertTrue(resFileIDs.getResultAddress().contains(deliveryUrl.toExternalForm()), "The resulting address'" + resFileIDs.getResultAddress() + "' should contain the argument address: '" + deliveryUrl.toExternalForm() + "'"); - Assert.assertNull(resFileIDs.getFileIDsData(), "No FileIDsData should be returned."); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.COMPLETE); + Assertions.assertNull(resFileIDs.getFileIDsData(), "No FileIDsData should be returned."); + assertEquals(OperationEventType.COMPLETE, testEventHandler.waitForEvent().getEventType()); } - @Test(groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public void getFileIDsDeliveredThroughMessage() throws Exception { addDescription("Tests the delivery of fileIDs from a pillar at a given URL."); addStep("Initialise the variables for this test.", @@ -180,7 +185,7 @@ public void getFileIDsDeliveredThroughMessage() throws Exception { IdentifyPillarsForGetFileIDsRequest receivedIdentifyRequestMessage = collectionReceiver.waitForMessage( IdentifyPillarsForGetFileIDsRequest.class); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.IDENTIFY_REQUEST_SENT); + assertEquals(OperationEventType.IDENTIFY_REQUEST_SENT, testEventHandler.waitForEvent().getEventType()); addStep("The pillar sends a response to the identify message.", "The callback listener should notify of the response and the client should send a GetFileIDsRequest " @@ -191,18 +196,18 @@ public void getFileIDsDeliveredThroughMessage() throws Exception { messageBus.sendMessage(identifyResponse); GetFileIDsRequest receivedGetFileIDsRequest = pillar1Receiver.waitForMessage(GetFileIDsRequest.class); - for(int i = 0; i < settingsForCUT.getRepositorySettings().getCollections().getCollection().get(0).getPillarIDs().getPillarID().size(); i++) { - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.COMPONENT_IDENTIFIED); + for (int i = 0; i < settingsForCUT.getRepositorySettings().getCollections().getCollection().get(0).getPillarIDs().getPillarID().size(); i++) { + assertEquals(OperationEventType.COMPONENT_IDENTIFIED, testEventHandler.waitForEvent().getEventType()); } - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.IDENTIFICATION_COMPLETE); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.REQUEST_SENT); + assertEquals(OperationEventType.IDENTIFICATION_COMPLETE, testEventHandler.waitForEvent().getEventType()); + assertEquals(OperationEventType.REQUEST_SENT, testEventHandler.waitForEvent().getEventType()); addStep("The pillar sends a getFileIDsProgressResponse to the GetFileIDsClient.", "The GetFileIDsClient should notify about the response through the callback interface."); GetFileIDsProgressResponse getFileIDsProgressResponse = messageFactory.createGetFileIDsProgressResponse( receivedGetFileIDsRequest, PILLAR1_ID, pillar1DestinationId); messageBus.sendMessage(getFileIDsProgressResponse); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.PROGRESS); + assertEquals(OperationEventType.PROGRESS, testEventHandler.waitForEvent().getEventType()); addStep("The resulting file is uploaded to the indicated url and the pillar sends a final response upload message", "The GetFileIDsClient notifies that the file is ready through the callback listener and the uploaded file is present."); @@ -226,22 +231,23 @@ public void getFileIDsDeliveredThroughMessage() throws Exception { addStep("Receive and validate event results for the pillar.", "Should be a FileIDsCompletePillarEvent with the ResultingFileIDs containing the list of fileids."); - for(int i = 0; i < settingsForCUT.getRepositorySettings().getCollections().getCollection().get(0).getPillarIDs().getPillarID().size(); i++) { + for (int i = 0; i < settingsForCUT.getRepositorySettings().getCollections().getCollection().get(0).getPillarIDs().getPillarID().size(); i++) { FileIDsCompletePillarEvent event = (FileIDsCompletePillarEvent) testEventHandler.waitForEvent(); - assertEquals(event.getEventType(), OperationEventType.COMPONENT_COMPLETE); + assertEquals(OperationEventType.COMPONENT_COMPLETE, event.getEventType()); ResultingFileIDs resFileIDs = event.getFileIDs(); - Assert.assertNotNull(resFileIDs, "The ResultingFileIDs may not be null."); - Assert.assertNull(resFileIDs.getResultAddress(), "The results should be sent back through the message, " + Assertions.assertNotNull(resFileIDs, "The ResultingFileIDs may not be null."); + Assertions.assertNull(resFileIDs.getResultAddress(), "The results should be sent back through the message, " + "and therefore no resulting address should be returned."); - Assert.assertNotNull(resFileIDs.getFileIDsData(), "No FileIDsData should be returned."); - assertEquals(resFileIDs.getFileIDsData().getFileIDsDataItems().getFileIDsDataItem().size(), - 1, "Response should contain same amount of fileids as requested."); + Assertions.assertNotNull(resFileIDs.getFileIDsData(), "No FileIDsData should be returned."); + assertEquals(1, + resFileIDs.getFileIDsData().getFileIDsDataItems().getFileIDsDataItem().size(), "Response should contain same amount of fileids as requested."); } - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.COMPLETE); + assertEquals(OperationEventType.COMPLETE, testEventHandler.waitForEvent().getEventType()); } - @Test(groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public void testNoSuchFile() throws Exception { addDescription("Testing how a request for a non-existing file is handled."); addStep("Setting up variables and such.", "Should be OK."); @@ -261,7 +267,7 @@ public void testNoSuchFile() throws Exception { IdentifyPillarsForGetFileIDsRequest receivedIdentifyRequestMessage = collectionReceiver.waitForMessage( IdentifyPillarsForGetFileIDsRequest.class); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.IDENTIFY_REQUEST_SENT); + assertEquals(OperationEventType.IDENTIFY_REQUEST_SENT, testEventHandler.waitForEvent().getEventType()); addStep("The pillar sends a response to the identify message.", "The callback listener should notify of the response and the client should send a GetFileIDsRequest " @@ -273,11 +279,11 @@ public void testNoSuchFile() throws Exception { messageBus.sendMessage(identifyResponse); receivedGetFileIDsRequest = pillar1Receiver.waitForMessage(GetFileIDsRequest.class); - for(int i = 0; i < settingsForCUT.getRepositorySettings().getCollections().getCollection().get(0).getPillarIDs().getPillarID().size(); i++) { - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.COMPONENT_IDENTIFIED); + for (int i = 0; i < settingsForCUT.getRepositorySettings().getCollections().getCollection().get(0).getPillarIDs().getPillarID().size(); i++) { + assertEquals(OperationEventType.COMPONENT_IDENTIFIED, testEventHandler.waitForEvent().getEventType()); } - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.IDENTIFICATION_COMPLETE); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.REQUEST_SENT); + assertEquals(OperationEventType.IDENTIFICATION_COMPLETE, testEventHandler.waitForEvent().getEventType()); + assertEquals(OperationEventType.REQUEST_SENT, testEventHandler.waitForEvent().getEventType()); addStep("Send a error that the file cannot be found.", "Should trigger a 'event failed'."); GetFileIDsFinalResponse completeMsg = messageFactory.createGetFileIDsFinalResponse( @@ -291,35 +297,36 @@ public void testNoSuchFile() throws Exception { messageBus.sendMessage(completeMsg); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.COMPONENT_FAILED); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.FAILED); + assertEquals(OperationEventType.COMPONENT_FAILED, testEventHandler.waitForEvent().getEventType()); + assertEquals(OperationEventType.FAILED, testEventHandler.waitForEvent().getEventType()); } - @Test(groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public void testPaging() throws Exception { addDescription("Tests the GetFileIDs client correctly handles functionality for limiting results, either by " + - "timestamp or result count."); + "timestamp or result count."); GetFileIDsClient client = createGetFileIDsClient(); addStep("Request fileIDs from with MinTimestamp, MaxTimestamp, MaxNumberOfResults set for both pillars .", - "A IdentifyPillarsForGetFileIDsRequest should be sent."); + "A IdentifyPillarsForGetFileIDsRequest should be sent."); Date timestamp3 = new Date(); - Date timestamp2 = new Date(timestamp3.getTime() - 100); - Date timestamp1 = new Date(timestamp3.getTime() - 1000); + Date timestamp2 = new Date(timestamp3.getTime() - 100); + Date timestamp1 = new Date(timestamp3.getTime() - 1000); ContributorQuery query1 = new ContributorQuery(PILLAR1_ID, timestamp1, timestamp2, 1); ContributorQuery query2 = new ContributorQuery(PILLAR2_ID, timestamp2, timestamp3, 2); client.getFileIDs(collectionID, new ContributorQuery[]{query1, query2}, null, null, testEventHandler); IdentifyPillarsForGetFileIDsRequest receivedIdentifyRequestMessage = collectionReceiver.waitForMessage( - IdentifyPillarsForGetFileIDsRequest.class); + IdentifyPillarsForGetFileIDsRequest.class); addStep("Send a IdentifyPillarsForGetFileIDsResponse from both pillars.", - "A GetFileIDsRequest should be sent to both pillars with the appropriate MinTimestamp, MaxTimestamp, " + - "MaxNumberOfResults values."); + "A GetFileIDsRequest should be sent to both pillars with the appropriate MinTimestamp, MaxTimestamp, " + + "MaxNumberOfResults values."); messageBus.sendMessage(messageFactory.createIdentifyPillarsForGetFileIDsResponse( receivedIdentifyRequestMessage, PILLAR1_ID, pillar1DestinationId)); messageBus.sendMessage(messageFactory.createIdentifyPillarsForGetFileIDsResponse( - receivedIdentifyRequestMessage, PILLAR2_ID, pillar2DestinationId)); + receivedIdentifyRequestMessage, PILLAR2_ID, pillar2DestinationId)); GetFileIDsRequest receivedGetFileIDsRequest1 = pillar1Receiver.waitForMessage(GetFileIDsRequest.class); assertEquals(receivedGetFileIDsRequest1.getMinTimestamp(), @@ -344,7 +351,8 @@ public void testPaging() throws Exception { "Unexpected MaxNumberOfResults in GetFileIDsRequest to pillar2."); } - @Test(groups={"regressiontest"}) + @Test + @Tag("regressiontest") public void getFileIDsFromOtherCollection() throws Exception { addDescription("Tests the getFileIDs client will correctly try to get from a second collection if required"); addFixture("Configure collection1 to contain both pillars and collection 2 to only contain pillar2"); @@ -354,14 +362,14 @@ public void getFileIDsFromOtherCollection() throws Exception { settingsForCUT.getRepositorySettings().getCollections().getCollection().get(0).getPillarIDs().getPillarID().add(PILLAR2_ID); settingsForCUT.getRepositorySettings().getCollections().getCollection().get(1).getPillarIDs().getPillarID().clear(); settingsForCUT.getRepositorySettings().getCollections().getCollection().get(1).getPillarIDs().getPillarID().add(PILLAR2_ID); - String otherCollection = settingsForCUT.getRepositorySettings().getCollections().getCollection().get(1).getID(); + String otherCollection = settingsForCUT.getRepositorySettings().getCollections().getCollection().get(1).getID(); TestEventHandler testEventHandler = new TestEventHandler(testEventManager); GetFileIDsClient client = createGetFileIDsClient(); addStep("Request the putting of a file through the PutClient for collection2", "A identification request should be dispatched."); client.getFileIDs(otherCollection, null, DEFAULT_FILE_ID, null, testEventHandler); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.IDENTIFY_REQUEST_SENT); + assertEquals(OperationEventType.IDENTIFY_REQUEST_SENT, testEventHandler.waitForEvent().getEventType()); IdentifyPillarsForGetFileIDsRequest receivedIdentifyRequestMessage = collectionReceiver.waitForMessage(IdentifyPillarsForGetFileIDsRequest.class); assertEquals(receivedIdentifyRequestMessage.getCollectionID(), otherCollection); @@ -371,9 +379,9 @@ public void getFileIDsFromOtherCollection() throws Exception { "REQUEST_SENT. A GetFileIdsFileRequest should be sent to pillar2"); messageBus.sendMessage(messageFactory.createIdentifyPillarsForGetFileIDsResponse( receivedIdentifyRequestMessage, PILLAR2_ID, pillar2DestinationId)); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.COMPONENT_IDENTIFIED); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.IDENTIFICATION_COMPLETE); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.REQUEST_SENT); + assertEquals(OperationEventType.COMPONENT_IDENTIFIED, testEventHandler.waitForEvent().getEventType()); + assertEquals(OperationEventType.IDENTIFICATION_COMPLETE, testEventHandler.waitForEvent().getEventType()); + assertEquals(OperationEventType.REQUEST_SENT, testEventHandler.waitForEvent().getEventType()); GetFileIDsRequest receivedRequest = pillar2Receiver.waitForMessage(GetFileIDsRequest.class); assertEquals(receivedRequest.getCollectionID(), otherCollection); @@ -382,15 +390,16 @@ public void getFileIDsFromOtherCollection() throws Exception { GetFileIDsFinalResponse putFileFinalResponse1 = messageFactory.createGetFileIDsFinalResponse( receivedRequest, PILLAR2_ID, pillar2DestinationId); messageBus.sendMessage(putFileFinalResponse1); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.COMPONENT_COMPLETE); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.COMPLETE); + assertEquals(OperationEventType.COMPONENT_COMPLETE, testEventHandler.waitForEvent().getEventType()); + assertEquals(OperationEventType.COMPLETE, testEventHandler.waitForEvent().getEventType()); } /** * Creates a new test GetFileIDsClient based on the supplied settings. - * + *

* Note that the normal way of creating client through the module factory would reuse components with settings from * previous tests. + * * @return A new GetFileIDsClient(Wrapper). */ private GetFileIDsClient createGetFileIDsClient() { @@ -401,14 +410,14 @@ private GetFileIDsClient createGetFileIDsClient() { @Override protected MessageResponse createIdentifyResponse(MessageRequest identifyRequest, String from, String to) { MessageResponse response = messageFactory.createIdentifyPillarsForGetFileIDsResponse( - (IdentifyPillarsForGetFileIDsRequest)identifyRequest, from, to); + (IdentifyPillarsForGetFileIDsRequest) identifyRequest, from, to); return response; } @Override protected MessageResponse createFinalResponse(MessageRequest request, String from, String to) { - MessageResponse response = messageFactory.createGetFileIDsFinalResponse( - (GetFileIDsRequest)request, from, to); + MessageResponse response = messageFactory.createGetFileIDsFinalResponse( + (GetFileIDsRequest) request, from, to); return response; } diff --git a/bitrepository-client/src/test/java/org/bitrepository/access/getfileids/GetFileIDsClientTestWrapper.java b/bitrepository-client/src/test/java/org/bitrepository/access/getfileids/GetFileIDsClientTestWrapper.java index 20e2811c1..352e181ca 100644 --- a/bitrepository-client/src/test/java/org/bitrepository/access/getfileids/GetFileIDsClientTestWrapper.java +++ b/bitrepository-client/src/test/java/org/bitrepository/access/getfileids/GetFileIDsClientTestWrapper.java @@ -55,8 +55,7 @@ public void getFileIDs(String collectionID, ContributorQuery[] contributorQuerie URL addressForResult, EventHandler eventHandler) { eventManager.addStimuli("Calling getFileIDs(" + (contributorQueries == null ? "null" : Arrays.asList(contributorQueries)) + - ", " + fileID + ", " + - "" + addressForResult + ", " + ", " + fileID + ", " + addressForResult + ", " + eventHandler + ")"); client.getFileIDs(collectionID, contributorQueries, fileID, addressForResult, eventHandler); } diff --git a/bitrepository-client/src/test/java/org/bitrepository/access/getstatus/GetStatusClientComponentTest.java b/bitrepository-client/src/test/java/org/bitrepository/access/getstatus/GetStatusClientComponentTest.java index 65154587b..0f3eb74d8 100644 --- a/bitrepository-client/src/test/java/org/bitrepository/access/getstatus/GetStatusClientComponentTest.java +++ b/bitrepository-client/src/test/java/org/bitrepository/access/getstatus/GetStatusClientComponentTest.java @@ -5,16 +5,16 @@ * Copyright (C) 2010 - 2012 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% @@ -36,172 +36,176 @@ import org.bitrepository.common.utils.CalendarUtils; import org.bitrepository.protocol.message.TestGetStatusMessageFactory; import org.bitrepository.settings.repositorysettings.GetStatusSettings; -import org.testng.Assert; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; import javax.xml.datatype.DatatypeFactory; import java.util.List; -import static org.testng.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; -public class GetStatusClientComponentTest extends DefaultFixtureClientTest { - - private TestGetStatusMessageFactory testMessageFactory; - @BeforeMethod(alwaysRun=true) - public void beforeMethodSetup() { - testMessageFactory = new TestGetStatusMessageFactory(settingsForTestClient.getComponentID()); +public class GetStatusClientComponentTest extends DefaultFixtureClientTest { - if (settingsForCUT.getRepositorySettings().getGetStatusSettings() == null) { - settingsForCUT.getRepositorySettings().setGetStatusSettings(new GetStatusSettings()); - } - List contributors = settingsForCUT.getRepositorySettings().getGetStatusSettings().getNonPillarContributorIDs(); - contributors.clear(); - contributors.add(PILLAR1_ID); - contributors.add(PILLAR2_ID); - } + private TestGetStatusMessageFactory testMessageFactory; - @Test(groups = {"regressiontest"}) - public void verifyGetStatusClientFromFactory() { - Assert.assertTrue(AccessComponentFactory.getInstance().createGetStatusClient( - settingsForCUT, securityManager, settingsForTestClient.getComponentID()) - instanceof ConversationBasedGetStatusClient, - "The default GetStatusClient from the Access factory should be of the type '" + - ConversationBasedGetStatusClient.class.getName() + "'."); - } - - @Test(groups = {"regressiontest"}) - public void incompleteSetOfIdendifyResponses() throws Exception { - addDescription("Verify that the GetStatus client works correct without receiving responses from all " + - "contributors."); - addStep("Configure 1 second timeout for identifying contributors. " + - "The default 2 contributors collection is used", ""); - - DatatypeFactory datatypeFactory = DatatypeFactory.newInstance(); - settingsForCUT.getRepositorySettings().getClientSettings() - .setIdentificationTimeoutDuration(datatypeFactory.newDuration(1000)); - TestEventHandler testEventHandler = new TestEventHandler(testEventManager); - GetStatusClient client = createGetStatusClient(); - - client.getStatus(testEventHandler); - IdentifyContributorsForGetStatusRequest identifyRequest = - collectionReceiver.waitForMessage(IdentifyContributorsForGetStatusRequest.class); - assertEquals(testEventHandler.waitForEvent().getEventType(), - OperationEventType.IDENTIFY_REQUEST_SENT); - - addStep("Send a identifyResponse from pillar 1", - "A COMPONENT_IDENTIFIED event should be received."); - IdentifyContributorsForGetStatusResponse responsePillar1 = - testMessageFactory.createIdentifyContributorsForGetStatusResponse(identifyRequest, - PILLAR1_ID, pillar1DestinationId); - messageBus.sendMessage(responsePillar1); - - assertEquals(testEventHandler.waitForEvent().getEventType(), - OperationEventType.COMPONENT_IDENTIFIED); - - addStep("Wait for timeout event", "An IDENTIFY_TIMEOUT and IDENTIFICATION_COMPLETE event should be received" + - "Right after this a GetStatusRequest should be sent to pillar1"); - assertEquals(testEventHandler.waitForEvent().getEventType(), - OperationEventType.IDENTIFY_TIMEOUT); - assertEquals(testEventHandler.waitForEvent().getEventType(), - OperationEventType.COMPONENT_FAILED); - assertEquals(testEventHandler.waitForEvent().getEventType(), - OperationEventType.IDENTIFICATION_COMPLETE); - assertEquals(testEventHandler.waitForEvent().getEventType(), - OperationEventType.REQUEST_SENT); - pillar1Receiver.waitForMessage(GetStatusRequest.class); - } - - @Test(groups = {"regressiontest"}) - public void getAllStatuses() throws InterruptedException { - addDescription("Tests the simplest case of getting status for all contributors."); - - addStep("Create a GetStatusClient.", ""); - TestEventHandler testEventHandler = new TestEventHandler(testEventManager); - GetStatusClient client = createGetStatusClient(); - - addStep("Retrieve from all contributors in the collection", - "This should be interpreted as a request for getting statuses from all contributors defined " + - "in the collection settings."); - client.getStatus(testEventHandler); - IdentifyContributorsForGetStatusRequest identifyRequest = - collectionReceiver.waitForMessage(IdentifyContributorsForGetStatusRequest.class); - assertEquals(testEventHandler.waitForEvent().getEventType(), - OperationEventType.IDENTIFY_REQUEST_SENT); - - addStep("Send a identifyResponse from each pillar", - "Two COMPONENT_IDENTIFIED events and a IDENTIFICATION_COMPLETE event should be received." + - "Rights after this a REQUEST_SENT should be received and a GetStatusRequest should " + - "be sent to each pillar"); - IdentifyContributorsForGetStatusResponse responsePillar1 = - testMessageFactory.createIdentifyContributorsForGetStatusResponse(identifyRequest, - PILLAR1_ID, pillar1DestinationId); - messageBus.sendMessage(responsePillar1); - assertEquals(testEventHandler.waitForEvent().getEventType(), - OperationEventType.COMPONENT_IDENTIFIED); - - IdentifyContributorsForGetStatusResponse responsePillar2 = - testMessageFactory.createIdentifyContributorsForGetStatusResponse(identifyRequest, - PILLAR2_ID, pillar2DestinationId); - messageBus.sendMessage(responsePillar2); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.COMPONENT_IDENTIFIED); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.IDENTIFICATION_COMPLETE); - - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.REQUEST_SENT); - GetStatusRequest requestPillar1 = pillar1Receiver.waitForMessage(GetStatusRequest.class); - assertEquals(requestPillar1, testMessageFactory.createGetStatusRequest( - requestPillar1, PILLAR1_ID, pillar1DestinationId, settingsForTestClient.getComponentID())); - GetStatusRequest requestPillar2 = pillar2Receiver.waitForMessage(GetStatusRequest.class); - assertEquals(requestPillar2, testMessageFactory.createGetStatusRequest( - requestPillar2, PILLAR2_ID, pillar2DestinationId, settingsForTestClient.getComponentID())); - - addStep("Send a final response from pillar 1", - "A COMPONENT_COMPLETE event should be generated with the audit trail results."); - ResultingStatus status1 = createTestResultingStatus(PILLAR1_ID); - GetStatusFinalResponse resultPillar1 = - testMessageFactory.createGetStatusFinalResponse(requestPillar1, - PILLAR1_ID, pillar1DestinationId, status1); - messageBus.sendMessage(resultPillar1); - StatusCompleteContributorEvent result1Event = (StatusCompleteContributorEvent) testEventHandler.waitForEvent(); - assertEquals(result1Event.getEventType(), OperationEventType.COMPONENT_COMPLETE); - assertEquals(result1Event.getStatus(), status1); - - addStep("Send a final response from pillar 2", - "A COMPONENT_COMPLETE event should be generated with the audit trail results." + - "This should be followed by a COMPLETE event"); - ResultingStatus status2 = createTestResultingStatus(PILLAR2_ID); - GetStatusFinalResponse resultPillar2 = - testMessageFactory.createGetStatusFinalResponse(requestPillar1, - PILLAR2_ID, pillar2DestinationId, status2); - messageBus.sendMessage(resultPillar2); - - StatusCompleteContributorEvent result2Event = (StatusCompleteContributorEvent) testEventHandler.waitForEvent(); - assertEquals(result2Event.getEventType(), OperationEventType.COMPONENT_COMPLETE); - assertEquals(result2Event.getStatus(), status2); - assertEquals(testEventHandler.waitForEvent().getEventType(), - OperationEventType.COMPLETE); - } + @BeforeEach + public void beforeMethodSetup() { + testMessageFactory = new TestGetStatusMessageFactory(settingsForTestClient.getComponentID()); - /** - * Creates a new test GetStatusClient based on the supplied settings. - * - * Note that the normal way of creating client through the module factory would reuse components with settings from - * previous tests. - * @return A new GetStatusClient(Wrapper). - */ - private GetStatusClient createGetStatusClient() { - return new GetStatusClientTestWrapper(new ConversationBasedGetStatusClient( - messageBus, conversationMediator, settingsForCUT, settingsForTestClient.getComponentID()) , testEventManager); - } - - private ResultingStatus createTestResultingStatus(String componentID) { - ResultingStatus resultingStatus = new ResultingStatus(); - StatusInfo info = new StatusInfo(); - info.setStatusCode(StatusCode.OK); - info.setStatusText("Everythings fine.."); - resultingStatus.setStatusInfo(info); - resultingStatus.setStatusTimestamp(CalendarUtils.getNow()); - return resultingStatus; + if (settingsForCUT.getRepositorySettings().getGetStatusSettings() == null) { + settingsForCUT.getRepositorySettings().setGetStatusSettings(new GetStatusSettings()); } + List contributors = settingsForCUT.getRepositorySettings().getGetStatusSettings().getNonPillarContributorIDs(); + contributors.clear(); + contributors.add(PILLAR1_ID); + contributors.add(PILLAR2_ID); + } + + @Test + @Tag("regressiontest") + public void verifyGetStatusClientFromFactory() { + Assertions.assertInstanceOf(ConversationBasedGetStatusClient.class, AccessComponentFactory.getInstance().createGetStatusClient( + settingsForCUT, securityManager, settingsForTestClient.getComponentID()), "The default GetStatusClient from the Access factory should be of the type '" + + ConversationBasedGetStatusClient.class.getName() + "'."); + } + + @Test + @Tag("regressiontest") + public void incompleteSetOfIdendifyResponses() throws Exception { + addDescription("Verify that the GetStatus client works correct without receiving responses from all " + + "contributors."); + addStep("Configure 1 second timeout for identifying contributors. " + + "The default 2 contributors collection is used", ""); + + DatatypeFactory datatypeFactory = DatatypeFactory.newInstance(); + settingsForCUT.getRepositorySettings().getClientSettings() + .setIdentificationTimeoutDuration(datatypeFactory.newDuration(1000)); + TestEventHandler testEventHandler = new TestEventHandler(testEventManager); + GetStatusClient client = createGetStatusClient(); + + client.getStatus(testEventHandler); + IdentifyContributorsForGetStatusRequest identifyRequest = + collectionReceiver.waitForMessage(IdentifyContributorsForGetStatusRequest.class); + assertEquals(OperationEventType.IDENTIFY_REQUEST_SENT, + testEventHandler.waitForEvent().getEventType()); + + addStep("Send a identifyResponse from pillar 1", + "A COMPONENT_IDENTIFIED event should be received."); + IdentifyContributorsForGetStatusResponse responsePillar1 = + testMessageFactory.createIdentifyContributorsForGetStatusResponse(identifyRequest, + PILLAR1_ID, pillar1DestinationId); + messageBus.sendMessage(responsePillar1); + + assertEquals(OperationEventType.COMPONENT_IDENTIFIED, + testEventHandler.waitForEvent().getEventType()); + + addStep("Wait for timeout event", "An IDENTIFY_TIMEOUT and IDENTIFICATION_COMPLETE event should be received" + + "Right after this a GetStatusRequest should be sent to pillar1"); + assertEquals(OperationEventType.IDENTIFY_TIMEOUT, + testEventHandler.waitForEvent().getEventType()); + assertEquals(OperationEventType.COMPONENT_FAILED, + testEventHandler.waitForEvent().getEventType()); + assertEquals(OperationEventType.IDENTIFICATION_COMPLETE, + testEventHandler.waitForEvent().getEventType()); + assertEquals(OperationEventType.REQUEST_SENT, + testEventHandler.waitForEvent().getEventType()); + pillar1Receiver.waitForMessage(GetStatusRequest.class); + } + + @Test + @Tag("regressiontest") + public void getAllStatuses() throws InterruptedException { + addDescription("Tests the simplest case of getting status for all contributors."); + + addStep("Create a GetStatusClient.", ""); + TestEventHandler testEventHandler = new TestEventHandler(testEventManager); + GetStatusClient client = createGetStatusClient(); + + addStep("Retrieve from all contributors in the collection", + "This should be interpreted as a request for getting statuses from all contributors defined " + + "in the collection settings."); + client.getStatus(testEventHandler); + IdentifyContributorsForGetStatusRequest identifyRequest = + collectionReceiver.waitForMessage(IdentifyContributorsForGetStatusRequest.class); + assertEquals(OperationEventType.IDENTIFY_REQUEST_SENT, + testEventHandler.waitForEvent().getEventType()); + + addStep("Send a identifyResponse from each pillar", + "Two COMPONENT_IDENTIFIED events and a IDENTIFICATION_COMPLETE event should be received." + + "Rights after this a REQUEST_SENT should be received and a GetStatusRequest should " + + "be sent to each pillar"); + IdentifyContributorsForGetStatusResponse responsePillar1 = + testMessageFactory.createIdentifyContributorsForGetStatusResponse(identifyRequest, + PILLAR1_ID, pillar1DestinationId); + messageBus.sendMessage(responsePillar1); + assertEquals(OperationEventType.COMPONENT_IDENTIFIED, + testEventHandler.waitForEvent().getEventType()); + + IdentifyContributorsForGetStatusResponse responsePillar2 = + testMessageFactory.createIdentifyContributorsForGetStatusResponse(identifyRequest, + PILLAR2_ID, pillar2DestinationId); + messageBus.sendMessage(responsePillar2); + assertEquals(OperationEventType.COMPONENT_IDENTIFIED, testEventHandler.waitForEvent().getEventType()); + assertEquals(OperationEventType.IDENTIFICATION_COMPLETE, testEventHandler.waitForEvent().getEventType()); + + assertEquals(OperationEventType.REQUEST_SENT, testEventHandler.waitForEvent().getEventType()); + GetStatusRequest requestPillar1 = pillar1Receiver.waitForMessage(GetStatusRequest.class); + assertEquals(requestPillar1, testMessageFactory.createGetStatusRequest( + requestPillar1, PILLAR1_ID, pillar1DestinationId, settingsForTestClient.getComponentID())); + GetStatusRequest requestPillar2 = pillar2Receiver.waitForMessage(GetStatusRequest.class); + assertEquals(requestPillar2, testMessageFactory.createGetStatusRequest( + requestPillar2, PILLAR2_ID, pillar2DestinationId, settingsForTestClient.getComponentID())); + + addStep("Send a final response from pillar 1", + "A COMPONENT_COMPLETE event should be generated with the audit trail results."); + ResultingStatus status1 = createTestResultingStatus(PILLAR1_ID); + GetStatusFinalResponse resultPillar1 = + testMessageFactory.createGetStatusFinalResponse(requestPillar1, + PILLAR1_ID, pillar1DestinationId, status1); + messageBus.sendMessage(resultPillar1); + StatusCompleteContributorEvent result1Event = (StatusCompleteContributorEvent) testEventHandler.waitForEvent(); + assertEquals(OperationEventType.COMPONENT_COMPLETE, result1Event.getEventType()); + assertEquals(result1Event.getStatus(), status1); + + addStep("Send a final response from pillar 2", + "A COMPONENT_COMPLETE event should be generated with the audit trail results." + + "This should be followed by a COMPLETE event"); + ResultingStatus status2 = createTestResultingStatus(PILLAR2_ID); + GetStatusFinalResponse resultPillar2 = + testMessageFactory.createGetStatusFinalResponse(requestPillar1, + PILLAR2_ID, pillar2DestinationId, status2); + messageBus.sendMessage(resultPillar2); + + StatusCompleteContributorEvent result2Event = (StatusCompleteContributorEvent) testEventHandler.waitForEvent(); + assertEquals(OperationEventType.COMPONENT_COMPLETE, result2Event.getEventType()); + assertEquals(result2Event.getStatus(), status2); + assertEquals(OperationEventType.COMPLETE, + testEventHandler.waitForEvent().getEventType()); + } + + /** + * Creates a new test GetStatusClient based on the supplied settings. + *

+ * Note that the normal way of creating client through the module factory would reuse components with settings from + * previous tests. + * + * @return A new GetStatusClient(Wrapper). + */ + private GetStatusClient createGetStatusClient() { + return new GetStatusClientTestWrapper(new ConversationBasedGetStatusClient( + messageBus, conversationMediator, settingsForCUT, settingsForTestClient.getComponentID()), testEventManager); + } + + private ResultingStatus createTestResultingStatus(String componentID) { + ResultingStatus resultingStatus = new ResultingStatus(); + StatusInfo info = new StatusInfo(); + info.setStatusCode(StatusCode.OK); + info.setStatusText("Everythings fine.."); + resultingStatus.setStatusInfo(info); + resultingStatus.setStatusTimestamp(CalendarUtils.getNow()); + return resultingStatus; + } } diff --git a/bitrepository-client/src/test/java/org/bitrepository/access/getstatus/GetStatusClientTestWrapper.java b/bitrepository-client/src/test/java/org/bitrepository/access/getstatus/GetStatusClientTestWrapper.java index 61413eaee..a57405324 100644 --- a/bitrepository-client/src/test/java/org/bitrepository/access/getstatus/GetStatusClientTestWrapper.java +++ b/bitrepository-client/src/test/java/org/bitrepository/access/getstatus/GetStatusClientTestWrapper.java @@ -25,8 +25,8 @@ import org.jaccept.TestEventManager; public class GetStatusClientTestWrapper implements GetStatusClient { - private GetStatusClient getStatusClient; - private TestEventManager testEventManager; + private final GetStatusClient getStatusClient; + private final TestEventManager testEventManager; public GetStatusClientTestWrapper(GetStatusClient getStatusClient, TestEventManager testEventManager) { diff --git a/bitrepository-client/src/test/java/org/bitrepository/client/DefaultClientTest.java b/bitrepository-client/src/test/java/org/bitrepository/client/DefaultClientTest.java index 3d34ee8a1..e13726449 100644 --- a/bitrepository-client/src/test/java/org/bitrepository/client/DefaultClientTest.java +++ b/bitrepository-client/src/test/java/org/bitrepository/client/DefaultClientTest.java @@ -6,16 +6,16 @@ * Copyright (C) 2010 - 2012 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% @@ -27,14 +27,16 @@ import org.bitrepository.client.eventhandler.OperationEvent; import org.bitrepository.client.eventhandler.OperationEvent.OperationEventType; import org.bitrepository.protocol.bus.MessageReceiver; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; import javax.xml.datatype.DatatypeConfigurationException; import javax.xml.datatype.DatatypeFactory; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + /** * Tests the general client functionality. A number of abstract methods with needs to be implemented with concrete @@ -44,12 +46,13 @@ public abstract class DefaultClientTest extends DefaultFixtureClientTest { protected final TestEventHandler testEventHandler = new TestEventHandler(testEventManager); private DatatypeFactory datatypeFactory; - @BeforeMethod(alwaysRun = true) + @BeforeEach public void setUpFactory() throws DatatypeConfigurationException { datatypeFactory = DatatypeFactory.newInstance(); } - @Test(groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public void identificationNegativeTest() throws Exception { addDescription("Verify that the client works correctly when a contributor sends a negative response."); @@ -57,7 +60,7 @@ public void identificationNegativeTest() throws Exception { "A IDENTIFY_REQUEST_SENT should be generate and a identification request should be sent."); startOperation(testEventHandler); MessageRequest identifyRequest = waitForIdentifyRequest(); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.IDENTIFY_REQUEST_SENT); + assertEquals(OperationEventType.IDENTIFY_REQUEST_SENT, testEventHandler.waitForEvent().getEventType()); addStep("Send a identification response from contributor1 with a IDENTIFICATION_NEGATIVE response code .", "A component failed event should be generated."); @@ -65,33 +68,34 @@ public void identificationNegativeTest() throws Exception { MessageResponse identifyResponse1 = createIdentifyResponse(identifyRequest, PILLAR1_ID, pillar1DestinationId); identifyResponse1.getResponseInfo().setResponseCode(ResponseCode.IDENTIFICATION_NEGATIVE); messageBus.sendMessage(identifyResponse1); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.COMPONENT_FAILED); + assertEquals(OperationEventType.COMPONENT_FAILED, testEventHandler.waitForEvent().getEventType()); addStep("Send a identification response from contributor2 with a IDENTIFICATION_POSITIVE response code .", "A component COMPONENT_IDENTIFIED event should be generated followed by a IDENTIFICATION_COMPLETE."); MessageResponse identifyResponse2 = createIdentifyResponse(identifyRequest, PILLAR2_ID, pillar2DestinationId); identifyResponse2.getResponseInfo().setResponseCode(ResponseCode.IDENTIFICATION_POSITIVE); messageBus.sendMessage(identifyResponse2); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.COMPONENT_IDENTIFIED); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.IDENTIFICATION_COMPLETE); + assertEquals(OperationEventType.COMPONENT_IDENTIFIED, testEventHandler.waitForEvent().getEventType()); + assertEquals(OperationEventType.IDENTIFICATION_COMPLETE, testEventHandler.waitForEvent().getEventType()); addStep("Verify that the client continues to the performing phase.", "A REQUEST_SENT event should be generated and a OperationRequest should be sent only to contributor2" + "."); checkNoRequestIsReceived(pillar1Receiver); MessageRequest request = waitForRequest(pillar2Receiver); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.REQUEST_SENT); + assertEquals(OperationEventType.REQUEST_SENT, testEventHandler.waitForEvent().getEventType()); addStep("Send a final response message from contributor2", "A COMPONENT_COMPLETE event should be generated followed by at COMPLETE event."); MessageResponse completeMsg = createFinalResponse(request, PILLAR2_ID, pillar2DestinationId); completeMsg.getResponseInfo().setResponseCode(ResponseCode.OPERATION_COMPLETED); messageBus.sendMessage(completeMsg); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.COMPONENT_COMPLETE); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.FAILED); + assertEquals(OperationEventType.COMPONENT_COMPLETE, testEventHandler.waitForEvent().getEventType()); + assertEquals(OperationEventType.FAILED, testEventHandler.waitForEvent().getEventType()); } - @Test(groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public void identificationFailureTest() throws Exception { addDescription("Verify that the client works correctly when a contributor sends a failure response."); @@ -99,14 +103,14 @@ public void identificationFailureTest() throws Exception { "A IDENTIFY_REQUEST_SENT should be generate and a identification request should be sent."); startOperation(testEventHandler); MessageRequest identifyRequest = waitForIdentifyRequest(); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.IDENTIFY_REQUEST_SENT); + assertEquals(OperationEventType.IDENTIFY_REQUEST_SENT, testEventHandler.waitForEvent().getEventType()); addStep("Send a identification response from contributor1 with a FAILURE response code.", "A component failed event should be generated."); MessageResponse identifyResponse1 = createIdentifyResponse(identifyRequest, PILLAR1_ID, pillar1DestinationId); identifyResponse1.getResponseInfo().setResponseCode(ResponseCode.FAILURE); messageBus.sendMessage(identifyResponse1); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.COMPONENT_FAILED); + assertEquals(OperationEventType.COMPONENT_FAILED, testEventHandler.waitForEvent().getEventType()); addStep("Send a identification response from contributor2 with a IDENTIFICATION_POSITIVE response code .", "A component COMPONENT_IDENTIFIED event should be generated followed by a IDENTIFICATION_COMPLETE."); @@ -114,25 +118,26 @@ public void identificationFailureTest() throws Exception { identifyRequest, PILLAR2_ID, pillar2DestinationId); identifyResponse2.getResponseInfo().setResponseCode(ResponseCode.IDENTIFICATION_POSITIVE); messageBus.sendMessage(identifyResponse2); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.COMPONENT_IDENTIFIED); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.IDENTIFICATION_COMPLETE); + assertEquals(OperationEventType.COMPONENT_IDENTIFIED, testEventHandler.waitForEvent().getEventType()); + assertEquals(OperationEventType.IDENTIFICATION_COMPLETE, testEventHandler.waitForEvent().getEventType()); addStep("Verify that the client continues to the performing phase.", "A REQUEST_SENT event should be generated and a Request should be sent only to contributor2."); checkNoRequestIsReceived(pillar1Receiver); MessageRequest request = waitForRequest(pillar2Receiver); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.REQUEST_SENT); + assertEquals(OperationEventType.REQUEST_SENT, testEventHandler.waitForEvent().getEventType()); addStep("Send a final response message from contributor2", "A COMPONENT_COMPLETE event should be generated followed by at COMPLETE event."); MessageResponse completeMsg = createFinalResponse(request, PILLAR2_ID, pillar2DestinationId); completeMsg.getResponseInfo().setResponseCode(ResponseCode.OPERATION_COMPLETED); messageBus.sendMessage(completeMsg); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.COMPONENT_COMPLETE); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.FAILED); + assertEquals(OperationEventType.COMPONENT_COMPLETE, testEventHandler.waitForEvent().getEventType()); + assertEquals(OperationEventType.FAILED, testEventHandler.waitForEvent().getEventType()); } - @Test(groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public void oneContributorNotRespondingTest() throws Exception { addDescription("Verify that the client works correct without receiving identification responses from all " + "contributors."); @@ -144,36 +149,37 @@ public void oneContributorNotRespondingTest() throws Exception { "A IDENTIFY_REQUEST_SENT should be generate and a identification request should be sent."); startOperation(testEventHandler); MessageRequest identifyRequest = waitForIdentifyRequest(); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.IDENTIFY_REQUEST_SENT); + assertEquals(OperationEventType.IDENTIFY_REQUEST_SENT, testEventHandler.waitForEvent().getEventType()); addStep("Send a identification response from contributor1.", "A COMPONENT_IDENTIFIED event should be generated."); MessageResponse identifyResponse1 = createIdentifyResponse(identifyRequest, PILLAR1_ID, pillar1DestinationId); identifyResponse1.getResponseInfo().setResponseCode(ResponseCode.IDENTIFICATION_POSITIVE); messageBus.sendMessage(identifyResponse1); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.COMPONENT_IDENTIFIED); + assertEquals(OperationEventType.COMPONENT_IDENTIFIED, testEventHandler.waitForEvent().getEventType()); addStep("Wait 1 second.", "A IDENTIFY_TIMEOUT event should be generated, followed by a IDENTIFICATION_COMPLETE."); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.IDENTIFY_TIMEOUT); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.COMPONENT_FAILED); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.IDENTIFICATION_COMPLETE); + assertEquals(OperationEventType.IDENTIFY_TIMEOUT, testEventHandler.waitForEvent().getEventType()); + assertEquals(OperationEventType.COMPONENT_FAILED, testEventHandler.waitForEvent().getEventType()); + assertEquals(OperationEventType.IDENTIFICATION_COMPLETE, testEventHandler.waitForEvent().getEventType()); addStep("Verify that the client continues to the performing phase.", "A REQUEST_SENT event should be generated and a Request should be sent to pillar1."); MessageRequest request = waitForRequest(pillar1Receiver); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.REQUEST_SENT); + assertEquals(OperationEventType.REQUEST_SENT, testEventHandler.waitForEvent().getEventType()); addStep("Send a final response upload message", "A COMPONENT_COMPLETE event should be generated followed by at COMPLETE event."); MessageResponse completeMsg = createFinalResponse(request, PILLAR1_ID, pillar1DestinationId); completeMsg.getResponseInfo().setResponseCode(ResponseCode.OPERATION_COMPLETED); messageBus.sendMessage(completeMsg); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.COMPONENT_COMPLETE); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.FAILED); + assertEquals(OperationEventType.COMPONENT_COMPLETE, testEventHandler.waitForEvent().getEventType()); + assertEquals(OperationEventType.FAILED, testEventHandler.waitForEvent().getEventType()); } - @Test(groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public void noContributorsRespondingTest() throws Exception { addDescription("Tests the the client handles lack of a IdentifyResponse gracefully. " + "More concrete this means that the occurrence of a identification timeout should be handled correctly"); @@ -184,17 +190,18 @@ public void noContributorsRespondingTest() throws Exception { addStep("Start the operation.", "A IDENTIFY_REQUEST_SENT event should be generated."); startOperation(testEventHandler); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.IDENTIFY_REQUEST_SENT); + assertEquals(OperationEventType.IDENTIFY_REQUEST_SENT, testEventHandler.waitForEvent().getEventType()); addStep("Wait for 1 second", "An IdentifyPillarTimeout event should be received followed by a FAILED event"); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.IDENTIFY_TIMEOUT); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.COMPONENT_FAILED); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.COMPONENT_FAILED); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.FAILED); + assertEquals(OperationEventType.IDENTIFY_TIMEOUT, testEventHandler.waitForEvent().getEventType()); + assertEquals(OperationEventType.COMPONENT_FAILED, testEventHandler.waitForEvent().getEventType()); + assertEquals(OperationEventType.COMPONENT_FAILED, testEventHandler.waitForEvent().getEventType()); + assertEquals(OperationEventType.FAILED, testEventHandler.waitForEvent().getEventType()); } - @Test(groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public void operationTimeoutTest() throws Exception { addDescription("Tests the the client handles lack of final responses gracefully."); @@ -205,30 +212,31 @@ public void operationTimeoutTest() throws Exception { addStep("Start the operation", "A IDENTIFY_REQUEST_SENT event should be received."); startOperation(testEventHandler); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.IDENTIFY_REQUEST_SENT); + assertEquals(OperationEventType.IDENTIFY_REQUEST_SENT, testEventHandler.waitForEvent().getEventType()); MessageRequest identifyRequest = waitForIdentifyRequest(); addStep("Send positive responses from the pillar1 and a negative response from pillar2", "A COMPONENT_IDENTIFIED + a " + - "event should be generated followed by a IDENTIFICATION_COMPLETE.

" + - "Finally a operation request should be sent to pillar1 and a REQUEST_SENT event be " + - "generated"); + "event should be generated followed by a IDENTIFICATION_COMPLETE.

" + + "Finally a operation request should be sent to pillar1 and a REQUEST_SENT event be " + + "generated"); messageBus.sendMessage(createIdentifyResponse(identifyRequest, PILLAR1_ID, pillar1DestinationId)); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.COMPONENT_IDENTIFIED); + assertEquals(OperationEventType.COMPONENT_IDENTIFIED, testEventHandler.waitForEvent().getEventType()); MessageResponse identifyResponse2 = createIdentifyResponse(identifyRequest, PILLAR2_ID, pillar2DestinationId); identifyResponse2.getResponseInfo().setResponseCode(ResponseCode.IDENTIFICATION_NEGATIVE); messageBus.sendMessage(identifyResponse2); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.COMPONENT_FAILED); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.IDENTIFICATION_COMPLETE); + assertEquals(OperationEventType.COMPONENT_FAILED, testEventHandler.waitForEvent().getEventType()); + assertEquals(OperationEventType.IDENTIFICATION_COMPLETE, testEventHandler.waitForEvent().getEventType()); waitForRequest(pillar1Receiver); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.REQUEST_SENT); + assertEquals(OperationEventType.REQUEST_SENT, testEventHandler.waitForEvent().getEventType()); addStep("Wait for 1 second", "An FAILED event should be received"); - assertEquals(testEventHandler.waitForEvent().getEventType(), - OperationEventType.FAILED); + assertEquals(OperationEventType.FAILED, + testEventHandler.waitForEvent().getEventType()); } - - @Test(groups = {"regressiontest"}) + + @Test + @Tag("regressiontest") public void collectionIDIncludedInEventsTest() throws Exception { addDescription("Tests the the client provides collectionID in events."); @@ -238,48 +246,49 @@ public void collectionIDIncludedInEventsTest() throws Exception { addStep("Start the operation", "A IDENTIFY_REQUEST_SENT event should be received."); startOperation(testEventHandler); - + OperationEvent event1 = testEventHandler.waitForEvent(); - assertEquals(event1.getEventType(), OperationEventType.IDENTIFY_REQUEST_SENT); + assertEquals(OperationEventType.IDENTIFY_REQUEST_SENT, event1.getEventType()); assertEquals(event1.getCollectionID(), collectionID); MessageRequest identifyRequest = waitForIdentifyRequest(); addStep("Send positive responses from the pillar1 and a negative response from pillar2", "A COMPONENT_IDENTIFIED + a " + - "event should be generated followed by a IDENTIFICATION_COMPLETE.

" + - "Finally a operation request should be sent to pillar1 and a REQUEST_SENT event be " + - "generated"); + "event should be generated followed by a IDENTIFICATION_COMPLETE.

" + + "Finally a operation request should be sent to pillar1 and a REQUEST_SENT event be " + + "generated"); messageBus.sendMessage(createIdentifyResponse(identifyRequest, PILLAR1_ID, pillar1DestinationId)); - + OperationEvent event2 = testEventHandler.waitForEvent(); - assertEquals(event2.getEventType(), OperationEventType.COMPONENT_IDENTIFIED); + assertEquals(OperationEventType.COMPONENT_IDENTIFIED, event2.getEventType()); assertEquals(event2.getCollectionID(), collectionID); - + MessageResponse identifyResponse2 = createIdentifyResponse(identifyRequest, PILLAR2_ID, pillar2DestinationId); identifyResponse2.getResponseInfo().setResponseCode(ResponseCode.IDENTIFICATION_NEGATIVE); messageBus.sendMessage(identifyResponse2); - + OperationEvent event3 = testEventHandler.waitForEvent(); - assertEquals(event3.getEventType(), OperationEventType.COMPONENT_FAILED); + assertEquals(OperationEventType.COMPONENT_FAILED, event3.getEventType()); assertEquals(event3.getCollectionID(), collectionID); - + OperationEvent event4 = testEventHandler.waitForEvent(); - assertEquals(event4.getEventType(), OperationEventType.IDENTIFICATION_COMPLETE); + assertEquals(OperationEventType.IDENTIFICATION_COMPLETE, event4.getEventType()); assertEquals(event4.getCollectionID(), collectionID); - + waitForRequest(pillar1Receiver); - + OperationEvent event5 = testEventHandler.waitForEvent(); - assertEquals(event5.getEventType(), OperationEventType.REQUEST_SENT); + assertEquals(OperationEventType.REQUEST_SENT, event5.getEventType()); assertEquals(event5.getCollectionID(), collectionID); addStep("Wait for 1 second", "An FAILED event should be received"); OperationEvent event6 = testEventHandler.waitForEvent(); - assertEquals(event6.getEventType(), OperationEventType.FAILED); + assertEquals(OperationEventType.FAILED, event6.getEventType()); assertEquals(event6.getCollectionID(), collectionID); - } + } - @Test(groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public void conversationTimeoutTest() throws Exception { addDescription("Tests the the client handles lack of IdentifyPillarResponses gracefully "); @@ -292,19 +301,24 @@ public void conversationTimeoutTest() throws Exception { addStep("Start the operation", "A IDENTIFY_REQUEST_SENT event should be generated followed by a FAILED event after 100 ms."); startOperation(testEventHandler); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.IDENTIFY_REQUEST_SENT); + assertEquals(OperationEventType.IDENTIFY_REQUEST_SENT, testEventHandler.waitForEvent().getEventType()); assertNotNull(waitForIdentifyRequest()); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.FAILED); + assertEquals(OperationEventType.FAILED, testEventHandler.waitForEvent().getEventType()); } protected abstract MessageResponse createIdentifyResponse(MessageRequest identifyRequest, String from, String to); + protected abstract MessageResponse createFinalResponse(MessageRequest request, String from, String to); protected abstract MessageRequest waitForIdentifyRequest(); + protected abstract MessageRequest waitForRequest(MessageReceiver receiver); + protected abstract void checkNoRequestIsReceived(MessageReceiver receiver); - /** Makes a default call to the client for the operation */ + /** + * Makes a default call to the client for the operation + */ protected abstract void startOperation(TestEventHandler testEventHandler); } diff --git a/bitrepository-client/src/test/java/org/bitrepository/client/TestEventHandler.java b/bitrepository-client/src/test/java/org/bitrepository/client/TestEventHandler.java index f8cb988d3..f1728c28d 100644 --- a/bitrepository-client/src/test/java/org/bitrepository/client/TestEventHandler.java +++ b/bitrepository-client/src/test/java/org/bitrepository/client/TestEventHandler.java @@ -32,7 +32,8 @@ import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; -import static org.testng.Assert.assertNull; +import static org.junit.jupiter.api.Assertions.assertNull; + /** Used to listen for operation event and store them for later retrieval by a test. */ public class TestEventHandler implements EventHandler { diff --git a/bitrepository-client/src/test/java/org/bitrepository/client/conversation/mediator/CollectionBasedConversationMediatorTest.java b/bitrepository-client/src/test/java/org/bitrepository/client/conversation/mediator/CollectionBasedConversationMediatorTest.java index c1ecc5073..19aae9332 100644 --- a/bitrepository-client/src/test/java/org/bitrepository/client/conversation/mediator/CollectionBasedConversationMediatorTest.java +++ b/bitrepository-client/src/test/java/org/bitrepository/client/conversation/mediator/CollectionBasedConversationMediatorTest.java @@ -25,9 +25,7 @@ package org.bitrepository.client.conversation.mediator; import org.bitrepository.common.settings.Settings; -import org.testng.annotations.Test; -@Test public class CollectionBasedConversationMediatorTest extends ConversationMediatorTest { @Override diff --git a/bitrepository-client/src/test/java/org/bitrepository/client/conversation/mediator/ConversationMediatorTest.java b/bitrepository-client/src/test/java/org/bitrepository/client/conversation/mediator/ConversationMediatorTest.java index f5b757094..3cccff5a9 100644 --- a/bitrepository-client/src/test/java/org/bitrepository/client/conversation/mediator/ConversationMediatorTest.java +++ b/bitrepository-client/src/test/java/org/bitrepository/client/conversation/mediator/ConversationMediatorTest.java @@ -31,12 +31,13 @@ import org.bitrepository.protocol.MessageContext; import org.bitrepository.protocol.security.DummySecurityManager; import org.bitrepository.protocol.security.SecurityManager; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + /** * Test the general ConversationMediator functionality. */ -@Test public abstract class ConversationMediatorTest { protected Settings settings = TestSettingsProvider.getSettings(getClass().getSimpleName()); protected SecurityManager securityManager = new DummySecurityManager(); @@ -45,7 +46,8 @@ public abstract class ConversationMediatorTest { * Validates the core mediator functionality of delegating messages from the message bus to the relevant * conversation. */ - @Test (groups = {"testfirst"}) + @Test + @Tag("testfirst") public void messagedelegationTest() { ConversationMediator mediator = createMediator(settings); @@ -57,9 +59,9 @@ public void messagedelegationTest() { @SuppressWarnings("unused") private class ConversationStub extends StateBasedConversation { private boolean hasStarted = false; - private boolean hasFailed = false; - private boolean hasEnded = false; - private Object result = null; + private final boolean hasFailed = false; + private final boolean hasEnded = false; + private final Object result = null; public ConversationStub() { super(null); diff --git a/bitrepository-client/src/test/java/org/bitrepository/client/exception/NegativeResponseExceptionTest.java b/bitrepository-client/src/test/java/org/bitrepository/client/exception/NegativeResponseExceptionTest.java index b99f6ec45..87bef14a6 100644 --- a/bitrepository-client/src/test/java/org/bitrepository/client/exception/NegativeResponseExceptionTest.java +++ b/bitrepository-client/src/test/java/org/bitrepository/client/exception/NegativeResponseExceptionTest.java @@ -24,12 +24,15 @@ import org.bitrepository.bitrepositoryelements.ResponseCode; import org.bitrepository.client.exceptions.NegativeResponseException; import org.jaccept.structure.ExtendedTestCase; -import org.testng.Assert; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + public class NegativeResponseExceptionTest extends ExtendedTestCase { - @Test(groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public void testNegativeResponse() { addDescription("Test the instantiation of the exception"); addStep("Setup", ""); @@ -41,10 +44,10 @@ public void testNegativeResponse() { try { throw new NegativeResponseException(errMsg, responseCode); } catch (Exception e) { - Assert.assertTrue(e instanceof NegativeResponseException); - Assert.assertEquals(e.getMessage(), errMsg); - Assert.assertEquals(((NegativeResponseException) e).getErrorCode(), responseCode); - Assert.assertNull(e.getCause()); + Assertions.assertInstanceOf(NegativeResponseException.class, e); + Assertions.assertEquals(errMsg, e.getMessage()); + Assertions.assertEquals(responseCode, ((NegativeResponseException) e).getErrorCode()); + Assertions.assertNull(e.getCause()); } } } diff --git a/bitrepository-client/src/test/java/org/bitrepository/client/exception/UnexpectedResponseExceptionTest.java b/bitrepository-client/src/test/java/org/bitrepository/client/exception/UnexpectedResponseExceptionTest.java index b9c7e0f1f..5fe3eb135 100644 --- a/bitrepository-client/src/test/java/org/bitrepository/client/exception/UnexpectedResponseExceptionTest.java +++ b/bitrepository-client/src/test/java/org/bitrepository/client/exception/UnexpectedResponseExceptionTest.java @@ -5,16 +5,16 @@ * Copyright (C) 2010 - 2012 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% @@ -23,36 +23,39 @@ import org.bitrepository.client.exceptions.UnexpectedResponseException; import org.jaccept.structure.ExtendedTestCase; -import org.testng.Assert; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + public class UnexpectedResponseExceptionTest extends ExtendedTestCase { - - @Test(groups = { "regressiontest" }) + + @Test + @Tag("regressiontest") public void testUnexpectedResponse() throws Exception { addDescription("Test the instantiation of the exception"); addStep("Setup", ""); String errMsg = "TEST-ERROR"; String causeMsg = "CAUSE-EXCEPTION"; - + addStep("Try to throw such an exception", "Should be able to be caught and validated"); try { throw new UnexpectedResponseException(errMsg); - } catch(Exception e) { - Assert.assertTrue(e instanceof UnexpectedResponseException); - Assert.assertEquals(e.getMessage(), errMsg); - Assert.assertNull(e.getCause()); + } catch (Exception e) { + Assertions.assertInstanceOf(UnexpectedResponseException.class, e); + Assertions.assertEquals(errMsg, e.getMessage()); + Assertions.assertNull(e.getCause()); } - + addStep("Throw the exception with an embedded exception", "The embedded exception should be the same."); try { throw new UnexpectedResponseException(errMsg, new IllegalArgumentException(causeMsg)); - } catch(Exception e) { - Assert.assertTrue(e instanceof UnexpectedResponseException); - Assert.assertEquals(e.getMessage(), errMsg); - Assert.assertNotNull(e.getCause()); - Assert.assertTrue(e.getCause() instanceof IllegalArgumentException); - Assert.assertEquals(e.getCause().getMessage(), causeMsg); + } catch (Exception e) { + Assertions.assertInstanceOf(UnexpectedResponseException.class, e); + Assertions.assertEquals(errMsg, e.getMessage()); + Assertions.assertNotNull(e.getCause()); + Assertions.assertInstanceOf(IllegalArgumentException.class, e.getCause()); + Assertions.assertEquals(causeMsg, e.getCause().getMessage()); } } } diff --git a/bitrepository-client/src/test/java/org/bitrepository/commandline/CommandLineTest.java b/bitrepository-client/src/test/java/org/bitrepository/commandline/CommandLineTest.java index be7a3ac5d..731774fca 100644 --- a/bitrepository-client/src/test/java/org/bitrepository/commandline/CommandLineTest.java +++ b/bitrepository-client/src/test/java/org/bitrepository/commandline/CommandLineTest.java @@ -5,16 +5,16 @@ * Copyright (C) 2010 - 2012 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% @@ -24,46 +24,56 @@ import org.apache.commons.cli.Option; import org.bitrepository.commandline.utils.CommandLineArgumentsHandler; import org.jaccept.structure.ExtendedTestCase; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertNotNull; -import static org.testng.Assert.assertTrue; public class CommandLineTest extends ExtendedTestCase { private static final String SETTINGS_DIR = "SettingsDir"; private static final String KEY_FILE = "KeyFile"; private static final String DUMMY_DATA = "DummyData"; - @Test(groups = { "regressiontest" }, expectedExceptions = Exception.class) + @Test + @Tag("regressiontest") public void argumentsTesterUnknownArgument() throws Exception { - addDescription("Test the handling of arguments by the CommandLineArgumentHandler."); - CommandLineArgumentsHandler clah = new CommandLineArgumentsHandler(); + assertThrows(Exception.class, () -> { + addDescription("Test the handling of arguments by the CommandLineArgumentHandler."); + CommandLineArgumentsHandler clah = new CommandLineArgumentsHandler(); - addStep("Validate arguments without any options.", "Ok, when no arguments, but fails when arguments given."); - clah.parseArguments(new String[0]); + addStep("Validate arguments without any options.", "Ok, when no arguments, but fails when arguments given."); + clah.parseArguments(); - clah.parseArguments("-Xunknown..."); + clah.parseArguments("-Xunknown..."); + }); } - @Test(groups = { "regressiontest" }, expectedExceptions = Exception.class) + @Test + @Tag("regressiontest") public void argumentsTesterWrongArgument() throws Exception { - addDescription("Test the handling of arguments by the CommandLineArgumentHandler."); - CommandLineArgumentsHandler clah = new CommandLineArgumentsHandler(); + assertThrows(Exception.class, () -> { + addDescription("Test the handling of arguments by the CommandLineArgumentHandler."); + CommandLineArgumentsHandler clah = new CommandLineArgumentsHandler(); - addStep("Validate the default options", "Ok, when both given. Fails if either is missing"); - clah = new CommandLineArgumentsHandler(); - clah.createDefaultOptions(); - clah.parseArguments("-s" + SETTINGS_DIR, "-k" + KEY_FILE); - assertEquals(clah.getOptionValue("s"), SETTINGS_DIR); - assertEquals(clah.getOptionValue("k"), KEY_FILE); + addStep("Validate the default options", "Ok, when both given. Fails if either is missing"); + clah = new CommandLineArgumentsHandler(); + clah.createDefaultOptions(); + clah.parseArguments("-s" + SETTINGS_DIR, "-k" + KEY_FILE); + assertEquals(SETTINGS_DIR, clah.getOptionValue("s")); + assertEquals(KEY_FILE, clah.getOptionValue("k")); - clah = new CommandLineArgumentsHandler(); - clah.createDefaultOptions(); - clah.parseArguments(); + clah = new CommandLineArgumentsHandler(); + clah.createDefaultOptions(); + clah.parseArguments(); + }); } - @Test(groups = { "regressiontest" }) + @Test + @Tag("regressiontest") public void newArgumentTester() throws Exception { addDescription("Test the handling of a new argument."); CommandLineArgumentsHandler clah = new CommandLineArgumentsHandler(); @@ -75,7 +85,7 @@ public void newArgumentTester() throws Exception { clah.parseArguments("-" + argName + DUMMY_DATA); assertTrue(clah.hasOption(argName)); - assertEquals(clah.getOptionValue(argName), DUMMY_DATA); + assertEquals(DUMMY_DATA, clah.getOptionValue(argName)); assertNotNull(clah.listArguments()); } diff --git a/bitrepository-client/src/test/java/org/bitrepository/commandline/DeleteFileCmdTest.java b/bitrepository-client/src/test/java/org/bitrepository/commandline/DeleteFileCmdTest.java index 2ffe6119a..e5e4ee130 100644 --- a/bitrepository-client/src/test/java/org/bitrepository/commandline/DeleteFileCmdTest.java +++ b/bitrepository-client/src/test/java/org/bitrepository/commandline/DeleteFileCmdTest.java @@ -22,11 +22,14 @@ package org.bitrepository.commandline; import org.bitrepository.client.DefaultFixtureClientTest; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; import java.util.Date; +import static org.junit.jupiter.api.Assertions.assertThrows; + public class DeleteFileCmdTest extends DefaultFixtureClientTest { private static final String SETTINGS_DIR = "settings/xml/bitrepository-devel"; private static final String KEY_FILE = "KeyFile"; @@ -34,12 +37,13 @@ public class DeleteFileCmdTest extends DefaultFixtureClientTest { private String DEFAULT_COLLECTION_ID; - @BeforeMethod(alwaysRun = true) + @BeforeEach public void setupClient() throws Exception { DEFAULT_COLLECTION_ID = settingsForTestClient.getCollections().get(0).getID(); } - @Test(groups = { "regressiontest" }) + @Test + @Tag( "regressiontest") public void defaultSuccessScenarioTest() throws Exception { addDescription("Tests simplest arguments for running the CmdLineClient"); String[] args = new String[]{"-s" + SETTINGS_DIR, @@ -51,52 +55,65 @@ public void defaultSuccessScenarioTest() throws Exception { new DeleteFileCmd(args); } - @Test(groups = { "regressiontest" }, expectedExceptions = IllegalArgumentException.class) + @Test + @Tag( "regressiontest") public void missingCollectionArgumentTest() throws Exception { - addDescription("Tests the scenario, where the collection arguments is missing."); - String[] args = new String[]{"-s" + SETTINGS_DIR, - "-k" + KEY_FILE, - "-p" + PILLAR1_ID, - "-C" + DEFAULT_CHECKSUM, - "-i" + DEFAULT_FILE_ID}; - new DeleteFileCmd(args); + assertThrows(IllegalArgumentException.class, () -> { + addDescription("Tests the scenario, where the collection arguments is missing."); + String[] args = new String[]{"-s" + SETTINGS_DIR, + "-k" + KEY_FILE, + "-p" + PILLAR1_ID, + "-C" + DEFAULT_CHECKSUM, + "-i" + DEFAULT_FILE_ID}; + new DeleteFileCmd(args); + }); } - @Test(groups = { "regressiontest" }, expectedExceptions = IllegalArgumentException.class) + @Test + @Tag( "regressiontest") public void missingPillarArgumentTest() throws Exception { - addDescription("Tests the different scenarios, with the pillar argument."); - String[] args = new String[]{"-s" + SETTINGS_DIR, - "-k" + KEY_FILE, - "-C" + DEFAULT_CHECKSUM, - "-c" + DEFAULT_COLLECTION_ID, - "-i" + DEFAULT_FILE_ID}; - new DeleteFileCmd(args); + assertThrows(IllegalArgumentException.class, () -> { + addDescription("Tests the different scenarios, with the pillar argument."); + String[] args = new String[]{"-s" + SETTINGS_DIR, + "-k" + KEY_FILE, + "-C" + DEFAULT_CHECKSUM, + "-c" + DEFAULT_COLLECTION_ID, + "-i" + DEFAULT_FILE_ID}; + new DeleteFileCmd(args); + }); } - @Test(groups = { "regressiontest" }, expectedExceptions = IllegalArgumentException.class) + @Test + @Tag( "regressiontest") public void unknownPillarArgumentTest() throws Exception { - addStep("Testing against a non-existing pillar id", "Should fail"); - String[] args = new String[]{"-s" + SETTINGS_DIR, - "-k" + KEY_FILE, - "-C" + DEFAULT_CHECKSUM, - "-c" + DEFAULT_COLLECTION_ID, - "-p" + "Random" + (new Date()).getTime() + "pillar", - "-i" + DEFAULT_FILE_ID}; - new DeleteFileCmd(args); + assertThrows(IllegalArgumentException.class, () -> { + addStep("Testing against a non-existing pillar id", "Should fail"); + String[] args = new String[]{"-s" + SETTINGS_DIR, + "-k" + KEY_FILE, + "-C" + DEFAULT_CHECKSUM, + "-c" + DEFAULT_COLLECTION_ID, + "-p" + "Random" + (new Date()).getTime() + "pillar", + "-i" + DEFAULT_FILE_ID}; + new DeleteFileCmd(args); + }); } - @Test(groups = { "regressiontest" }, expectedExceptions = IllegalArgumentException.class) + @Test + @Tag( "regressiontest") public void missingFileIDArgumentTest() throws Exception { - addDescription("Tests the scenario, where no arguments for file id argument is given."); - String[] args = new String[]{"-s" + SETTINGS_DIR, - "-k" + KEY_FILE, - "-p" + PILLAR1_ID, - "-c" + DEFAULT_COLLECTION_ID, - "-C" + DEFAULT_CHECKSUM}; - new DeleteFileCmd(args); + assertThrows(IllegalArgumentException.class, () -> { + addDescription("Tests the scenario, where no arguments for file id argument is given."); + String[] args = new String[]{"-s" + SETTINGS_DIR, + "-k" + KEY_FILE, + "-p" + PILLAR1_ID, + "-c" + DEFAULT_COLLECTION_ID, + "-C" + DEFAULT_CHECKSUM}; + new DeleteFileCmd(args); + }); } - @Test(groups = { "regressiontest" }) + @Test + @Tag( "regressiontest") public void checksumArgumentNonSaltAlgorithmWitoutSaltTest() throws Exception { addDescription("Test MD5 checksum without salt -> no failure"); String[] args = new String[]{"-s" + SETTINGS_DIR, @@ -109,7 +126,8 @@ public void checksumArgumentNonSaltAlgorithmWitoutSaltTest() throws Exception { new DeleteFileCmd(args); } - @Test(groups = { "regressiontest" }) + @Test + @Tag( "regressiontest") public void checksumArgumentSaltAlgorithmWithSaltTest() throws Exception { addDescription("Test HMAC_SHA256 checksum with salt -> No failure"); String[] args = new String[]{"-s" + SETTINGS_DIR, diff --git a/bitrepository-client/src/test/java/org/bitrepository/commandline/GetChecksumsCmdTest.java b/bitrepository-client/src/test/java/org/bitrepository/commandline/GetChecksumsCmdTest.java index 300fa7aa1..2b097a6af 100644 --- a/bitrepository-client/src/test/java/org/bitrepository/commandline/GetChecksumsCmdTest.java +++ b/bitrepository-client/src/test/java/org/bitrepository/commandline/GetChecksumsCmdTest.java @@ -5,16 +5,16 @@ * Copyright (C) 2010 - 2012 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% @@ -22,44 +22,52 @@ package org.bitrepository.commandline; import org.bitrepository.client.DefaultFixtureClientTest; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; import java.util.Date; +import static org.junit.jupiter.api.Assertions.assertThrows; + public class GetChecksumsCmdTest extends DefaultFixtureClientTest { private static final String SETTINGS_DIR = "settings/xml/bitrepository-devel"; private static final String KEY_FILE = "KeyFile"; private String DEFAULT_COLLECTION_ID; - @BeforeMethod(alwaysRun = true) + @BeforeEach public void setupClient() throws Exception { DEFAULT_COLLECTION_ID = settingsForTestClient.getCollections().get(0).getID(); } - @Test(groups = { "regressiontest" }) + @Test + @Tag("regressiontest") public void defaultSuccessScenarioTest() throws Exception { addDescription("Tests simplest arguments for running the CmdLineClient"); - String[] args = new String[]{"-s" + SETTINGS_DIR, + String[] args = new String[]{"-s" + SETTINGS_DIR, "-k" + KEY_FILE, "-c" + DEFAULT_COLLECTION_ID}; new GetChecksumsCmd(args); } - @Test(groups = { "regressiontest" }, expectedExceptions = IllegalArgumentException.class) + @Test + @Tag("regressiontest") public void missingCollectionArgumentTest() throws Exception { - addDescription("Tests the scenario, where the collection arguments is missing."); - String[] args = new String[]{"-s" + SETTINGS_DIR, - "-k" + KEY_FILE, - "-i" + DEFAULT_FILE_ID}; - new GetChecksumsCmd(args); + assertThrows(IllegalArgumentException.class, () -> { + addDescription("Tests the scenario, where the collection arguments is missing."); + String[] args = new String[]{"-s" + SETTINGS_DIR, + "-k" + KEY_FILE, + "-i" + DEFAULT_FILE_ID}; + new GetChecksumsCmd(args); + }); } - @Test(groups = { "regressiontest" }) + @Test + @Tag("regressiontest") public void specificPillarArgumentTest() throws Exception { addDescription("Test argument for a specific pillar"); - String[] args = new String[]{"-s" + SETTINGS_DIR, + String[] args = new String[]{"-s" + SETTINGS_DIR, "-k" + KEY_FILE, "-c" + DEFAULT_COLLECTION_ID, "-p" + PILLAR1_ID, @@ -67,45 +75,51 @@ public void specificPillarArgumentTest() throws Exception { new GetChecksumsCmd(args); } - @Test(groups = { "regressiontest" }, expectedExceptions = IllegalArgumentException.class) + @Test + @Tag("regressiontest") public void unknownPillarArgumentTest() throws Exception { - addDescription("Testing against a non-existing pillar id -> Should fail"); - String[] args = new String[]{"-s" + SETTINGS_DIR, - "-k" + KEY_FILE, - "-c" + DEFAULT_COLLECTION_ID, - "-p" + "Random" + (new Date()).getTime() + "pillar", - "-i" + DEFAULT_FILE_ID}; + assertThrows(IllegalArgumentException.class, () -> { + addDescription("Testing against a non-existing pillar id -> Should fail"); + String[] args = new String[]{"-s" + SETTINGS_DIR, + "-k" + KEY_FILE, + "-c" + DEFAULT_COLLECTION_ID, + "-p" + "Random" + (new Date()).getTime() + "pillar", + "-i" + DEFAULT_FILE_ID}; - new GetChecksumsCmd(args); + new GetChecksumsCmd(args); + }); } - @Test(groups = { "regressiontest" }) + @Test + @Tag("regressiontest") public void fileArgumentTest() throws Exception { addDescription("Tests the argument for a specific file."); - String[] args = new String[]{"-s" + SETTINGS_DIR, + String[] args = new String[]{"-s" + SETTINGS_DIR, "-k" + KEY_FILE, "-c" + DEFAULT_COLLECTION_ID, "-i" + DEFAULT_FILE_ID}; new GetChecksumsCmd(args); } - @Test(groups = { "regressiontest" }) + @Test + @Tag("regressiontest") public void checksumArgumentNonSaltAlgorithmWitoutSaltTest() throws Exception { addDescription("Test MD5 checksum without salt -> no failure"); - String[] args = new String[]{"-s" + SETTINGS_DIR, + String[] args = new String[]{"-s" + SETTINGS_DIR, "-k" + KEY_FILE, - "-c" + DEFAULT_COLLECTION_ID, + "-c" + DEFAULT_COLLECTION_ID, "-i" + DEFAULT_FILE_ID, "-R" + "MD5"}; new GetChecksumsCmd(args); } - @Test(groups = { "regressiontest" }) + @Test + @Tag("regressiontest") public void checksumArgumentSaltAlgorithmWithSaltTest() throws Exception { addDescription("Test HMAC_SHA256 checksum with salt -> No failure"); - String[] args = new String[]{"-s" + SETTINGS_DIR, + String[] args = new String[]{"-s" + SETTINGS_DIR, "-k" + KEY_FILE, - "-c" + DEFAULT_COLLECTION_ID, + "-c" + DEFAULT_COLLECTION_ID, "-i" + DEFAULT_FILE_ID, "-R" + "HMAC_SHA256", "-S" + "SALT"}; diff --git a/bitrepository-client/src/test/java/org/bitrepository/commandline/GetFileCmdTest.java b/bitrepository-client/src/test/java/org/bitrepository/commandline/GetFileCmdTest.java index 13443cfbd..075430613 100644 --- a/bitrepository-client/src/test/java/org/bitrepository/commandline/GetFileCmdTest.java +++ b/bitrepository-client/src/test/java/org/bitrepository/commandline/GetFileCmdTest.java @@ -22,23 +22,27 @@ package org.bitrepository.commandline; import org.bitrepository.client.DefaultFixtureClientTest; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; import java.util.Date; +import static org.junit.jupiter.api.Assertions.assertThrows; + public class GetFileCmdTest extends DefaultFixtureClientTest { private static final String SETTINGS_DIR = "settings/xml/bitrepository-devel"; private static final String KEY_FILE = "KeyFile"; private String DEFAULT_COLLECTION_ID; - @BeforeMethod(alwaysRun = true) + @BeforeEach public void setupClient() throws Exception { DEFAULT_COLLECTION_ID = settingsForTestClient.getCollections().get(0).getID(); } - @Test(groups = { "regressiontest" }) + @Test + @Tag( "regressiontest") public void defaultSuccessScenarioTest() throws Exception { addDescription("Tests simplest arguments for running the CmdLineClient"); String[] args = new String[]{"-s" + SETTINGS_DIR, @@ -48,16 +52,20 @@ public void defaultSuccessScenarioTest() throws Exception { new GetFileCmd(args); } - @Test(groups = { "regressiontest" }, expectedExceptions = IllegalArgumentException.class) + @Test + @Tag( "regressiontest") public void missingCollectionArgumentTest() throws Exception { - addDescription("Tests the scenario, where the collection arguments is missing."); - String[] args = new String[]{"-s" + SETTINGS_DIR, - "-k" + KEY_FILE, - "-i" + DEFAULT_FILE_ID}; - new GetFileCmd(args); + assertThrows(IllegalArgumentException.class, () -> { + addDescription("Tests the scenario, where the collection arguments is missing."); + String[] args = new String[]{"-s" + SETTINGS_DIR, + "-k" + KEY_FILE, + "-i" + DEFAULT_FILE_ID}; + new GetFileCmd(args); + }); } - @Test(groups = { "regressiontest" }) + @Test + @Tag( "regressiontest" ) public void specificPillarArgumentTest() throws Exception { addDescription("Test argument for a specific pillar"); String[] args = new String[]{"-s" + SETTINGS_DIR, @@ -68,23 +76,29 @@ public void specificPillarArgumentTest() throws Exception { new GetFileCmd(args); } - @Test(groups = { "regressiontest" }, expectedExceptions = IllegalArgumentException.class) + @Test + @Tag( "regressiontest") public void unknownPillarArgumentTest() throws Exception { - addDescription("Testing against a non-existing pillar id -> Should fail"); - String[] args = new String[]{"-s" + SETTINGS_DIR, - "-k" + KEY_FILE, - "-c" + DEFAULT_COLLECTION_ID, - "-p" + "Random" + (new Date()).getTime() + "pillar", - "-i" + DEFAULT_FILE_ID}; - new GetFileCmd(args); + assertThrows(IllegalArgumentException.class, () -> { + addDescription("Testing against a non-existing pillar id -> Should fail"); + String[] args = new String[]{"-s" + SETTINGS_DIR, + "-k" + KEY_FILE, + "-c" + DEFAULT_COLLECTION_ID, + "-p" + "Random" + (new Date()).getTime() + "pillar", + "-i" + DEFAULT_FILE_ID}; + new GetFileCmd(args); + }); } - @Test(groups = { "regressiontest" }, expectedExceptions = IllegalArgumentException.class) + @Test + @Tag( "regressiontest") public void missingFileIDArgumentTest() throws Exception { - addDescription("Tests the scenario, where no arguments for file id argument is given."); - String[] args = new String[]{"-s" + SETTINGS_DIR, - "-k" + KEY_FILE, - "-c" + DEFAULT_COLLECTION_ID}; - new GetFileCmd(args); + assertThrows(IllegalArgumentException.class, () -> { + addDescription("Tests the scenario, where no arguments for file id argument is given."); + String[] args = new String[]{"-s" + SETTINGS_DIR, + "-k" + KEY_FILE, + "-c" + DEFAULT_COLLECTION_ID}; + new GetFileCmd(args); + }); } } diff --git a/bitrepository-client/src/test/java/org/bitrepository/commandline/GetFileIDsCmdTest.java b/bitrepository-client/src/test/java/org/bitrepository/commandline/GetFileIDsCmdTest.java index 8ef5aec53..ef8d6b391 100644 --- a/bitrepository-client/src/test/java/org/bitrepository/commandline/GetFileIDsCmdTest.java +++ b/bitrepository-client/src/test/java/org/bitrepository/commandline/GetFileIDsCmdTest.java @@ -22,23 +22,27 @@ package org.bitrepository.commandline; import org.bitrepository.client.DefaultFixtureClientTest; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; import java.util.Date; +import static org.junit.jupiter.api.Assertions.assertThrows; + public class GetFileIDsCmdTest extends DefaultFixtureClientTest { private static final String SETTINGS_DIR = "settings/xml/bitrepository-devel"; private static final String KEY_FILE = "KeyFile"; private String DEFAULT_COLLECTION_ID; - @BeforeMethod(alwaysRun = true) + @BeforeEach public void setupClient() throws Exception { DEFAULT_COLLECTION_ID = settingsForTestClient.getCollections().get(0).getID(); } - @Test(groups = { "regressiontest" }) + @Test + @Tag( "regressiontest") public void defaultSuccessScenarioTest() throws Exception { addDescription("Tests simplest arguments for running the CmdLineClient"); String[] args = new String[]{"-s" + SETTINGS_DIR, @@ -48,16 +52,20 @@ public void defaultSuccessScenarioTest() throws Exception { } - @Test(groups = { "regressiontest" }, expectedExceptions = IllegalArgumentException.class) + @Test + @Tag( "regressiontest") public void missingCollectionArgumentTest() throws Exception { - addDescription("Tests the scenario, where the collection arguments is missing."); - String[] args = new String[]{"-s" + SETTINGS_DIR, - "-k" + KEY_FILE, - "-i" + DEFAULT_FILE_ID}; - new GetFileIDsCmd(args); + assertThrows(IllegalArgumentException.class, () -> { + addDescription("Tests the scenario, where the collection arguments is missing."); + String[] args = new String[]{"-s" + SETTINGS_DIR, + "-k" + KEY_FILE, + "-i" + DEFAULT_FILE_ID}; + new GetFileIDsCmd(args); + }); } - @Test(groups = { "regressiontest" }) + @Test + @Tag( "regressiontest") public void specificPillarArgumentTest() throws Exception { addDescription("Test argument for a specific pillar"); String[] args = new String[]{"-s" + SETTINGS_DIR, @@ -68,18 +76,22 @@ public void specificPillarArgumentTest() throws Exception { new GetFileIDsCmd(args); } - @Test(groups = { "regressiontest" }, expectedExceptions = IllegalArgumentException.class) + @Test + @Tag( "regressiontest") public void unknownPillarArgumentTest() throws Exception { - addDescription("Testing against a non-existing pillar id -> Should fail"); - String[] args = new String[]{"-s" + SETTINGS_DIR, - "-k" + KEY_FILE, - "-c" + DEFAULT_COLLECTION_ID, - "-p" + "Random" + (new Date()).getTime() + "pillar", - "-i" + DEFAULT_FILE_ID}; - new GetFileIDsCmd(args); + assertThrows(IllegalArgumentException.class, () -> { + addDescription("Testing against a non-existing pillar id -> Should fail"); + String[] args = new String[]{"-s" + SETTINGS_DIR, + "-k" + KEY_FILE, + "-c" + DEFAULT_COLLECTION_ID, + "-p" + "Random" + (new Date()).getTime() + "pillar", + "-i" + DEFAULT_FILE_ID}; + new GetFileIDsCmd(args); + }); } - @Test(groups = { "regressiontest" }) + @Test + @Tag( "regressiontest") public void fileArgumentTest() throws Exception { addDescription("Tests the argument for a specific file."); String[] args = new String[]{"-s" + SETTINGS_DIR, diff --git a/bitrepository-client/src/test/java/org/bitrepository/commandline/PutFileCmdTest.java b/bitrepository-client/src/test/java/org/bitrepository/commandline/PutFileCmdTest.java index 09f429e0a..b63c26372 100644 --- a/bitrepository-client/src/test/java/org/bitrepository/commandline/PutFileCmdTest.java +++ b/bitrepository-client/src/test/java/org/bitrepository/commandline/PutFileCmdTest.java @@ -5,16 +5,16 @@ * Copyright (C) 2010 - 2012 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% @@ -22,10 +22,11 @@ package org.bitrepository.commandline; import org.bitrepository.client.DefaultFixtureClientTest; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; -import java.util.Date; +import static org.junit.jupiter.api.Assertions.assertThrows; public class PutFileCmdTest extends DefaultFixtureClientTest { private static final String SETTINGS_DIR = "settings/xml/bitrepository-devel"; @@ -34,120 +35,138 @@ public class PutFileCmdTest extends DefaultFixtureClientTest { private String DEFAULT_COLLECTION_ID; - @BeforeMethod(alwaysRun = true) + @BeforeEach public void setupClient() throws Exception { DEFAULT_COLLECTION_ID = settingsForTestClient.getCollections().get(0).getID(); } - @Test(groups = { "regressiontest" }) + @Test + @Tag("regressiontest") public void defaultSuccessScenarioTest() throws Exception { addDescription("Tests simplest arguments for running the CmdLineClient"); - String[] args = new String[]{"-s" + SETTINGS_DIR, + String[] args = new String[]{"-s" + SETTINGS_DIR, "-k" + KEY_FILE, "-c" + DEFAULT_COLLECTION_ID, "-f" + DEFAULT_FILE_ID}; new PutFileCmd(args); } - @Test(groups = { "regressiontest" }) + @Test + @Tag("regressiontest") public void urlSuccessScenarioTest() throws Exception { addDescription("Tests arguments for putting a file on a given URL"); - String[] args = new String[]{"-s" + SETTINGS_DIR, + String[] args = new String[]{"-s" + SETTINGS_DIR, "-k" + KEY_FILE, - "-u" + DEFAULT_UPLOAD_FILE_ADDRESS, + "-u" + defaultUploadFileAddress, "-C" + DEFAULT_CHECKSUM, - "-c" + DEFAULT_COLLECTION_ID, + "-c" + DEFAULT_COLLECTION_ID, "-i" + DEFAULT_FILE_ID}; new PutFileCmd(args); } - @Test(groups = { "regressiontest" }, expectedExceptions = IllegalArgumentException.class) + @Test + @Tag("regressiontest") public void missingCollectionArgumentTest() throws Exception { - addDescription("Tests the scenario, where the collection arguments is missing."); - String[] args = new String[]{"-s" + SETTINGS_DIR, - "-k" + KEY_FILE, - "-u" + DEFAULT_UPLOAD_FILE_ADDRESS, - "-C" + DEFAULT_CHECKSUM, - "-i" + DEFAULT_FILE_ID}; - new PutFileCmd(args); + assertThrows(IllegalArgumentException.class, () -> { + addDescription("Tests the scenario, where the collection arguments is missing."); + String[] args = new String[]{"-s" + SETTINGS_DIR, + "-k" + KEY_FILE, + "-u" + defaultUploadFileAddress, + "-C" + DEFAULT_CHECKSUM, + "-i" + DEFAULT_FILE_ID}; + new PutFileCmd(args); + }); } - @Test(groups = { "regressiontest" }, expectedExceptions = IllegalArgumentException.class) + @Test + @Tag("regressiontest") public void missingFileOrURLArgumentTest() throws Exception { - addDescription("Tests the scenario, where no arguments for file or url is given."); - String[] args = new String[]{"-s" + SETTINGS_DIR, - "-k" + KEY_FILE, - "-c" + DEFAULT_COLLECTION_ID, - "-C" + DEFAULT_CHECKSUM, - "-i" + DEFAULT_FILE_ID}; - new PutFileCmd(args); + assertThrows(IllegalArgumentException.class, () -> { + addDescription("Tests the scenario, where no arguments for file or url is given."); + String[] args = new String[]{"-s" + SETTINGS_DIR, + "-k" + KEY_FILE, + "-c" + DEFAULT_COLLECTION_ID, + "-C" + DEFAULT_CHECKSUM, + "-i" + DEFAULT_FILE_ID}; + new PutFileCmd(args); + }); } - @Test(groups = { "regressiontest" }, expectedExceptions = IllegalArgumentException.class) + @Test + @Tag("regressiontest") public void missingChecksumWhenURLArgumentTest() throws Exception { - addDescription("Tests the scenario, where no checksum argument is given, but a URL is given."); - String[] args = new String[]{"-s" + SETTINGS_DIR, - "-k" + KEY_FILE, - "-c" + DEFAULT_COLLECTION_ID, - "-u" + DEFAULT_DOWNLOAD_FILE_ADDRESS, - "-i" + DEFAULT_FILE_ID}; - new PutFileCmd(args); + assertThrows(IllegalArgumentException.class, () -> { + addDescription("Tests the scenario, where no checksum argument is given, but a URL is given."); + String[] args = new String[]{"-s" + SETTINGS_DIR, + "-k" + KEY_FILE, + "-c" + DEFAULT_COLLECTION_ID, + "-u" + defaultDownloadFileAddress, + "-i" + DEFAULT_FILE_ID}; + new PutFileCmd(args); + }); } - @Test(groups = { "regressiontest" }) + @Test + @Tag("regressiontest") public void missingChecksumWhenFileArgumentTest() throws Exception { addDescription("Tests the scenario, where no checksum argument is given, but a file is given."); - String[] args = new String[]{"-s" + SETTINGS_DIR, + String[] args = new String[]{"-s" + SETTINGS_DIR, "-k" + KEY_FILE, - "-c" + DEFAULT_COLLECTION_ID, + "-c" + DEFAULT_COLLECTION_ID, "-f" + DEFAULT_FILE_ID, "-i" + DEFAULT_FILE_ID}; new PutFileCmd(args); } - @Test(groups = { "regressiontest" }, expectedExceptions = IllegalArgumentException.class) + @Test + @Tag("regressiontest") public void missingFileIDWhenURLArgumentTest() throws Exception { - addDescription("Tests the scenario, where no checksum argument is given, but a URL is given."); - String[] args = new String[]{"-s" + SETTINGS_DIR, - "-k" + KEY_FILE, - "-c" + DEFAULT_COLLECTION_ID, - "-C" + DEFAULT_CHECKSUM, - "-u" + DEFAULT_DOWNLOAD_FILE_ADDRESS}; - new PutFileCmd(args); + assertThrows(IllegalArgumentException.class, () -> { + addDescription("Tests the scenario, where no checksum argument is given, but a URL is given."); + String[] args = new String[]{"-s" + SETTINGS_DIR, + "-k" + KEY_FILE, + "-c" + DEFAULT_COLLECTION_ID, + "-C" + DEFAULT_CHECKSUM, + "-u" + defaultDownloadFileAddress}; + new PutFileCmd(args); + }); } - @Test(groups = { "regressiontest" }) + @Test + @Tag("regressiontest") public void missingFileIDWhenFileArgumentTest() throws Exception { addDescription("Tests the scenario, where no checksum argument is given, but a URL is given."); - String[] args = new String[]{"-s" + SETTINGS_DIR, + String[] args = new String[]{"-s" + SETTINGS_DIR, "-k" + KEY_FILE, - "-c" + DEFAULT_COLLECTION_ID, + "-c" + DEFAULT_COLLECTION_ID, "-C" + DEFAULT_CHECKSUM, "-f" + DEFAULT_FILE_ID}; new PutFileCmd(args); } - @Test(groups = { "regressiontest" }) + @Test + @Tag("regressiontest") public void checksumArgumentNonSaltAlgorithmWitoutSaltTest() throws Exception { addDescription("Test MD5 checksum without salt -> no failure"); - String[] args = new String[]{"-s" + SETTINGS_DIR, + String[] args = new String[]{"-s" + SETTINGS_DIR, "-k" + KEY_FILE, - "-u" + DEFAULT_UPLOAD_FILE_ADDRESS, + "-u" + defaultUploadFileAddress, "-C" + DEFAULT_CHECKSUM, - "-c" + DEFAULT_COLLECTION_ID, + "-c" + DEFAULT_COLLECTION_ID, "-i" + DEFAULT_FILE_ID, "-R" + "MD5"}; new PutFileCmd(args); } - @Test(groups = { "regressiontest" }) + @Test + @Tag("regressiontest") public void checksumArgumentSaltAlgorithmWithSaltTest() throws Exception { addDescription("Test HMAC_SHA256 checksum with salt -> No failure"); - String[] args = new String[]{"-s" + SETTINGS_DIR, + String[] args = new String[]{"-s" + SETTINGS_DIR, "-k" + KEY_FILE, - "-u" + DEFAULT_UPLOAD_FILE_ADDRESS, + "-u" + defaultUploadFileAddress, "-C" + DEFAULT_CHECKSUM, - "-c" + DEFAULT_COLLECTION_ID, + "-c" + DEFAULT_COLLECTION_ID, "-i" + DEFAULT_FILE_ID, "-R" + "HMAC_SHA256", "-S" + "SALT"}; diff --git a/bitrepository-client/src/test/java/org/bitrepository/commandline/ReplaceFileCmdTest.java b/bitrepository-client/src/test/java/org/bitrepository/commandline/ReplaceFileCmdTest.java index 843fd12b5..c116e6259 100644 --- a/bitrepository-client/src/test/java/org/bitrepository/commandline/ReplaceFileCmdTest.java +++ b/bitrepository-client/src/test/java/org/bitrepository/commandline/ReplaceFileCmdTest.java @@ -5,16 +5,16 @@ * Copyright (C) 2010 - 2012 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% @@ -22,11 +22,14 @@ package org.bitrepository.commandline; import org.bitrepository.client.DefaultFixtureClientTest; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; import java.util.Date; +import static org.junit.jupiter.api.Assertions.assertThrows; + public class ReplaceFileCmdTest extends DefaultFixtureClientTest { private static final String SETTINGS_DIR = "settings/xml/bitrepository-devel"; private static final String KEY_FILE = "KeyFile"; @@ -34,15 +37,16 @@ public class ReplaceFileCmdTest extends DefaultFixtureClientTest { private String DEFAULT_COLLECTION_ID; - @BeforeMethod(alwaysRun = true) + @BeforeEach public void setupClient() throws Exception { DEFAULT_COLLECTION_ID = settingsForTestClient.getCollections().get(0).getID(); } - @Test(groups = { "regressiontest" }) + @Test + @Tag("regressiontest") public void defaultSuccessScenarioTest() throws Exception { addDescription("Tests simplest arguments for running the CmdLineClient"); - String[] args = new String[]{"-s" + SETTINGS_DIR, + String[] args = new String[]{"-s" + SETTINGS_DIR, "-k" + KEY_FILE, "-p" + PILLAR1_ID, "-f" + DEFAULT_FILE_ID, @@ -51,190 +55,222 @@ public void defaultSuccessScenarioTest() throws Exception { new ReplaceFileCmd(args); } - @Test(groups = { "regressiontest" }) + @Test + @Tag("regressiontest") public void URLSuccessScenarioTest() throws Exception { addDescription("Tests the scenario, where a URL instead of a file is used for the replacement file."); - String[] args = new String[]{"-s" + SETTINGS_DIR, + String[] args = new String[]{"-s" + SETTINGS_DIR, "-k" + KEY_FILE, "-p" + PILLAR1_ID, - "-u" + DEFAULT_DOWNLOAD_FILE_ADDRESS, + "-u" + defaultDownloadFileAddress, "-r" + DEFAULT_CHECKSUM, "-C" + DEFAULT_CHECKSUM, - "-c" + DEFAULT_COLLECTION_ID, + "-c" + DEFAULT_COLLECTION_ID, "-i" + DEFAULT_FILE_ID}; new ReplaceFileCmd(args); } - @Test(groups = { "regressiontest" }, expectedExceptions = IllegalArgumentException.class) + @Test + @Tag("regressiontest") public void missingCollectionArgumentTest() throws Exception { - addDescription("Tests the scenario, where the collection arguments is missing."); - String[] args = new String[]{"-s" + SETTINGS_DIR, - "-k" + KEY_FILE, - "-p" + PILLAR1_ID, - "-u" + DEFAULT_DOWNLOAD_FILE_ADDRESS, - "-r" + DEFAULT_CHECKSUM, - "-C" + DEFAULT_CHECKSUM, - "-i" + DEFAULT_FILE_ID}; - new ReplaceFileCmd(args); + assertThrows(IllegalArgumentException.class, () -> { + addDescription("Tests the scenario, where the collection arguments is missing."); + String[] args = new String[]{"-s" + SETTINGS_DIR, + "-k" + KEY_FILE, + "-p" + PILLAR1_ID, + "-u" + defaultDownloadFileAddress, + "-r" + DEFAULT_CHECKSUM, + "-C" + DEFAULT_CHECKSUM, + "-i" + DEFAULT_FILE_ID}; + new ReplaceFileCmd(args); + }); } - @Test(groups = { "regressiontest" }, expectedExceptions = IllegalArgumentException.class) + @Test + @Tag("regressiontest") public void missingPillarArgumentTest() throws Exception { - addDescription("Tests the different scenarios, with the pillar argument."); - String[] args = new String[]{"-s" + SETTINGS_DIR, - "-k" + KEY_FILE, - "-u" + DEFAULT_DOWNLOAD_FILE_ADDRESS, - "-r" + DEFAULT_CHECKSUM, - "-C" + DEFAULT_CHECKSUM, - "-c" + DEFAULT_COLLECTION_ID, - "-i" + DEFAULT_FILE_ID}; - new ReplaceFileCmd(args); + assertThrows(IllegalArgumentException.class, () -> { + addDescription("Tests the different scenarios, with the pillar argument."); + String[] args = new String[]{"-s" + SETTINGS_DIR, + "-k" + KEY_FILE, + "-u" + defaultDownloadFileAddress, + "-r" + DEFAULT_CHECKSUM, + "-C" + DEFAULT_CHECKSUM, + "-c" + DEFAULT_COLLECTION_ID, + "-i" + DEFAULT_FILE_ID}; + new ReplaceFileCmd(args); + }); } - @Test(groups = { "regressiontest" }, expectedExceptions = IllegalArgumentException.class) + @Test + @Tag("regressiontest") public void unknownPillarArgumentTest() throws Exception { - addStep("Testing against a non-existing pillar id", "Should fail"); - String[] args = new String[]{"-s" + SETTINGS_DIR, - "-k" + KEY_FILE, - "-u" + DEFAULT_DOWNLOAD_FILE_ADDRESS, - "-r" + DEFAULT_CHECKSUM, - "-C" + DEFAULT_CHECKSUM, - "-c" + DEFAULT_COLLECTION_ID, - "-p" + "Random" + (new Date()).getTime() + "pillar", - "-i" + DEFAULT_FILE_ID}; - new ReplaceFileCmd(args); + assertThrows(IllegalArgumentException.class, () -> { + addStep("Testing against a non-existing pillar id", "Should fail"); + String[] args = new String[]{"-s" + SETTINGS_DIR, + "-k" + KEY_FILE, + "-u" + defaultDownloadFileAddress, + "-r" + DEFAULT_CHECKSUM, + "-C" + DEFAULT_CHECKSUM, + "-c" + DEFAULT_COLLECTION_ID, + "-p" + "Random" + (new Date()).getTime() + "pillar", + "-i" + DEFAULT_FILE_ID}; + new ReplaceFileCmd(args); + }); } - @Test(groups = { "regressiontest" }, expectedExceptions = IllegalArgumentException.class) + @Test + @Tag("regressiontest") public void missingFileOrURLArgumentTest() throws Exception { - addDescription("Tests the scenario, where no arguments for file or url is given."); - String[] args = new String[]{"-s" + SETTINGS_DIR, - "-k" + KEY_FILE, - "-p" + PILLAR1_ID, - "-r" + DEFAULT_CHECKSUM, - "-c" + DEFAULT_COLLECTION_ID, - "-C" + DEFAULT_CHECKSUM, - "-i" + DEFAULT_FILE_ID}; - new ReplaceFileCmd(args); + assertThrows(IllegalArgumentException.class, () -> { + addDescription("Tests the scenario, where no arguments for file or url is given."); + String[] args = new String[]{"-s" + SETTINGS_DIR, + "-k" + KEY_FILE, + "-p" + PILLAR1_ID, + "-r" + DEFAULT_CHECKSUM, + "-c" + DEFAULT_COLLECTION_ID, + "-C" + DEFAULT_CHECKSUM, + "-i" + DEFAULT_FILE_ID}; + new ReplaceFileCmd(args); + }); } - - @Test(groups = { "regressiontest" }, expectedExceptions = IllegalArgumentException.class) + + @Test + @Tag("regressiontest") public void bothFileAndURLArgumentTest() throws Exception { - addDescription("Tests the scenario, where both arguments for file or url is given."); - String[] args = new String[]{"-s" + SETTINGS_DIR, - "-k" + KEY_FILE, - "-p" + PILLAR1_ID, - "-r" + DEFAULT_CHECKSUM, - "-f" + DEFAULT_FILE_ID, - "-u" + DEFAULT_DOWNLOAD_FILE_ADDRESS, - "-c" + DEFAULT_COLLECTION_ID, - "-C" + DEFAULT_CHECKSUM, - "-i" + DEFAULT_FILE_ID}; - new ReplaceFileCmd(args); + assertThrows(IllegalArgumentException.class, () -> { + addDescription("Tests the scenario, where both arguments for file or url is given."); + String[] args = new String[]{"-s" + SETTINGS_DIR, + "-k" + KEY_FILE, + "-p" + PILLAR1_ID, + "-r" + DEFAULT_CHECKSUM, + "-f" + DEFAULT_FILE_ID, + "-u" + defaultDownloadFileAddress, + "-c" + DEFAULT_COLLECTION_ID, + "-C" + DEFAULT_CHECKSUM, + "-i" + DEFAULT_FILE_ID}; + new ReplaceFileCmd(args); + }); } - - @Test(groups = { "regressiontest" }, expectedExceptions = IllegalArgumentException.class) + + @Test + @Tag("regressiontest") public void missingFileIDWhenURLArgumentTest() throws Exception { - addDescription("Tests the scenario, where no checksum argument is given, but a URL is given."); - String[] args = new String[]{"-s" + SETTINGS_DIR, - "-k" + KEY_FILE, - "-p" + PILLAR1_ID, - "-u" + DEFAULT_DOWNLOAD_FILE_ADDRESS, - "-r" + DEFAULT_CHECKSUM, - "-c" + DEFAULT_COLLECTION_ID, - "-C" + DEFAULT_CHECKSUM}; - new ReplaceFileCmd(args); + assertThrows(IllegalArgumentException.class, () -> { + addDescription("Tests the scenario, where no checksum argument is given, but a URL is given."); + String[] args = new String[]{"-s" + SETTINGS_DIR, + "-k" + KEY_FILE, + "-p" + PILLAR1_ID, + "-u" + defaultDownloadFileAddress, + "-r" + DEFAULT_CHECKSUM, + "-c" + DEFAULT_COLLECTION_ID, + "-C" + DEFAULT_CHECKSUM}; + new ReplaceFileCmd(args); + }); } - @Test(groups = { "regressiontest" }) + @Test + @Tag("regressiontest") public void missingFileIDWhenFileArgumentTest() throws Exception { addDescription("Tests the scenario, where no checksum argument is given, but a URL is given."); - String[] args = new String[]{"-s" + SETTINGS_DIR, + String[] args = new String[]{"-s" + SETTINGS_DIR, "-k" + KEY_FILE, "-p" + PILLAR1_ID, "-f" + DEFAULT_FILE_ID, - "-c" + DEFAULT_COLLECTION_ID, + "-c" + DEFAULT_COLLECTION_ID, "-C" + DEFAULT_CHECKSUM}; new ReplaceFileCmd(args); } - @Test(groups = { "regressiontest" }, expectedExceptions = IllegalArgumentException.class) + @Test + @Tag("regressiontest") public void missingChecksumForNewFileWhenUsingURLArgumentTest() throws Exception { - addDescription("Tests the scenario, where no checksum argument is given, but a URL is given."); - String[] args = new String[]{"-s" + SETTINGS_DIR, - "-k" + KEY_FILE, - "-p" + PILLAR1_ID, - "-u" + DEFAULT_DOWNLOAD_FILE_ADDRESS, - "-C" + DEFAULT_CHECKSUM, - "-c" + DEFAULT_COLLECTION_ID, - "-i" + DEFAULT_FILE_ID}; - new ReplaceFileCmd(args); + assertThrows(IllegalArgumentException.class, () -> { + addDescription("Tests the scenario, where no checksum argument is given, but a URL is given."); + String[] args = new String[]{"-s" + SETTINGS_DIR, + "-k" + KEY_FILE, + "-p" + PILLAR1_ID, + "-u" + defaultDownloadFileAddress, + "-C" + DEFAULT_CHECKSUM, + "-c" + DEFAULT_COLLECTION_ID, + "-i" + DEFAULT_FILE_ID}; + new ReplaceFileCmd(args); + }); } - @Test(groups = { "regressiontest" }) + @Test + @Tag("regressiontest") public void missingChecksumForNewFileWhenUsingFileArgumentTest() throws Exception { addDescription("Tests the scenario, where no checksum argument is given, but a File is given."); - String[] args = new String[]{"-s" + SETTINGS_DIR, + String[] args = new String[]{"-s" + SETTINGS_DIR, "-k" + KEY_FILE, "-p" + PILLAR1_ID, "-f" + DEFAULT_FILE_ID, "-C" + DEFAULT_CHECKSUM, - "-c" + DEFAULT_COLLECTION_ID, + "-c" + DEFAULT_COLLECTION_ID, "-i" + DEFAULT_FILE_ID}; new ReplaceFileCmd(args); } - @Test(groups = { "regressiontest" }, expectedExceptions = IllegalArgumentException.class) + @Test + @Tag("regressiontest") public void missingChecksumForExistingFileWhenUsingURLArgumentTest() throws Exception { - addDescription("Tests the scenario, where no checksum argument is given, but a URL is given."); - String[] args = new String[]{"-s" + SETTINGS_DIR, - "-k" + KEY_FILE, - "-p" + PILLAR1_ID, - "-u" + DEFAULT_DOWNLOAD_FILE_ADDRESS, - "-r" + DEFAULT_CHECKSUM, - "-c" + DEFAULT_COLLECTION_ID, - "-i" + DEFAULT_FILE_ID}; - new ReplaceFileCmd(args); + assertThrows(IllegalArgumentException.class, () -> { + addDescription("Tests the scenario, where no checksum argument is given, but a URL is given."); + String[] args = new String[]{"-s" + SETTINGS_DIR, + "-k" + KEY_FILE, + "-p" + PILLAR1_ID, + "-u" + defaultDownloadFileAddress, + "-r" + DEFAULT_CHECKSUM, + "-c" + DEFAULT_COLLECTION_ID, + "-i" + DEFAULT_FILE_ID}; + new ReplaceFileCmd(args); + }); } - @Test(groups = { "regressiontest" }, expectedExceptions = IllegalArgumentException.class) + @Test + @Tag("regressiontest") public void missingChecksumForExistingFileWhenUsingFileArgumentTest() throws Exception { - addDescription("Tests the scenario, where no checksum argument is given, but a File is given."); - String[] args = new String[]{"-s" + SETTINGS_DIR, - "-k" + KEY_FILE, - "-p" + PILLAR1_ID, - "-f" + DEFAULT_FILE_ID, - "-r" + DEFAULT_CHECKSUM, - "-c" + DEFAULT_COLLECTION_ID, - "-i" + DEFAULT_FILE_ID}; - new ReplaceFileCmd(args); + assertThrows(IllegalArgumentException.class, () -> { + addDescription("Tests the scenario, where no checksum argument is given, but a File is given."); + String[] args = new String[]{"-s" + SETTINGS_DIR, + "-k" + KEY_FILE, + "-p" + PILLAR1_ID, + "-f" + DEFAULT_FILE_ID, + "-r" + DEFAULT_CHECKSUM, + "-c" + DEFAULT_COLLECTION_ID, + "-i" + DEFAULT_FILE_ID}; + new ReplaceFileCmd(args); + }); } - - @Test(groups = { "regressiontest" }) + + @Test + @Tag("regressiontest") public void checksumArgumentNonSaltAlgorithmWitoutSaltTest() throws Exception { addDescription("Test MD5 checksum without salt -> no failure"); - String[] args = new String[]{"-s" + SETTINGS_DIR, + String[] args = new String[]{"-s" + SETTINGS_DIR, "-k" + KEY_FILE, "-p" + PILLAR1_ID, - "-u" + DEFAULT_DOWNLOAD_FILE_ADDRESS, + "-u" + defaultDownloadFileAddress, "-r" + DEFAULT_CHECKSUM, "-C" + DEFAULT_CHECKSUM, - "-c" + DEFAULT_COLLECTION_ID, + "-c" + DEFAULT_COLLECTION_ID, "-i" + DEFAULT_FILE_ID, "-R" + "MD5"}; new ReplaceFileCmd(args); } - @Test(groups = { "regressiontest" }) + @Test + @Tag("regressiontest") public void checksumArgumentSaltAlgorithmWithSaltTest() throws Exception { addDescription("Test HMAC_SHA256 checksum with salt -> No failure"); - String[] args = new String[]{"-s" + SETTINGS_DIR, + String[] args = new String[]{"-s" + SETTINGS_DIR, "-k" + KEY_FILE, "-p" + PILLAR1_ID, - "-u" + DEFAULT_DOWNLOAD_FILE_ADDRESS, + "-u" + defaultDownloadFileAddress, "-r" + DEFAULT_CHECKSUM, "-C" + DEFAULT_CHECKSUM, - "-c" + DEFAULT_COLLECTION_ID, + "-c" + DEFAULT_COLLECTION_ID, "-i" + DEFAULT_FILE_ID, "-R" + "HMAC_SHA256", "-S" + "SALT"}; diff --git a/bitrepository-client/src/test/java/org/bitrepository/commandline/utils/ChecksumExtractionUtilsTest.java b/bitrepository-client/src/test/java/org/bitrepository/commandline/utils/ChecksumExtractionUtilsTest.java index e669ea875..62be9106a 100644 --- a/bitrepository-client/src/test/java/org/bitrepository/commandline/utils/ChecksumExtractionUtilsTest.java +++ b/bitrepository-client/src/test/java/org/bitrepository/commandline/utils/ChecksumExtractionUtilsTest.java @@ -26,19 +26,20 @@ import org.bitrepository.client.DefaultFixtureClientTest; import org.bitrepository.commandline.Constants; import org.bitrepository.commandline.output.OutputHandler; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mock; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertNotEquals; -import static org.testng.Assert.assertTrue; public class ChecksumExtractionUtilsTest extends DefaultFixtureClientTest { CommandLineArgumentsHandler cmdHandler; OutputHandler output; - @BeforeMethod(alwaysRun = true) + @BeforeEach public void setup() { cmdHandler = new CommandLineArgumentsHandler(); cmdHandler.addOption(new Option(Constants.REQUEST_CHECKSUM_SALT_ARG, Constants.HAS_ARGUMENT, "")); @@ -46,32 +47,36 @@ public void setup() { output = mock(OutputHandler.class); } - @Test(groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public void testDefaultChecksumSpec() throws Exception { addDescription("Test that the default checksum is retrieved when no arguments are given."); - cmdHandler.parseArguments(new String[]{}); + cmdHandler.parseArguments(); ChecksumType type = ChecksumExtractionUtils.extractChecksumType(cmdHandler, settingsForCUT, output); assertEquals(type.name(), settingsForCUT.getRepositorySettings().getProtocolSettings().getDefaultChecksumType()); } - @Test(groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public void testDefaultChecksumSpecWithSaltArgument() throws Exception { addDescription("Test that the HMAC version of default checksum is retrieved when the salt arguments are given."); - cmdHandler.parseArguments(new String[]{"-" + Constants.REQUEST_CHECKSUM_SALT_ARG + "0110"}); + cmdHandler.parseArguments("-" + Constants.REQUEST_CHECKSUM_SALT_ARG + "0110"); ChecksumType type = ChecksumExtractionUtils.extractChecksumType(cmdHandler, settingsForCUT, output); assertEquals(type.name(), "HMAC_" + settingsForCUT.getRepositorySettings().getProtocolSettings().getDefaultChecksumType()); } - @Test(groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public void testNonSaltChecksumSpecWithoutSaltArgument() throws Exception { addDescription("Test that a non-salt checksum type is retrieved when it is given as argument, and no salt arguments are given."); ChecksumType enteredType = ChecksumType.SHA384; - cmdHandler.parseArguments(new String[]{"-" + Constants.REQUEST_CHECKSUM_TYPE_ARG + enteredType}); + cmdHandler.parseArguments("-" + Constants.REQUEST_CHECKSUM_TYPE_ARG + enteredType); ChecksumType type = ChecksumExtractionUtils.extractChecksumType(cmdHandler, settingsForCUT, output); - assertEquals(type, enteredType); + assertEquals(enteredType, type); } - @Test(groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public void testNonSaltChecksumSpecWithSaltArgument() throws Exception { addDescription("Test that a salt checksum type is retrieved even though a non-salt checksum algorithm it is given as argument, " + "but a salt argument also is given."); @@ -79,23 +84,25 @@ public void testNonSaltChecksumSpecWithSaltArgument() throws Exception { cmdHandler.parseArguments("-" + Constants.REQUEST_CHECKSUM_TYPE_ARG + enteredType, "-" + Constants.REQUEST_CHECKSUM_SALT_ARG + "0110"); ChecksumType type = ChecksumExtractionUtils.extractChecksumType(cmdHandler, settingsForCUT, output); - assertNotEquals(type, enteredType); + assertNotEquals(enteredType, type); assertEquals(type.name(), "HMAC_" + enteredType.name()); } - @Test(groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public void testSaltChecksumSpecWithoutSaltArgument() throws Exception { addDescription("Test that a non-salt checksum type is retrieved even though a salt checksum algorithm it is given as argument, " + "but no salt argument also is given."); ChecksumType enteredType = ChecksumType.HMAC_SHA256; cmdHandler.parseArguments("-" + Constants.REQUEST_CHECKSUM_TYPE_ARG + enteredType); ChecksumType type = ChecksumExtractionUtils.extractChecksumType(cmdHandler, settingsForCUT, output); - assertNotEquals(type, enteredType); + assertNotEquals(enteredType, type); assertTrue(enteredType.name().contains("HMAC")); assertEquals(type.name(), enteredType.name().replace("HMAC_", "")); } - @Test(groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public void testSaltChecksumSpecWithSaltArgument() throws Exception { addDescription("Test that a salt checksum type is retrieved when the salt checksum algorithm it is given as argument, " + "and a salt argument also is given."); @@ -103,6 +110,6 @@ public void testSaltChecksumSpecWithSaltArgument() throws Exception { cmdHandler.parseArguments("-" + Constants.REQUEST_CHECKSUM_TYPE_ARG + enteredType, "-" + Constants.REQUEST_CHECKSUM_SALT_ARG + "0110"); ChecksumType type = ChecksumExtractionUtils.extractChecksumType(cmdHandler, settingsForCUT, output); - assertEquals(type, enteredType); + assertEquals(enteredType, type); } } diff --git a/bitrepository-client/src/test/java/org/bitrepository/modify/deletefile/DeleteFileClientComponentTest.java b/bitrepository-client/src/test/java/org/bitrepository/modify/deletefile/DeleteFileClientComponentTest.java index d2f989307..156e14b00 100644 --- a/bitrepository-client/src/test/java/org/bitrepository/modify/deletefile/DeleteFileClientComponentTest.java +++ b/bitrepository-client/src/test/java/org/bitrepository/modify/deletefile/DeleteFileClientComponentTest.java @@ -1,23 +1,23 @@ /* * #%L * Bitrepository Access Client - * + * * $Id$ * $HeadURL$ * %% * Copyright (C) 2010 - 2011 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% @@ -41,9 +41,10 @@ import org.bitrepository.common.utils.CalendarUtils; import org.bitrepository.common.utils.TestFileHelper; import org.bitrepository.modify.ModifyComponentFactory; -import org.testng.Assert; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; import javax.xml.datatype.DatatypeFactory; import java.nio.charset.StandardCharsets; @@ -52,24 +53,26 @@ public class DeleteFileClientComponentTest extends DefaultFixtureClientTest { private TestDeleteFileMessageFactory messageFactory; private DatatypeFactory datatypeFactory; - @BeforeMethod(alwaysRun=true) + @BeforeEach public void initialise() throws Exception { messageFactory = new TestDeleteFileMessageFactory(collectionID); datatypeFactory = DatatypeFactory.newInstance(); } - @Test(groups={"regressiontest"}) + @Test + @Tag("regressiontest") public void verifyDeleteClientFromFactory() { addDescription("Testing the initialization through the ModifyComponentFactory."); addStep("Use the ModifyComponentFactory to instantiate a PutFileClient.", "It should be an instance of SimplePutFileClient"); DeleteFileClient dfc = ModifyComponentFactory.getInstance().retrieveDeleteFileClient( settingsForCUT, securityManager, settingsForTestClient.getComponentID()); - Assert.assertTrue(dfc instanceof ConversationBasedDeleteFileClient, "The DeleteFileClient '" + dfc + Assertions.assertInstanceOf(ConversationBasedDeleteFileClient.class, dfc, "The DeleteFileClient '" + dfc + "' should be instance of '" + ConversationBasedDeleteFileClient.class.getName() + "'"); } - @Test(groups={"regressiontest"}) + @Test + @Tag("regressiontest") public void deleteClientTester() throws Exception { addDescription("Tests the DeleteClient. Makes a whole conversation for the delete client for a 'good' scenario."); addStep("Initialise the number of pillars to one", "Should be OK."); @@ -98,14 +101,14 @@ public void deleteClientTester() throws Exception { IdentifyPillarsForDeleteFileRequest receivedIdentifyRequestMessage = collectionReceiver.waitForMessage( IdentifyPillarsForDeleteFileRequest.class); - Assert.assertEquals(receivedIdentifyRequestMessage.getCollectionID(), collectionID); - Assert.assertNotNull(receivedIdentifyRequestMessage.getCorrelationID()); - Assert.assertEquals(receivedIdentifyRequestMessage.getReplyTo(), settingsForCUT.getReceiverDestinationID()); - Assert.assertEquals(receivedIdentifyRequestMessage.getFileID(), DEFAULT_FILE_ID); - Assert.assertEquals(receivedIdentifyRequestMessage.getFrom(), settingsForTestClient.getComponentID()); - Assert.assertEquals(receivedIdentifyRequestMessage.getDestination(), settingsForTestClient.getCollectionDestination()); + Assertions.assertEquals(receivedIdentifyRequestMessage.getCollectionID(), collectionID); + Assertions.assertNotNull(receivedIdentifyRequestMessage.getCorrelationID()); + Assertions.assertEquals(receivedIdentifyRequestMessage.getReplyTo(), settingsForCUT.getReceiverDestinationID()); + Assertions.assertEquals(DEFAULT_FILE_ID, receivedIdentifyRequestMessage.getFileID()); + Assertions.assertEquals(receivedIdentifyRequestMessage.getFrom(), settingsForTestClient.getComponentID()); + Assertions.assertEquals(receivedIdentifyRequestMessage.getDestination(), settingsForTestClient.getCollectionDestination()); - Assert.assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.IDENTIFY_REQUEST_SENT); + Assertions.assertEquals(OperationEventType.IDENTIFY_REQUEST_SENT, testEventHandler.waitForEvent().getEventType()); addStep("Make response for the pillar.", "The client receive the response, identify the pillar and send the request."); @@ -115,42 +118,43 @@ public void deleteClientTester() throws Exception { PILLAR1_ID, pillar1DestinationId, DEFAULT_FILE_ID); messageBus.sendMessage(identifyResponse); receivedDeleteFileRequest = pillar1Receiver.waitForMessage(DeleteFileRequest.class); - Assert.assertEquals(receivedDeleteFileRequest.getCollectionID(), collectionID); - Assert.assertEquals(receivedDeleteFileRequest.getCorrelationID(), receivedIdentifyRequestMessage.getCorrelationID()); - Assert.assertEquals(receivedDeleteFileRequest.getReplyTo(), settingsForCUT.getReceiverDestinationID()); - Assert.assertEquals(receivedDeleteFileRequest.getFileID(), DEFAULT_FILE_ID); - Assert.assertEquals(receivedDeleteFileRequest.getFrom(), settingsForTestClient.getComponentID()); - Assert.assertEquals(receivedDeleteFileRequest.getDestination(), pillar1DestinationId); + Assertions.assertEquals(receivedDeleteFileRequest.getCollectionID(), collectionID); + Assertions.assertEquals(receivedDeleteFileRequest.getCorrelationID(), receivedIdentifyRequestMessage.getCorrelationID()); + Assertions.assertEquals(receivedDeleteFileRequest.getReplyTo(), settingsForCUT.getReceiverDestinationID()); + Assertions.assertEquals(DEFAULT_FILE_ID, receivedDeleteFileRequest.getFileID()); + Assertions.assertEquals(receivedDeleteFileRequest.getFrom(), settingsForTestClient.getComponentID()); + Assertions.assertEquals(receivedDeleteFileRequest.getDestination(), pillar1DestinationId); addStep("Validate the steps of the DeleteClient by going through the events.", "Should be 'PillarIdentified', " + "'PillarSelected' and 'RequestSent'"); - for(int i = 0; i < settingsForCUT.getRepositorySettings().getCollections().getCollection().get(0).getPillarIDs().getPillarID().size(); i++) { - Assert.assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.COMPONENT_IDENTIFIED); + for (int i = 0; i < settingsForCUT.getRepositorySettings().getCollections().getCollection().get(0).getPillarIDs().getPillarID().size(); i++) { + Assertions.assertEquals(OperationEventType.COMPONENT_IDENTIFIED, testEventHandler.waitForEvent().getEventType()); } - Assert.assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.IDENTIFICATION_COMPLETE); - Assert.assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.REQUEST_SENT); + Assertions.assertEquals(OperationEventType.IDENTIFICATION_COMPLETE, testEventHandler.waitForEvent().getEventType()); + Assertions.assertEquals(OperationEventType.REQUEST_SENT, testEventHandler.waitForEvent().getEventType()); addStep("The pillar sends a progress response to the DeleteClient.", "Should be caught by the event handler."); DeleteFileProgressResponse deleteFileProgressResponse = messageFactory.createDeleteFileProgressResponse( receivedDeleteFileRequest, PILLAR1_ID, pillar1DestinationId); messageBus.sendMessage(deleteFileProgressResponse); - Assert.assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.PROGRESS); + Assertions.assertEquals(OperationEventType.PROGRESS, testEventHandler.waitForEvent().getEventType()); addStep("Send a final response message to the DeleteClient.", "Should be caught by the event handler. First a PartiallyComplete, then a Complete."); DeleteFileFinalResponse deleteFileFinalResponse = messageFactory.createDeleteFileFinalResponse( receivedDeleteFileRequest, PILLAR1_ID, pillar1DestinationId, DEFAULT_FILE_ID); messageBus.sendMessage(deleteFileFinalResponse); - for(int i = 1; i < 2* settingsForCUT.getRepositorySettings().getCollections().getCollection().get(0).getPillarIDs().getPillarID().size(); i++) { + for (int i = 1; i < 2 * settingsForCUT.getRepositorySettings().getCollections().getCollection().get(0).getPillarIDs().getPillarID().size(); i++) { OperationEventType eventType = testEventHandler.waitForEvent().getEventType(); - Assert.assertTrue( (eventType == OperationEventType.COMPONENT_COMPLETE) - || (eventType == OperationEventType.PROGRESS), + Assertions.assertTrue((eventType == OperationEventType.COMPONENT_COMPLETE) + || (eventType == OperationEventType.PROGRESS), "Expected either PartiallyComplete or Progress, but was: " + eventType); } - Assert.assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.COMPLETE); + Assertions.assertEquals(OperationEventType.COMPLETE, testEventHandler.waitForEvent().getEventType()); } - @Test(groups={"regressiontest"}) + @Test + @Tag("regressiontest") public void fileAlreadyDeletedFromPillar() throws Exception { addDescription("Test that a delete on a pillar completes successfully when the file is missing " + "(has already been deleted). This is a test of the Idempotent behaviour of the delete client"); @@ -164,7 +168,7 @@ public void fileAlreadyDeletedFromPillar() throws Exception { IdentifyPillarsForDeleteFileRequest receivedIdentifyRequestMessage = collectionReceiver.waitForMessage( IdentifyPillarsForDeleteFileRequest.class); - Assert.assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.IDENTIFY_REQUEST_SENT); + Assertions.assertEquals(OperationEventType.IDENTIFY_REQUEST_SENT, testEventHandler.waitForEvent().getEventType()); addStep("Send a identify response from Pillar1 with a missing file response.", "The client should generate a COMPONENT_IDENTIFIED, a COMPONENT_COMPLETE and " + @@ -173,20 +177,21 @@ public void fileAlreadyDeletedFromPillar() throws Exception { receivedIdentifyRequestMessage, PILLAR1_ID, pillar1DestinationId, DEFAULT_FILE_ID); identifyResponse.getResponseInfo().setResponseCode(ResponseCode.FILE_NOT_FOUND_FAILURE); messageBus.sendMessage(identifyResponse); - Assert.assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.COMPONENT_IDENTIFIED); - Assert.assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.COMPONENT_COMPLETE); - Assert.assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.IDENTIFICATION_COMPLETE); + Assertions.assertEquals(OperationEventType.COMPONENT_IDENTIFIED, testEventHandler.waitForEvent().getEventType()); + Assertions.assertEquals(OperationEventType.COMPONENT_COMPLETE, testEventHandler.waitForEvent().getEventType()); + Assertions.assertEquals(OperationEventType.IDENTIFICATION_COMPLETE, testEventHandler.waitForEvent().getEventType()); addStep("The client should then continue to the performing phase and finish immediately as the pillar " + - "has already had the file removed apparently .", + "has already had the file removed apparently .", "The client should generate a COMPLETE event."); - Assert.assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.COMPLETE); + Assertions.assertEquals(OperationEventType.COMPLETE, testEventHandler.waitForEvent().getEventType()); addStep("Send a identify response from Pillar2", "The response should be ignored"); testEventHandler.verifyNoEventsAreReceived(); } - @Test(groups={"regressiontest"}) + @Test + @Tag("regressiontest") public void deleteClientIdentificationTimeout() throws Exception { addDescription("Tests the handling of a failed identification for the DeleteClient"); addStep("Initialise the number of pillars and the DeleteClient. Sets the identification timeout to 1 sec.", @@ -216,16 +221,17 @@ public void deleteClientIdentificationTimeout() throws Exception { testEventHandler, null); collectionReceiver.waitForMessage(IdentifyPillarsForDeleteFileRequest.class); - Assert.assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.IDENTIFY_REQUEST_SENT); + Assertions.assertEquals(OperationEventType.IDENTIFY_REQUEST_SENT, testEventHandler.waitForEvent().getEventType()); addStep("Do not respond. Just await the timeout.", "Should make send a Failure event to the event handler."); - Assert.assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.IDENTIFY_TIMEOUT); - Assert.assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.COMPONENT_FAILED); - Assert.assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.FAILED); + Assertions.assertEquals(OperationEventType.IDENTIFY_TIMEOUT, testEventHandler.waitForEvent().getEventType()); + Assertions.assertEquals(OperationEventType.COMPONENT_FAILED, testEventHandler.waitForEvent().getEventType()); + Assertions.assertEquals(OperationEventType.FAILED, testEventHandler.waitForEvent().getEventType()); } - @Test(groups={"regressiontest"}) + @Test + @Tag("regressiontest") public void deleteClientOperationTimeout() throws Exception { addDescription("Tests the handling of a failed operation for the DeleteClient"); addStep("Initialise the number of pillars and the DeleteClient. Sets the operation timeout to 100 ms.", @@ -255,7 +261,7 @@ public void deleteClientOperationTimeout() throws Exception { IdentifyPillarsForDeleteFileRequest receivedIdentifyRequestMessage = collectionReceiver.waitForMessage(IdentifyPillarsForDeleteFileRequest.class); - Assert.assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.IDENTIFY_REQUEST_SENT); + Assertions.assertEquals(OperationEventType.IDENTIFY_REQUEST_SENT, testEventHandler.waitForEvent().getEventType()); addStep("Make response for the pillar.", "The client receive the response, identify the pillar and send the request."); @@ -267,18 +273,19 @@ public void deleteClientOperationTimeout() throws Exception { addStep("Validate the steps of the DeleteClient by going through the events.", "Should be 'PillarIdentified', " + "'PillarSelected' and 'RequestSent'"); - for(int i = 0; i < settingsForCUT.getRepositorySettings().getCollections().getCollection().get(0).getPillarIDs().getPillarID().size(); i++) { - Assert.assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.COMPONENT_IDENTIFIED); + for (int i = 0; i < settingsForCUT.getRepositorySettings().getCollections().getCollection().get(0).getPillarIDs().getPillarID().size(); i++) { + Assertions.assertEquals(OperationEventType.COMPONENT_IDENTIFIED, testEventHandler.waitForEvent().getEventType()); } - Assert.assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.IDENTIFICATION_COMPLETE); - Assert.assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.REQUEST_SENT); + Assertions.assertEquals(OperationEventType.IDENTIFICATION_COMPLETE, testEventHandler.waitForEvent().getEventType()); + Assertions.assertEquals(OperationEventType.REQUEST_SENT, testEventHandler.waitForEvent().getEventType()); addStep("Do not respond. Just await the timeout.", "Should make send a Failure event to the event handler."); - Assert.assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.FAILED); + Assertions.assertEquals(OperationEventType.FAILED, testEventHandler.waitForEvent().getEventType()); } - @Test(groups={"regressiontest"}) + @Test + @Tag("regressiontest") public void deleteClientPillarFailedDuringPerform() throws Exception { addDescription("Tests the handling of a operation failure for the DeleteClient. "); addStep("Initialise the number of pillars to one", "Should be OK."); @@ -305,7 +312,7 @@ public void deleteClientPillarFailedDuringPerform() throws Exception { IdentifyPillarsForDeleteFileRequest receivedIdentifyRequestMessage = collectionReceiver.waitForMessage(IdentifyPillarsForDeleteFileRequest.class); - Assert.assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.IDENTIFY_REQUEST_SENT); + Assertions.assertEquals(OperationEventType.IDENTIFY_REQUEST_SENT, testEventHandler.waitForEvent().getEventType()); addStep("Make response for the pillar.", "The client receive the response, identify the pillar and send the request."); @@ -317,11 +324,11 @@ public void deleteClientPillarFailedDuringPerform() throws Exception { receivedDeleteFileRequest = pillar1Receiver.waitForMessage(DeleteFileRequest.class); addStep("Validate the steps of the DeleteClient by going through the events.", "Should be 'PillarIdentified', " + "'PillarSelected' and 'RequestSent'"); - for(int i = 0; i < settingsForCUT.getRepositorySettings().getCollections().getCollection().get(0).getPillarIDs().getPillarID().size(); i++) { - Assert.assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.COMPONENT_IDENTIFIED); + for (int i = 0; i < settingsForCUT.getRepositorySettings().getCollections().getCollection().get(0).getPillarIDs().getPillarID().size(); i++) { + Assertions.assertEquals(OperationEventType.COMPONENT_IDENTIFIED, testEventHandler.waitForEvent().getEventType()); } - Assert.assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.IDENTIFICATION_COMPLETE); - Assert.assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.REQUEST_SENT); + Assertions.assertEquals(OperationEventType.IDENTIFICATION_COMPLETE, testEventHandler.waitForEvent().getEventType()); + Assertions.assertEquals(OperationEventType.REQUEST_SENT, testEventHandler.waitForEvent().getEventType()); addStep("Send a failed response message to the DeleteClient.", "Should be caught by the event handler. First a COMPONENT_FAILED, then a COMPLETE."); @@ -332,11 +339,12 @@ public void deleteClientPillarFailedDuringPerform() throws Exception { ri.setResponseText("Verifying that a failure can be understood!"); deleteFileFinalResponse.setResponseInfo(ri); messageBus.sendMessage(deleteFileFinalResponse); - Assert.assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.COMPONENT_FAILED); - Assert.assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.FAILED); + Assertions.assertEquals(OperationEventType.COMPONENT_FAILED, testEventHandler.waitForEvent().getEventType()); + Assertions.assertEquals(OperationEventType.FAILED, testEventHandler.waitForEvent().getEventType()); } - @Test(groups={"regressiontest"}) + @Test + @Tag("regressiontest") public void deleteClientSpecifiedPillarFailedDuringIdentification() throws Exception { addDescription("Tests the handling of a identification failure for a pillar for the DeleteClient. "); TestEventHandler testEventHandler = new TestEventHandler(testEventManager); @@ -359,12 +367,13 @@ public void deleteClientSpecifiedPillarFailedDuringIdentification() throws Excep identifyResponse.getResponseInfo().setResponseCode(ResponseCode.IDENTIFICATION_NEGATIVE); messageBus.sendMessage(identifyResponse); - Assert.assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.IDENTIFY_REQUEST_SENT); - Assert.assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.COMPONENT_FAILED); - Assert.assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.FAILED); + Assertions.assertEquals(OperationEventType.IDENTIFY_REQUEST_SENT, testEventHandler.waitForEvent().getEventType()); + Assertions.assertEquals(OperationEventType.COMPONENT_FAILED, testEventHandler.waitForEvent().getEventType()); + Assertions.assertEquals(OperationEventType.FAILED, testEventHandler.waitForEvent().getEventType()); } - @Test(groups={"regressiontest"}) + @Test + @Tag("regressiontest") public void deleteClientOtherPillarFailedDuringIdentification() throws Exception { addDescription("Tests the handling of a identification failure for a pillar for the DeleteClient. "); TestEventHandler testEventHandler = new TestEventHandler(testEventManager); @@ -374,7 +383,7 @@ public void deleteClientOtherPillarFailedDuringIdentification() throws Exception "A IdentifyPillarsForDeleteFileRequest should be sent and a IDENTIFY_REQUEST_SENT event should be generated."); deleteClient.deleteFile(collectionID, DEFAULT_FILE_ID, PILLAR1_ID, TestFileHelper.getDefaultFileChecksum(), null, testEventHandler, null); - Assert.assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.IDENTIFY_REQUEST_SENT); + Assertions.assertEquals(OperationEventType.IDENTIFY_REQUEST_SENT, testEventHandler.waitForEvent().getEventType()); IdentifyPillarsForDeleteFileRequest receivedIdentifyRequestMessage = collectionReceiver.waitForMessage( IdentifyPillarsForDeleteFileRequest.class); @@ -395,20 +404,21 @@ public void deleteClientOtherPillarFailedDuringIdentification() throws Exception messageFactory.createIdentifyPillarsForDeleteFileResponse(receivedIdentifyRequestMessage, PILLAR1_ID, pillar1DestinationId, DEFAULT_FILE_ID); messageBus.sendMessage(identifyResponse2); - Assert.assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.COMPONENT_IDENTIFIED); - Assert.assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.IDENTIFICATION_COMPLETE); - Assert.assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.REQUEST_SENT); + Assertions.assertEquals(OperationEventType.COMPONENT_IDENTIFIED, testEventHandler.waitForEvent().getEventType()); + Assertions.assertEquals(OperationEventType.IDENTIFICATION_COMPLETE, testEventHandler.waitForEvent().getEventType()); + Assertions.assertEquals(OperationEventType.REQUEST_SENT, testEventHandler.waitForEvent().getEventType()); DeleteFileRequest receivedDeleteFileRequest = pillar1Receiver.waitForMessage(DeleteFileRequest.class); addStep("Send a final response message from pillar 1 to the DeleteClient.", "Should produce a COMPONENT_COMPLETE event followed by a COMPLETE event."); messageBus.sendMessage(messageFactory.createDeleteFileFinalResponse( receivedDeleteFileRequest, PILLAR1_ID, pillar1DestinationId, DEFAULT_FILE_ID)); - Assert.assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.COMPONENT_COMPLETE); - Assert.assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.COMPLETE); + Assertions.assertEquals(OperationEventType.COMPONENT_COMPLETE, testEventHandler.waitForEvent().getEventType()); + Assertions.assertEquals(OperationEventType.COMPLETE, testEventHandler.waitForEvent().getEventType()); } - @Test(groups={"regressiontest"}) + @Test + @Tag("regressiontest") public void deleteOnChecksumPillar() throws Exception { addDescription("Verify that the DeleteClient works correctly when a checksum pillar is present. "); TestEventHandler testEventHandler = new TestEventHandler(testEventManager); @@ -418,7 +428,7 @@ public void deleteOnChecksumPillar() throws Exception { "A IdentifyPillarsForDeleteFileRequest should be sent and a IDENTIFY_REQUEST_SENT event should be generated."); deleteClient.deleteFile(collectionID, DEFAULT_FILE_ID, PILLAR1_ID, TestFileHelper.getDefaultFileChecksum(), null, testEventHandler, null); - Assert.assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.IDENTIFY_REQUEST_SENT); + Assertions.assertEquals(OperationEventType.IDENTIFY_REQUEST_SENT, testEventHandler.waitForEvent().getEventType()); IdentifyPillarsForDeleteFileRequest receivedIdentifyRequestMessage = collectionReceiver.waitForMessage( IdentifyPillarsForDeleteFileRequest.class); @@ -432,7 +442,7 @@ public void deleteOnChecksumPillar() throws Exception { testEventHandler.verifyNoEventsAreReceived(); addStep("Send a response from pillar1 with PillarChecksumSpec element set, indicating that this is a " + - "checksum pillar.", + "checksum pillar.", "Following events should be generated: COMPONENT_IDENTIFIED, IDENTIFICATION_COMPLETE and a REQUEST_SENT." + "a request should be sent to pillar1"); IdentifyPillarsForDeleteFileResponse identifyResponse @@ -442,14 +452,15 @@ public void deleteOnChecksumPillar() throws Exception { checksumSpecTYPEFromPillar.setChecksumType(ChecksumType.MD5); identifyResponse.setPillarChecksumSpec(checksumSpecTYPEFromPillar); messageBus.sendMessage(identifyResponse); - Assert.assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.COMPONENT_IDENTIFIED); - Assert.assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.IDENTIFICATION_COMPLETE); - Assert.assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.REQUEST_SENT); - Assert.assertNotNull(pillar1Receiver.waitForMessage(DeleteFileRequest.class)); + Assertions.assertEquals(OperationEventType.COMPONENT_IDENTIFIED, testEventHandler.waitForEvent().getEventType()); + Assertions.assertEquals(OperationEventType.IDENTIFICATION_COMPLETE, testEventHandler.waitForEvent().getEventType()); + Assertions.assertEquals(OperationEventType.REQUEST_SENT, testEventHandler.waitForEvent().getEventType()); + Assertions.assertNotNull(pillar1Receiver.waitForMessage(DeleteFileRequest.class)); pillar2Receiver.checkNoMessageIsReceived(DeleteFileRequest.class); } - @Test(groups={"regressiontest"}) + @Test + @Tag("regressiontest") public void deleteOnChecksumPillarWithDefaultReturnChecksumType() throws Exception { addDescription("Verify that the DeleteClient works correctly when a return checksum of the default type" + "is requested. "); @@ -457,19 +468,19 @@ public void deleteOnChecksumPillarWithDefaultReturnChecksumType() throws Excepti DeleteFileClient deleteClient = createDeleteFileClient(); addStep("Request a file to be deleted on the pillar1. The call should include a request for a check sum of the " + - "default type", + "default type", "A IdentifyPillarsForDeleteFileRequest should be sent and a IDENTIFY_REQUEST_SENT event should be " + "generated."); ChecksumSpecTYPE checksumSpecTYPE = new ChecksumSpecTYPE(); checksumSpecTYPE.setChecksumType(ChecksumType.MD5); deleteClient.deleteFile(collectionID, DEFAULT_FILE_ID, PILLAR1_ID, TestFileHelper.getDefaultFileChecksum(), checksumSpecTYPE, testEventHandler, null); - Assert.assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.IDENTIFY_REQUEST_SENT); + Assertions.assertEquals(OperationEventType.IDENTIFY_REQUEST_SENT, testEventHandler.waitForEvent().getEventType()); IdentifyPillarsForDeleteFileRequest receivedIdentifyRequestMessage = collectionReceiver.waitForMessage( IdentifyPillarsForDeleteFileRequest.class); addStep("Send a response from pillar1 with PillarChecksumSpec element set, indicating that this is a " + - "checksum pillar.", + "checksum pillar.", "Following events should be generated: COMPONENT_IDENTIFIED, IDENTIFICATION_COMPLETE and a " + "REQUEST_SENT. A request should be sent to pillar1 with a request for return of a checksum " + "of the default type "); @@ -480,14 +491,15 @@ public void deleteOnChecksumPillarWithDefaultReturnChecksumType() throws Excepti checksumSpecTYPEFromPillar.setChecksumType(ChecksumType.MD5); identifyResponse.setPillarChecksumSpec(checksumSpecTYPEFromPillar); messageBus.sendMessage(identifyResponse); - Assert.assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.COMPONENT_IDENTIFIED); - Assert.assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.IDENTIFICATION_COMPLETE); - Assert.assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.REQUEST_SENT); + Assertions.assertEquals(OperationEventType.COMPONENT_IDENTIFIED, testEventHandler.waitForEvent().getEventType()); + Assertions.assertEquals(OperationEventType.IDENTIFICATION_COMPLETE, testEventHandler.waitForEvent().getEventType()); + Assertions.assertEquals(OperationEventType.REQUEST_SENT, testEventHandler.waitForEvent().getEventType()); DeleteFileRequest receivedPutFileRequest1 = pillar1Receiver.waitForMessage(DeleteFileRequest.class); - Assert.assertEquals(receivedPutFileRequest1.getChecksumRequestForExistingFile(), checksumSpecTYPE); + Assertions.assertEquals(receivedPutFileRequest1.getChecksumRequestForExistingFile(), checksumSpecTYPE); } - @Test(groups={"regressiontest"}) + @Test + @Tag("regressiontest") public void deleteOnChecksumPillarWithSaltedReturnChecksumType() throws Exception { addDescription("Verify that the DeleteClient works correctly when a return checksum with a salt " + "is requested. "); @@ -502,12 +514,12 @@ public void deleteOnChecksumPillarWithSaltedReturnChecksumType() throws Exceptio checksumSpecTYPE.setChecksumSalt(Base16Utils.encodeBase16("aa")); deleteClient.deleteFile(collectionID, DEFAULT_FILE_ID, PILLAR1_ID, TestFileHelper.getDefaultFileChecksum(), checksumSpecTYPE, testEventHandler, null); - Assert.assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.IDENTIFY_REQUEST_SENT); + Assertions.assertEquals(OperationEventType.IDENTIFY_REQUEST_SENT, testEventHandler.waitForEvent().getEventType()); IdentifyPillarsForDeleteFileRequest receivedIdentifyRequestMessage = collectionReceiver.waitForMessage( IdentifyPillarsForDeleteFileRequest.class); addStep("Send a response from pillar1 with PillarChecksumSpec element set, indicating that this is a " + - "checksum pillar.", + "checksum pillar.", "Following events should be generated: COMPONENT_IDENTIFIED, IDENTIFICATION_COMPLETE and a " + "REQUEST_SENT. A request should be sent to pillar1 without a request for a return checksum."); IdentifyPillarsForDeleteFileResponse identifyResponse @@ -517,18 +529,19 @@ public void deleteOnChecksumPillarWithSaltedReturnChecksumType() throws Exceptio checksumSpecTYPEFromPillar.setChecksumType(ChecksumType.MD5); identifyResponse.setPillarChecksumSpec(checksumSpecTYPEFromPillar); messageBus.sendMessage(identifyResponse); - Assert.assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.COMPONENT_IDENTIFIED); - Assert.assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.IDENTIFICATION_COMPLETE); - Assert.assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.REQUEST_SENT); + Assertions.assertEquals(OperationEventType.COMPONENT_IDENTIFIED, testEventHandler.waitForEvent().getEventType()); + Assertions.assertEquals(OperationEventType.IDENTIFICATION_COMPLETE, testEventHandler.waitForEvent().getEventType()); + Assertions.assertEquals(OperationEventType.REQUEST_SENT, testEventHandler.waitForEvent().getEventType()); DeleteFileRequest receivedPutFileRequest1 = pillar1Receiver.waitForMessage(DeleteFileRequest.class); - Assert.assertNull(receivedPutFileRequest1.getChecksumRequestForExistingFile()); + Assertions.assertNull(receivedPutFileRequest1.getChecksumRequestForExistingFile()); } /** * Creates a new test DeleteFileClient based on the supplied settings. - * + *

* Note that the normal way of creating client through the module factory would reuse components with settings from * previous tests. + * * @return A new DeleteFileClient(Wrapper). */ private DeleteFileClient createDeleteFileClient() { diff --git a/bitrepository-client/src/test/java/org/bitrepository/modify/deletefile/DeleteFileClientTestWrapper.java b/bitrepository-client/src/test/java/org/bitrepository/modify/deletefile/DeleteFileClientTestWrapper.java index 25b7ab2a4..c59a41fee 100644 --- a/bitrepository-client/src/test/java/org/bitrepository/modify/deletefile/DeleteFileClientTestWrapper.java +++ b/bitrepository-client/src/test/java/org/bitrepository/modify/deletefile/DeleteFileClientTestWrapper.java @@ -34,9 +34,9 @@ */ public class DeleteFileClientTestWrapper implements DeleteFileClient { /** The PutClient to wrap. */ - private DeleteFileClient wrappedDeleteClient; + private final DeleteFileClient wrappedDeleteClient; /** The manager to monitor the operations.*/ - private TestEventManager testEventManager; + private final TestEventManager testEventManager; /** * Constructor. diff --git a/bitrepository-client/src/test/java/org/bitrepository/modify/putfile/PutFileClientComponentTest.java b/bitrepository-client/src/test/java/org/bitrepository/modify/putfile/PutFileClientComponentTest.java index 8fc300a60..293cdb574 100644 --- a/bitrepository-client/src/test/java/org/bitrepository/modify/putfile/PutFileClientComponentTest.java +++ b/bitrepository-client/src/test/java/org/bitrepository/modify/putfile/PutFileClientComponentTest.java @@ -1,23 +1,23 @@ /* * #%L * Bitrepository Access Client - * + * * $Id$ * $HeadURL$ * %% * Copyright (C) 2010 - 2011 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% @@ -40,38 +40,42 @@ import org.bitrepository.common.utils.Base16Utils; import org.bitrepository.common.utils.TestFileHelper; import org.bitrepository.modify.ModifyComponentFactory; -import org.testng.Assert; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; import javax.xml.datatype.DatatypeFactory; import java.math.BigInteger; import java.util.concurrent.TimeUnit; -import static org.testng.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; + public class PutFileClientComponentTest extends DefaultFixtureClientTest { private TestPutFileMessageFactory messageFactory; private DatatypeFactory datatypeFactory; - @BeforeMethod(alwaysRun=true) + @BeforeEach public void initialise() throws Exception { messageFactory = new TestPutFileMessageFactory(settingsForTestClient.getComponentID()); datatypeFactory = DatatypeFactory.newInstance(); } - @Test(groups={"regressiontest"}) + @Test + @Tag("regressiontest") public void verifyPutClientFromFactory() { addDescription("Testing the initialization through the ModifyComponentFactory."); addStep("Use the ModifyComponentFactory to instantiate a PutFileClient.", "It should be an instance of SimplePutFileClient"); PutFileClient pfc = ModifyComponentFactory.getInstance().retrievePutClient( settingsForCUT, securityManager, settingsForTestClient.getComponentID()); - Assert.assertTrue(pfc instanceof ConversationBasedPutFileClient, "The PutFileClient '" + pfc + "' should be instance of '" + Assertions.assertInstanceOf(ConversationBasedPutFileClient.class, pfc, "The PutFileClient '" + pfc + "' should be instance of '" + ConversationBasedPutFileClient.class.getName() + "'"); } - @Test(groups={"regressiontest"}) + @Test + @Tag("regressiontest") public void normalPutFile() throws Exception { addDescription("Tests the PutClient. Makes a whole conversation for the put client for a 'good' scenario."); addFixture("Initialise the number of pillars to one"); @@ -92,55 +96,56 @@ public void normalPutFile() throws Exception { IdentifyPillarsForPutFileRequest receivedIdentifyRequestMessage = collectionReceiver.waitForMessage(IdentifyPillarsForPutFileRequest.class); assertEquals(receivedIdentifyRequestMessage.getCollectionID(), collectionID); - Assert.assertNotNull(receivedIdentifyRequestMessage.getCorrelationID()); + Assertions.assertNotNull(receivedIdentifyRequestMessage.getCorrelationID()); assertEquals(receivedIdentifyRequestMessage.getReplyTo(), settingsForCUT.getReceiverDestinationID()); - assertEquals(receivedIdentifyRequestMessage.getFileID(), DEFAULT_FILE_ID); + assertEquals(DEFAULT_FILE_ID, receivedIdentifyRequestMessage.getFileID()); assertEquals(receivedIdentifyRequestMessage.getFrom(), settingsForTestClient.getComponentID()); assertEquals(receivedIdentifyRequestMessage.getDestination(), settingsForTestClient.getCollectionDestination()); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.IDENTIFY_REQUEST_SENT); + assertEquals(OperationEventType.IDENTIFY_REQUEST_SENT, testEventHandler.waitForEvent().getEventType()); addStep("Make response for the pillar.", "The client should then send the actual PutFileRequest."); IdentifyPillarsForPutFileResponse identifyResponse = messageFactory.createIdentifyPillarsForPutFileResponse( - receivedIdentifyRequestMessage, PILLAR1_ID, pillar1DestinationId); + receivedIdentifyRequestMessage, PILLAR1_ID, pillar1DestinationId); messageBus.sendMessage(identifyResponse); PutFileRequest receivedPutFileRequest = pillar1Receiver.waitForMessage(PutFileRequest.class, 10, TimeUnit.SECONDS); assertEquals(receivedPutFileRequest.getCollectionID(), collectionID); assertEquals(receivedPutFileRequest.getCorrelationID(), receivedIdentifyRequestMessage.getCorrelationID()); assertEquals(receivedPutFileRequest.getReplyTo(), settingsForCUT.getReceiverDestinationID()); - assertEquals(receivedPutFileRequest.getFileID(), DEFAULT_FILE_ID); + assertEquals(DEFAULT_FILE_ID, receivedPutFileRequest.getFileID()); assertEquals(receivedPutFileRequest.getFrom(), settingsForTestClient.getComponentID()); assertEquals(receivedPutFileRequest.getDestination(), pillar1DestinationId); addStep("Validate the steps of the PutClient by going through the events.", "Should be 'PillarIdentified', " + "'PillarSelected' and 'RequestSent'"); - for(int i = 0; i < settingsForCUT.getRepositorySettings().getCollections().getCollection().get(0).getPillarIDs().getPillarID().size(); i++) { - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.COMPONENT_IDENTIFIED); + for (int i = 0; i < settingsForCUT.getRepositorySettings().getCollections().getCollection().get(0).getPillarIDs().getPillarID().size(); i++) { + assertEquals(OperationEventType.COMPONENT_IDENTIFIED, testEventHandler.waitForEvent().getEventType()); } - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.IDENTIFICATION_COMPLETE); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.REQUEST_SENT); + assertEquals(OperationEventType.IDENTIFICATION_COMPLETE, testEventHandler.waitForEvent().getEventType()); + assertEquals(OperationEventType.REQUEST_SENT, testEventHandler.waitForEvent().getEventType()); addStep("The pillar sends a progress response to the PutClient.", "Should be caught by the event handler."); - PutFileProgressResponse putFileProgressResponse = messageFactory.createPutFileProgressResponse( - receivedPutFileRequest, PILLAR1_ID, pillar1DestinationId); - messageBus.sendMessage(putFileProgressResponse); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.PROGRESS); + PutFileProgressResponse putFileProgressResponse = messageFactory.createPutFileProgressResponse( + receivedPutFileRequest, PILLAR1_ID, pillar1DestinationId); + messageBus.sendMessage(putFileProgressResponse); + assertEquals(OperationEventType.PROGRESS, testEventHandler.waitForEvent().getEventType()); addStep("Send a final response message to the PutClient.", "Should be caught by the event handler. First a PartiallyComplete, then a Complete."); - PutFileFinalResponse putFileFinalResponse = messageFactory.createPutFileFinalResponse( - receivedPutFileRequest, PILLAR1_ID, pillar1DestinationId); - messageBus.sendMessage(putFileFinalResponse); - for(int i = 1; i < 2* settingsForCUT.getRepositorySettings().getCollections().getCollection().get(0).getPillarIDs().getPillarID().size(); i++) { + PutFileFinalResponse putFileFinalResponse = messageFactory.createPutFileFinalResponse( + receivedPutFileRequest, PILLAR1_ID, pillar1DestinationId); + messageBus.sendMessage(putFileFinalResponse); + for (int i = 1; i < 2 * settingsForCUT.getRepositorySettings().getCollections().getCollection().get(0).getPillarIDs().getPillarID().size(); i++) { OperationEventType eventType = testEventHandler.waitForEvent().getEventType(); - Assert.assertTrue( (eventType == OperationEventType.COMPONENT_COMPLETE) - || (eventType == OperationEventType.PROGRESS), + Assertions.assertTrue((eventType == OperationEventType.COMPONENT_COMPLETE) + || (eventType == OperationEventType.PROGRESS), "Expected either PartiallyComplete or Progress, but was: " + eventType); } - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.COMPLETE); + assertEquals(OperationEventType.COMPLETE, testEventHandler.waitForEvent().getEventType()); } - @Test(groups={"regressiontest"}) + @Test + @Tag("regressiontest") public void noPillarsResponding() throws Exception { addDescription("Tests the handling of missing identification responses from all pillar"); addFixture("Sets the identification timeout to 100 ms."); @@ -154,18 +159,19 @@ public void noPillarsResponding() throws Exception { "An identification request should be dispatched."); putClient.putFile(collectionID, httpServerConfiguration.getURL(DEFAULT_FILE_ID), DEFAULT_FILE_ID, 0, null, null, testEventHandler, null); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.IDENTIFY_REQUEST_SENT); + assertEquals(OperationEventType.IDENTIFY_REQUEST_SENT, testEventHandler.waitForEvent().getEventType()); collectionReceiver.waitForMessage(IdentifyPillarsForPutFileRequest.class); addStep("Do not respond. Just await the timeout.", "An IDENTIFY_TIMEOUT event should be generate, followed by a FAILED event."); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.IDENTIFY_TIMEOUT); - Assert.assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.COMPONENT_FAILED); - Assert.assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.COMPONENT_FAILED); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.FAILED); + assertEquals(OperationEventType.IDENTIFY_TIMEOUT, testEventHandler.waitForEvent().getEventType()); + assertEquals(OperationEventType.COMPONENT_FAILED, testEventHandler.waitForEvent().getEventType()); + assertEquals(OperationEventType.COMPONENT_FAILED, testEventHandler.waitForEvent().getEventType()); + assertEquals(OperationEventType.FAILED, testEventHandler.waitForEvent().getEventType()); } - @Test(groups={"regressiontest"}) + @Test + @Tag("regressiontest") public void onePillarRespondingWithPartialPutAllowed() throws Exception { addReference("" + "BITMAG-598 It should be possible to putFiles, even though only a subset of the pillars are available"); @@ -183,7 +189,7 @@ public void onePillarRespondingWithPartialPutAllowed() throws Exception { "A identification request should be dispatched."); putClient.putFile(collectionID, httpServerConfiguration.getURL(DEFAULT_FILE_ID), DEFAULT_FILE_ID, 0, null, null, testEventHandler, null); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.IDENTIFY_REQUEST_SENT); + assertEquals(OperationEventType.IDENTIFY_REQUEST_SENT, testEventHandler.waitForEvent().getEventType()); IdentifyPillarsForPutFileRequest receivedIdentifyRequestMessage = collectionReceiver.waitForMessage(IdentifyPillarsForPutFileRequest.class); @@ -192,17 +198,17 @@ public void onePillarRespondingWithPartialPutAllowed() throws Exception { IdentifyPillarsForPutFileResponse identifyResponse = messageFactory.createIdentifyPillarsForPutFileResponse( receivedIdentifyRequestMessage, PILLAR1_ID, pillar1DestinationId); messageBus.sendMessage(identifyResponse); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.COMPONENT_IDENTIFIED); + assertEquals(OperationEventType.COMPONENT_IDENTIFIED, testEventHandler.waitForEvent().getEventType()); addStep("Await the timeout.", "An IDENTIFY_TIMEOUT events, a COMPONENT_FAILED " + "event for the non-responding pillar and an IDENTIFICATION_COMPLETE event should be generated."); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.IDENTIFY_TIMEOUT); - Assert.assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.COMPONENT_FAILED); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.IDENTIFICATION_COMPLETE); + assertEquals(OperationEventType.IDENTIFY_TIMEOUT, testEventHandler.waitForEvent().getEventType()); + assertEquals(OperationEventType.COMPONENT_FAILED, testEventHandler.waitForEvent().getEventType()); + assertEquals(OperationEventType.IDENTIFICATION_COMPLETE, testEventHandler.waitForEvent().getEventType()); addStep("The client should proceed to send a putFileOperation request to the responding pillar.", "A REQUEST_SENT event should be generated and a PutFileRequest should be received on the pillar."); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.REQUEST_SENT); + assertEquals(OperationEventType.REQUEST_SENT, testEventHandler.waitForEvent().getEventType()); PutFileRequest receivedPutFileRequest = pillar1Receiver.waitForMessage(PutFileRequest.class); addStep("Send a pillar complete event", @@ -210,11 +216,12 @@ public void onePillarRespondingWithPartialPutAllowed() throws Exception { PutFileFinalResponse putFileFinalResponse = messageFactory.createPutFileFinalResponse( receivedPutFileRequest, PILLAR1_ID, pillar1DestinationId); messageBus.sendMessage(putFileFinalResponse); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.COMPONENT_COMPLETE); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.FAILED); + assertEquals(OperationEventType.COMPONENT_COMPLETE, testEventHandler.waitForEvent().getEventType()); + assertEquals(OperationEventType.FAILED, testEventHandler.waitForEvent().getEventType()); } - @Test(groups={"regressiontest"}) + @Test + @Tag("regressiontest") public void onePillarRespondingWithPartialPutDisallowed() throws Exception { addDescription("Tests the handling of missing identification responses from one pillar, " + "when partial put are allowed"); @@ -230,7 +237,7 @@ public void onePillarRespondingWithPartialPutDisallowed() throws Exception { "A identification request should be dispatched."); putClient.putFile(collectionID, httpServerConfiguration.getURL(DEFAULT_FILE_ID), DEFAULT_FILE_ID, 0, null, null, testEventHandler, null); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.IDENTIFY_REQUEST_SENT); + assertEquals(OperationEventType.IDENTIFY_REQUEST_SENT, testEventHandler.waitForEvent().getEventType()); IdentifyPillarsForPutFileRequest receivedIdentifyRequestMessage = collectionReceiver.waitForMessage(IdentifyPillarsForPutFileRequest.class); @@ -239,18 +246,19 @@ public void onePillarRespondingWithPartialPutDisallowed() throws Exception { IdentifyPillarsForPutFileResponse identifyResponse = messageFactory.createIdentifyPillarsForPutFileResponse( receivedIdentifyRequestMessage, PILLAR1_ID, pillar1DestinationId); messageBus.sendMessage(identifyResponse); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.COMPONENT_IDENTIFIED); + assertEquals(OperationEventType.COMPONENT_IDENTIFIED, testEventHandler.waitForEvent().getEventType()); addStep("Await the timeout.", "An IDENTIFY_TIMEOUT event ,COMPONENT_FAILED " + "event for the non-responding pillar, an IDENTIFICATION_COMPLETE and " + "lastly a OperationEventType.FAILED event should be generated."); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.IDENTIFY_TIMEOUT); - Assert.assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.COMPONENT_FAILED); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.FAILED); + assertEquals(OperationEventType.IDENTIFY_TIMEOUT, testEventHandler.waitForEvent().getEventType()); + assertEquals(OperationEventType.COMPONENT_FAILED, testEventHandler.waitForEvent().getEventType()); + assertEquals(OperationEventType.FAILED, testEventHandler.waitForEvent().getEventType()); } - @Test(groups={"regressiontest"}) + @Test + @Tag("regressiontest") public void putClientOperationTimeout() throws Exception { addDescription("Tests the handling of a failed operation for the PutClient"); addStep("Initialise the number of pillars and the PutClient. Sets the operation timeout to 100 ms.", @@ -269,7 +277,7 @@ public void putClientOperationTimeout() throws Exception { IdentifyPillarsForPutFileRequest receivedIdentifyRequestMessage = collectionReceiver.waitForMessage(IdentifyPillarsForPutFileRequest.class); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.IDENTIFY_REQUEST_SENT); + assertEquals(OperationEventType.IDENTIFY_REQUEST_SENT, testEventHandler.waitForEvent().getEventType()); addStep("Make response for the pillar.", "The client should then send the actual PutFileRequest."); IdentifyPillarsForPutFileResponse identifyResponse = messageFactory @@ -280,18 +288,19 @@ public void putClientOperationTimeout() throws Exception { addStep("Validate the steps of the PutClient by going through the events.", "Should be 'PillarIdentified', " + "'PillarSelected' and 'RequestSent'"); - for(int i = 0; i < settingsForCUT.getRepositorySettings().getCollections().getCollection().get(0).getPillarIDs().getPillarID().size(); i++) { - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.COMPONENT_IDENTIFIED); + for (int i = 0; i < settingsForCUT.getRepositorySettings().getCollections().getCollection().get(0).getPillarIDs().getPillarID().size(); i++) { + assertEquals(OperationEventType.COMPONENT_IDENTIFIED, testEventHandler.waitForEvent().getEventType()); } - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.IDENTIFICATION_COMPLETE); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.REQUEST_SENT); + assertEquals(OperationEventType.IDENTIFICATION_COMPLETE, testEventHandler.waitForEvent().getEventType()); + assertEquals(OperationEventType.REQUEST_SENT, testEventHandler.waitForEvent().getEventType()); addStep("Do not respond. Just await the timeout.", "Should make send a Failure event to the eventhandler."); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.FAILED); + assertEquals(OperationEventType.FAILED, testEventHandler.waitForEvent().getEventType()); } - @Test(groups={"regressiontest"}) + @Test + @Tag("regressiontest") public void putClientPillarOperationFailed() throws Exception { addDescription("Tests the handling of a operation failure for the PutClient. "); addStep("Initialise the number of pillars to one", "Should be OK."); @@ -310,7 +319,7 @@ public void putClientPillarOperationFailed() throws Exception { IdentifyPillarsForPutFileRequest receivedIdentifyRequestMessage = collectionReceiver.waitForMessage(IdentifyPillarsForPutFileRequest.class); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.IDENTIFY_REQUEST_SENT); + assertEquals(OperationEventType.IDENTIFY_REQUEST_SENT, testEventHandler.waitForEvent().getEventType()); addStep("Send pillar response.", "The client should then send the actual PutFileRequest."); IdentifyPillarsForPutFileResponse identifyResponse = messageFactory.createIdentifyPillarsForPutFileResponse( @@ -320,26 +329,27 @@ public void putClientPillarOperationFailed() throws Exception { addStep("Validate the steps of the PutClient by going through the events.", "Should be 'PillarIdentified', 'PillarSelected' and 'RequestSent'"); - for(int i = 0; i < settingsForCUT.getRepositorySettings().getCollections().getCollection().get(0).getPillarIDs().getPillarID().size(); i++) { - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.COMPONENT_IDENTIFIED); + for (int i = 0; i < settingsForCUT.getRepositorySettings().getCollections().getCollection().get(0).getPillarIDs().getPillarID().size(); i++) { + assertEquals(OperationEventType.COMPONENT_IDENTIFIED, testEventHandler.waitForEvent().getEventType()); } - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.IDENTIFICATION_COMPLETE); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.REQUEST_SENT); + assertEquals(OperationEventType.IDENTIFICATION_COMPLETE, testEventHandler.waitForEvent().getEventType()); + assertEquals(OperationEventType.REQUEST_SENT, testEventHandler.waitForEvent().getEventType()); addStep("Send a failed response message to the PutClient.", "Should be caught by the event handler. First a PillarFailed, then a Complete."); - PutFileFinalResponse putFileFinalResponse = messageFactory.createPutFileFinalResponse( - receivedPutFileRequest, PILLAR1_ID, pillar1DestinationId); - ResponseInfo ri = new ResponseInfo(); - ri.setResponseCode(ResponseCode.FAILURE); - ri.setResponseText("Verifying that a failure can be understood!"); - putFileFinalResponse.setResponseInfo(ri); - messageBus.sendMessage(putFileFinalResponse); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.COMPONENT_FAILED); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.FAILED); + PutFileFinalResponse putFileFinalResponse = messageFactory.createPutFileFinalResponse( + receivedPutFileRequest, PILLAR1_ID, pillar1DestinationId); + ResponseInfo ri = new ResponseInfo(); + ri.setResponseCode(ResponseCode.FAILURE); + ri.setResponseText("Verifying that a failure can be understood!"); + putFileFinalResponse.setResponseInfo(ri); + messageBus.sendMessage(putFileFinalResponse); + assertEquals(OperationEventType.COMPONENT_FAILED, testEventHandler.waitForEvent().getEventType()); + assertEquals(OperationEventType.FAILED, testEventHandler.waitForEvent().getEventType()); } - @Test(groups={"regressiontest"}) + @Test + @Tag("regressiontest") public void fileExistsOnPillarNoChecksumFromPillar() throws Exception { addDescription("Tests that PutClient handles the presence of a file correctly, when the pillar doesn't return a " + "checksum in the identification response. "); @@ -354,12 +364,12 @@ public void fileExistsOnPillarNoChecksumFromPillar() throws Exception { IdentifyPillarsForPutFileRequest receivedIdentifyRequestMessage = collectionReceiver.waitForMessage(IdentifyPillarsForPutFileRequest.class); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.IDENTIFY_REQUEST_SENT); + assertEquals(OperationEventType.IDENTIFY_REQUEST_SENT, testEventHandler.waitForEvent().getEventType()); addStep("Send a DUPLICATE_FILE_FAILURE response without a checksum.", "The client should generate the following events:'" - + OperationEventType.COMPONENT_FAILED + "', '" - + OperationEventType.FAILED + "'"); + + OperationEventType.COMPONENT_FAILED + "', '" + + OperationEventType.FAILED + "'"); IdentifyPillarsForPutFileResponse identifyResponse = messageFactory.createIdentifyPillarsForPutFileResponse( receivedIdentifyRequestMessage, PILLAR1_ID, pillar1DestinationId); ResponseInfo ri = new ResponseInfo(); @@ -368,11 +378,12 @@ public void fileExistsOnPillarNoChecksumFromPillar() throws Exception { identifyResponse.setResponseInfo(ri); messageBus.sendMessage(identifyResponse); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.COMPONENT_FAILED); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.FAILED); + assertEquals(OperationEventType.COMPONENT_FAILED, testEventHandler.waitForEvent().getEventType()); + assertEquals(OperationEventType.FAILED, testEventHandler.waitForEvent().getEventType()); } - @Test(groups={"regressiontest"}) + @Test + @Tag("regressiontest") public void fileExistsOnPillarDifferentChecksumFromPillar() throws Exception { addDescription("Tests that PutClient handles the presence of a file correctly, when the pillar " + "returns a checksum different from the file being put. "); @@ -389,7 +400,7 @@ public void fileExistsOnPillarDifferentChecksumFromPillar() throws Exception { IdentifyPillarsForPutFileRequest receivedIdentifyRequestMessage = collectionReceiver.waitForMessage(IdentifyPillarsForPutFileRequest.class); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.IDENTIFY_REQUEST_SENT); + assertEquals(OperationEventType.IDENTIFY_REQUEST_SENT, testEventHandler.waitForEvent().getEventType()); addStep("Send a DUPLICATE_FILE_FAILURE response with a random checksum.", "The client should generate the following events:'" @@ -406,11 +417,12 @@ public void fileExistsOnPillarDifferentChecksumFromPillar() throws Exception { identifyResponse.setChecksumDataForExistingFile(csPillarData); messageBus.sendMessage(identifyResponse); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.COMPONENT_FAILED); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.FAILED); + assertEquals(OperationEventType.COMPONENT_FAILED, testEventHandler.waitForEvent().getEventType()); + assertEquals(OperationEventType.FAILED, testEventHandler.waitForEvent().getEventType()); } - @Test(groups={"regressiontest"}) + @Test + @Tag("regressiontest") public void sameFileExistsOnOnePillar() throws Exception { addDescription("Tests that PutClient handles the presence of a file correctly, when the pillar " + "returns a checksum equal the file being put (idempotent)."); @@ -426,7 +438,7 @@ public void sameFileExistsOnOnePillar() throws Exception { IdentifyPillarsForPutFileRequest receivedIdentifyRequestMessage = collectionReceiver.waitForMessage(IdentifyPillarsForPutFileRequest.class); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.IDENTIFY_REQUEST_SENT); + assertEquals(OperationEventType.IDENTIFY_REQUEST_SENT, testEventHandler.waitForEvent().getEventType()); addStep("Send a DUPLICATE_FILE_FAILURE response with a checksum equal to the one supplied to the client.", "The client should generate the following events:'" @@ -441,19 +453,19 @@ public void sameFileExistsOnOnePillar() throws Exception { identifyResponse.setChecksumDataForExistingFile(csPillarData); messageBus.sendMessage(identifyResponse); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.COMPONENT_COMPLETE); + assertEquals(OperationEventType.COMPONENT_COMPLETE, testEventHandler.waitForEvent().getEventType()); addStep("Send an identification response from the second pillar.", "An COMPONENT_IDENTIFIED OperationEventType.IDENTIFICATION_COMPLETE and a event should be generate."); IdentifyPillarsForPutFileResponse identifyResponse2 = messageFactory.createIdentifyPillarsForPutFileResponse( receivedIdentifyRequestMessage, PILLAR2_ID, pillar2DestinationId); messageBus.sendMessage(identifyResponse2); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.COMPONENT_IDENTIFIED); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.IDENTIFICATION_COMPLETE); + assertEquals(OperationEventType.COMPONENT_IDENTIFIED, testEventHandler.waitForEvent().getEventType()); + assertEquals(OperationEventType.IDENTIFICATION_COMPLETE, testEventHandler.waitForEvent().getEventType()); addStep("The client should proceed to send a putFileOperation request to the second pillar.", "A REQUEST_SENT event should be generated and a PutFileRequest should be received on the pillar."); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.REQUEST_SENT); + assertEquals(OperationEventType.REQUEST_SENT, testEventHandler.waitForEvent().getEventType()); PutFileRequest receivedPutFileRequest = pillar2Receiver.waitForMessage(PutFileRequest.class); addStep("Send a pillar complete event", @@ -461,11 +473,12 @@ public void sameFileExistsOnOnePillar() throws Exception { PutFileFinalResponse putFileFinalResponse = messageFactory.createPutFileFinalResponse( receivedPutFileRequest, PILLAR2_ID, pillar1DestinationId); messageBus.sendMessage(putFileFinalResponse); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.COMPONENT_COMPLETE); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.COMPLETE); + assertEquals(OperationEventType.COMPONENT_COMPLETE, testEventHandler.waitForEvent().getEventType()); + assertEquals(OperationEventType.COMPLETE, testEventHandler.waitForEvent().getEventType()); } - @Test(groups={"regressiontest"}) + @Test + @Tag("regressiontest") public void fileExistsOnPillarChecksumFromPillarNoClientChecksum() throws Exception { addDescription("Tests that PutClient handles the presence of a file correctly, when the pillar " + "returns a checksum but the putFile was called without a checksum. "); @@ -480,7 +493,7 @@ public void fileExistsOnPillarChecksumFromPillarNoClientChecksum() throws Except IdentifyPillarsForPutFileRequest receivedIdentifyRequestMessage = collectionReceiver.waitForMessage( IdentifyPillarsForPutFileRequest.class); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.IDENTIFY_REQUEST_SENT); + assertEquals(OperationEventType.IDENTIFY_REQUEST_SENT, testEventHandler.waitForEvent().getEventType()); addStep("Send a DUPLICATE_FILE_FAILURE response with a random checksum.", "The client should generate the following events:'" @@ -497,11 +510,12 @@ public void fileExistsOnPillarChecksumFromPillarNoClientChecksum() throws Except identifyResponse.setChecksumDataForExistingFile(csData); messageBus.sendMessage(identifyResponse); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.COMPONENT_FAILED); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.FAILED); + assertEquals(OperationEventType.COMPONENT_FAILED, testEventHandler.waitForEvent().getEventType()); + assertEquals(OperationEventType.FAILED, testEventHandler.waitForEvent().getEventType()); } - @Test(groups={"regressiontest"}) + @Test + @Tag("regressiontest") public void saltedReturnChecksumsWithChecksumPillar() throws Exception { addDescription("Tests that PutClient handles the presence of a ChecksumPillar correctly, when a salted return" + " checksum (which a checksum pillar can't provide) is requested. "); @@ -523,10 +537,10 @@ public void saltedReturnChecksumsWithChecksumPillar() throws Exception { IdentifyPillarsForPutFileRequest receivedIdentifyRequestMessage = collectionReceiver.waitForMessage( IdentifyPillarsForPutFileRequest.class); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.IDENTIFY_REQUEST_SENT); + assertEquals(OperationEventType.IDENTIFY_REQUEST_SENT, testEventHandler.waitForEvent().getEventType()); addStep("Send an identification response with a PillarChecksumSpec element set, indicating that this is a " + - "checksum pillar.", + "checksum pillar.", "An COMPONENT_IDENTIFIED event should be generate."); IdentifyPillarsForPutFileResponse identifyResponse = messageFactory.createIdentifyPillarsForPutFileResponse( receivedIdentifyRequestMessage, PILLAR1_ID, pillar1DestinationId); @@ -534,7 +548,7 @@ public void saltedReturnChecksumsWithChecksumPillar() throws Exception { checksumSpecTYPEFromPillar.setChecksumType(ChecksumType.MD5); identifyResponse.setPillarChecksumSpec(checksumSpecTYPEFromPillar); messageBus.sendMessage(identifyResponse); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.COMPONENT_IDENTIFIED); + assertEquals(OperationEventType.COMPONENT_IDENTIFIED, testEventHandler.waitForEvent().getEventType()); addStep("Send an normal identification response from pillar2.", "An COMPONENT_IDENTIFIED event should be generate followed by an IDENTIFICATION_COMPLETE and a " + @@ -544,11 +558,11 @@ public void saltedReturnChecksumsWithChecksumPillar() throws Exception { IdentifyPillarsForPutFileResponse identifyResponse2 = messageFactory.createIdentifyPillarsForPutFileResponse( receivedIdentifyRequestMessage, PILLAR2_ID, pillar2DestinationId); messageBus.sendMessage(identifyResponse2); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.COMPONENT_IDENTIFIED); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.IDENTIFICATION_COMPLETE); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.REQUEST_SENT); + assertEquals(OperationEventType.COMPONENT_IDENTIFIED, testEventHandler.waitForEvent().getEventType()); + assertEquals(OperationEventType.IDENTIFICATION_COMPLETE, testEventHandler.waitForEvent().getEventType()); + assertEquals(OperationEventType.REQUEST_SENT, testEventHandler.waitForEvent().getEventType()); PutFileRequest receivedPutFileRequest1 = pillar1Receiver.waitForMessage(PutFileRequest.class); - Assert.assertNull(receivedPutFileRequest1.getChecksumRequestForNewFile()); + Assertions.assertNull(receivedPutFileRequest1.getChecksumRequestForNewFile()); PutFileRequest receivedPutFileRequest2 = pillar2Receiver.waitForMessage(PutFileRequest.class); @@ -556,7 +570,8 @@ public void saltedReturnChecksumsWithChecksumPillar() throws Exception { } - @Test(groups={"regressiontest"}) + @Test + @Tag("regressiontest") public void defaultReturnChecksumsWithChecksumPillar() throws Exception { addDescription("Tests that PutClient handles the presence of a ChecksumPillar correctly, when a return" + " checksum of default type is requested (which a checksum pillar can provide). "); @@ -574,10 +589,10 @@ public void defaultReturnChecksumsWithChecksumPillar() throws Exception { IdentifyPillarsForPutFileRequest receivedIdentifyRequestMessage = collectionReceiver.waitForMessage( IdentifyPillarsForPutFileRequest.class); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.IDENTIFY_REQUEST_SENT); + assertEquals(OperationEventType.IDENTIFY_REQUEST_SENT, testEventHandler.waitForEvent().getEventType()); addStep("Send an identification response with a PillarChecksumSpec element set, indicating that this is a " + - "checksum pillar.", + "checksum pillar.", "An COMPONENT_IDENTIFIED event should be generate."); IdentifyPillarsForPutFileResponse identifyResponse = messageFactory.createIdentifyPillarsForPutFileResponse( receivedIdentifyRequestMessage, PILLAR1_ID, pillar1DestinationId); @@ -585,7 +600,7 @@ public void defaultReturnChecksumsWithChecksumPillar() throws Exception { checksumSpecTYPEFromPillar.setChecksumType(ChecksumType.MD5); identifyResponse.setPillarChecksumSpec(checksumSpecTYPEFromPillar); messageBus.sendMessage(identifyResponse); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.COMPONENT_IDENTIFIED); + assertEquals(OperationEventType.COMPONENT_IDENTIFIED, testEventHandler.waitForEvent().getEventType()); addStep("Send an normal identification response from pillar2.", "An COMPONENT_IDENTIFIED event should be generate followed by an IDENTIFICATION_COMPLETE and a " + @@ -595,9 +610,9 @@ public void defaultReturnChecksumsWithChecksumPillar() throws Exception { IdentifyPillarsForPutFileResponse identifyResponse2 = messageFactory.createIdentifyPillarsForPutFileResponse( receivedIdentifyRequestMessage, PILLAR2_ID, pillar2DestinationId); messageBus.sendMessage(identifyResponse2); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.COMPONENT_IDENTIFIED); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.IDENTIFICATION_COMPLETE); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.REQUEST_SENT); + assertEquals(OperationEventType.COMPONENT_IDENTIFIED, testEventHandler.waitForEvent().getEventType()); + assertEquals(OperationEventType.IDENTIFICATION_COMPLETE, testEventHandler.waitForEvent().getEventType()); + assertEquals(OperationEventType.REQUEST_SENT, testEventHandler.waitForEvent().getEventType()); PutFileRequest receivedPutFileRequest1 = pillar1Receiver.waitForMessage(PutFileRequest.class); assertEquals(receivedPutFileRequest1.getChecksumRequestForNewFile(), checksumSpecTYPE); @@ -607,7 +622,8 @@ public void defaultReturnChecksumsWithChecksumPillar() throws Exception { assertEquals(receivedPutFileRequest2.getChecksumRequestForNewFile(), checksumSpecTYPE); } - @Test(groups={"regressiontest"}) + @Test + @Tag("regressiontest") public void noReturnChecksumsWithChecksumPillar() throws Exception { addDescription("Tests that PutClient handles the presence of a ChecksumPillar correctly, when no return" + " checksum is requested."); @@ -623,10 +639,10 @@ public void noReturnChecksumsWithChecksumPillar() throws Exception { IdentifyPillarsForPutFileRequest receivedIdentifyRequestMessage = collectionReceiver.waitForMessage( IdentifyPillarsForPutFileRequest.class); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.IDENTIFY_REQUEST_SENT); + assertEquals(OperationEventType.IDENTIFY_REQUEST_SENT, testEventHandler.waitForEvent().getEventType()); addStep("Send an identification response with a PillarChecksumSpec element set, indicating that this is a " + - "checksum pillar.", + "checksum pillar.", "An COMPONENT_IDENTIFIED event should be generate."); IdentifyPillarsForPutFileResponse identifyResponse = messageFactory.createIdentifyPillarsForPutFileResponse( receivedIdentifyRequestMessage, PILLAR1_ID, pillar1DestinationId); @@ -634,7 +650,7 @@ public void noReturnChecksumsWithChecksumPillar() throws Exception { checksumSpecTYPEFromPillar.setChecksumType(ChecksumType.MD5); identifyResponse.setPillarChecksumSpec(checksumSpecTYPEFromPillar); messageBus.sendMessage(identifyResponse); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.COMPONENT_IDENTIFIED); + assertEquals(OperationEventType.COMPONENT_IDENTIFIED, testEventHandler.waitForEvent().getEventType()); addStep("Send an normal identification response from pillar2.", "An COMPONENT_IDENTIFIED event should be generate followed by an IDENTIFICATION_COMPLETE and a " + @@ -643,17 +659,18 @@ public void noReturnChecksumsWithChecksumPillar() throws Exception { IdentifyPillarsForPutFileResponse identifyResponse2 = messageFactory.createIdentifyPillarsForPutFileResponse( receivedIdentifyRequestMessage, PILLAR2_ID, pillar2DestinationId); messageBus.sendMessage(identifyResponse2); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.COMPONENT_IDENTIFIED); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.IDENTIFICATION_COMPLETE); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.REQUEST_SENT); + assertEquals(OperationEventType.COMPONENT_IDENTIFIED, testEventHandler.waitForEvent().getEventType()); + assertEquals(OperationEventType.IDENTIFICATION_COMPLETE, testEventHandler.waitForEvent().getEventType()); + assertEquals(OperationEventType.REQUEST_SENT, testEventHandler.waitForEvent().getEventType()); PutFileRequest receivedPutFileRequest1 = pillar1Receiver.waitForMessage(PutFileRequest.class); - Assert.assertNull(receivedPutFileRequest1.getChecksumRequestForNewFile()); + Assertions.assertNull(receivedPutFileRequest1.getChecksumRequestForNewFile()); PutFileRequest receivedPutFileRequest2 = pillar2Receiver.waitForMessage(PutFileRequest.class); - Assert.assertNull(receivedPutFileRequest2.getChecksumRequestForNewFile()); + Assertions.assertNull(receivedPutFileRequest2.getChecksumRequestForNewFile()); } - - @Test(groups={"regressiontest"}) + + @Test + @Tag("regressiontest") public void onePillarPutRetrySuccess() throws Exception { addReference("" + "BITMAG-810 Reference client should be able to retry failed file transfers"); @@ -670,7 +687,7 @@ public void onePillarPutRetrySuccess() throws Exception { "A identification request should be dispatched."); putClient.putFile(collectionID, httpServerConfiguration.getURL(DEFAULT_FILE_ID), DEFAULT_FILE_ID, 0, null, null, testEventHandler, null); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.IDENTIFY_REQUEST_SENT); + assertEquals(OperationEventType.IDENTIFY_REQUEST_SENT, testEventHandler.waitForEvent().getEventType()); IdentifyPillarsForPutFileRequest receivedIdentifyRequestMessage = collectionReceiver.waitForMessage(IdentifyPillarsForPutFileRequest.class); @@ -679,12 +696,12 @@ public void onePillarPutRetrySuccess() throws Exception { IdentifyPillarsForPutFileResponse identifyResponse = messageFactory.createIdentifyPillarsForPutFileResponse( receivedIdentifyRequestMessage, PILLAR1_ID, pillar1DestinationId); messageBus.sendMessage(identifyResponse); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.COMPONENT_IDENTIFIED); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.IDENTIFICATION_COMPLETE); + assertEquals(OperationEventType.COMPONENT_IDENTIFIED, testEventHandler.waitForEvent().getEventType()); + assertEquals(OperationEventType.IDENTIFICATION_COMPLETE, testEventHandler.waitForEvent().getEventType()); addStep("The client should proceed to send a putFileOperation request to the responding pillar.", "A REQUEST_SENT event should be generated and a PutFileRequest should be received on the pillar."); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.REQUEST_SENT); + assertEquals(OperationEventType.REQUEST_SENT, testEventHandler.waitForEvent().getEventType()); PutFileRequest receivedPutFileRequest = pillar1Receiver.waitForMessage(PutFileRequest.class); addStep("Send a PutFileFinalResponse indicating a FILE_TRANSFER_FAILURE", @@ -692,25 +709,26 @@ public void onePillarPutRetrySuccess() throws Exception { PutFileFinalResponse putFileFinalResponse = messageFactory.createPutFileFinalResponse( receivedPutFileRequest, PILLAR1_ID, pillar1DestinationId); putFileFinalResponse.getResponseInfo().setResponseCode(ResponseCode.FILE_TRANSFER_FAILURE); - messageBus.sendMessage(putFileFinalResponse); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.WARNING); - + messageBus.sendMessage(putFileFinalResponse); + assertEquals(OperationEventType.WARNING, testEventHandler.waitForEvent().getEventType()); + addStep("A new PutFileRequest is send, pillar responds with success", "The client generates " + - "a COMPONENT_COMPLETE, followed by a COMPLETE event."); + "a COMPONENT_COMPLETE, followed by a COMPLETE event."); PutFileRequest receivedPutFileRequest2 = pillar1Receiver.waitForMessage(PutFileRequest.class); PutFileFinalResponse putFileFinalResponse2 = messageFactory.createPutFileFinalResponse( receivedPutFileRequest2, PILLAR1_ID, pillar1DestinationId); messageBus.sendMessage(putFileFinalResponse2); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.COMPONENT_COMPLETE); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.COMPLETE); + assertEquals(OperationEventType.COMPONENT_COMPLETE, testEventHandler.waitForEvent().getEventType()); + assertEquals(OperationEventType.COMPLETE, testEventHandler.waitForEvent().getEventType()); } - @Test(groups={"regressiontest"}) + @Test + @Tag("regressiontest") public void onePillarPutRetryFailure() throws Exception { addReference("" + "BITMAG-810 Reference client should be able to retry failed file transfers"); addDescription("Tests that a putfile attempt failing due to FILE_TRANSFER_FAILURE " + - "is only attempted the maximum allowed attempts"); + "is only attempted the maximum allowed attempts"); addFixture("Sets the identification timeout to 3 sec, allow two retries and only register one pillar."); settingsForCUT.getReferenceSettings().getClientSettings().setOperationRetryCount(BigInteger.valueOf(2)); @@ -723,7 +741,7 @@ public void onePillarPutRetryFailure() throws Exception { "A identification request should be dispatched."); putClient.putFile(collectionID, httpServerConfiguration.getURL(DEFAULT_FILE_ID), DEFAULT_FILE_ID, 0, null, null, testEventHandler, null); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.IDENTIFY_REQUEST_SENT); + assertEquals(OperationEventType.IDENTIFY_REQUEST_SENT, testEventHandler.waitForEvent().getEventType()); IdentifyPillarsForPutFileRequest receivedIdentifyRequestMessage = collectionReceiver.waitForMessage(IdentifyPillarsForPutFileRequest.class); @@ -732,12 +750,12 @@ public void onePillarPutRetryFailure() throws Exception { IdentifyPillarsForPutFileResponse identifyResponse = messageFactory.createIdentifyPillarsForPutFileResponse( receivedIdentifyRequestMessage, PILLAR1_ID, pillar1DestinationId); messageBus.sendMessage(identifyResponse); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.COMPONENT_IDENTIFIED); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.IDENTIFICATION_COMPLETE); + assertEquals(OperationEventType.COMPONENT_IDENTIFIED, testEventHandler.waitForEvent().getEventType()); + assertEquals(OperationEventType.IDENTIFICATION_COMPLETE, testEventHandler.waitForEvent().getEventType()); addStep("The client should proceed to send a putFileOperation request to the responding pillar.", "A REQUEST_SENT event should be generated and a PutFileRequest should be received on the pillar."); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.REQUEST_SENT); + assertEquals(OperationEventType.REQUEST_SENT, testEventHandler.waitForEvent().getEventType()); PutFileRequest receivedPutFileRequest = pillar1Receiver.waitForMessage(PutFileRequest.class); addStep("Send a PutFileFinalResponse indicating a FILE_TRANSFER_FAILURE", @@ -745,9 +763,9 @@ public void onePillarPutRetryFailure() throws Exception { PutFileFinalResponse putFileFinalResponse = messageFactory.createPutFileFinalResponse( receivedPutFileRequest, PILLAR1_ID, pillar1DestinationId); putFileFinalResponse.getResponseInfo().setResponseCode(ResponseCode.FILE_TRANSFER_FAILURE); - messageBus.sendMessage(putFileFinalResponse); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.WARNING); - + messageBus.sendMessage(putFileFinalResponse); + assertEquals(OperationEventType.WARNING, testEventHandler.waitForEvent().getEventType()); + addStep("Send a PutFileFinalResponse indicating a FILE_TRANSFER_FAILURE for the second put attempt", "The client should emit a warning event and generate new PutFileRequest for the pillar"); receivedPutFileRequest = pillar1Receiver.waitForMessage(PutFileRequest.class); @@ -755,8 +773,8 @@ public void onePillarPutRetryFailure() throws Exception { receivedPutFileRequest, PILLAR1_ID, pillar1DestinationId); putFileFinalResponse.getResponseInfo().setResponseCode(ResponseCode.FILE_TRANSFER_FAILURE); messageBus.sendMessage(putFileFinalResponse); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.WARNING); - + assertEquals(OperationEventType.WARNING, testEventHandler.waitForEvent().getEventType()); + addStep("Send a PutFileFinalResponse indicating a FILE_TRANSFER_FAILURE for the third put attempt", "The client should emit a COMPONENT_FAILED event and fail the put operation"); receivedPutFileRequest = pillar1Receiver.waitForMessage(PutFileRequest.class); @@ -764,11 +782,12 @@ public void onePillarPutRetryFailure() throws Exception { receivedPutFileRequest, PILLAR1_ID, pillar1DestinationId); putFileFinalResponse.getResponseInfo().setResponseCode(ResponseCode.FILE_TRANSFER_FAILURE); messageBus.sendMessage(putFileFinalResponse); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.COMPONENT_FAILED); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.FAILED); + assertEquals(OperationEventType.COMPONENT_FAILED, testEventHandler.waitForEvent().getEventType()); + assertEquals(OperationEventType.FAILED, testEventHandler.waitForEvent().getEventType()); } - @Test(groups={"regressiontest"}) + @Test + @Tag("regressiontest") public void putToOtherCollection() throws Exception { addReference("" + "BITMAG-925 Client will always try to put to the pillars defined in the first collection"); @@ -782,7 +801,7 @@ public void putToOtherCollection() throws Exception { settingsForCUT.getRepositorySettings().getCollections().getCollection().get(0).getPillarIDs().getPillarID().add(PILLAR2_ID); settingsForCUT.getRepositorySettings().getCollections().getCollection().get(1).getPillarIDs().getPillarID().clear(); settingsForCUT.getRepositorySettings().getCollections().getCollection().get(1).getPillarIDs().getPillarID().add(PILLAR2_ID); - String otherCollection = settingsForCUT.getRepositorySettings().getCollections().getCollection().get(1).getID(); + String otherCollection = settingsForCUT.getRepositorySettings().getCollections().getCollection().get(1).getID(); TestEventHandler testEventHandler = new TestEventHandler(testEventManager); PutFileClient putClient = createPutFileClient(); @@ -790,7 +809,7 @@ public void putToOtherCollection() throws Exception { "A identification request should be dispatched."); putClient.putFile(otherCollection, httpServerConfiguration.getURL(DEFAULT_FILE_ID), DEFAULT_FILE_ID, 0, null, null, testEventHandler, null); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.IDENTIFY_REQUEST_SENT); + assertEquals(OperationEventType.IDENTIFY_REQUEST_SENT, testEventHandler.waitForEvent().getEventType()); IdentifyPillarsForPutFileRequest receivedIdentifyRequestMessage = collectionReceiver.waitForMessage(IdentifyPillarsForPutFileRequest.class); assertEquals(receivedIdentifyRequestMessage.getCollectionID(), otherCollection); @@ -801,9 +820,9 @@ public void putToOtherCollection() throws Exception { IdentifyPillarsForPutFileResponse identifyResponse = messageFactory.createIdentifyPillarsForPutFileResponse( receivedIdentifyRequestMessage, PILLAR2_ID, pillar2DestinationId); messageBus.sendMessage(identifyResponse); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.COMPONENT_IDENTIFIED); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.IDENTIFICATION_COMPLETE); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.REQUEST_SENT); + assertEquals(OperationEventType.COMPONENT_IDENTIFIED, testEventHandler.waitForEvent().getEventType()); + assertEquals(OperationEventType.IDENTIFICATION_COMPLETE, testEventHandler.waitForEvent().getEventType()); + assertEquals(OperationEventType.REQUEST_SENT, testEventHandler.waitForEvent().getEventType()); PutFileRequest receivedPutFileRequest = pillar2Receiver.waitForMessage(PutFileRequest.class); assertEquals(receivedPutFileRequest.getCollectionID(), otherCollection); @@ -812,17 +831,18 @@ public void putToOtherCollection() throws Exception { PutFileFinalResponse putFileFinalResponse1 = messageFactory.createPutFileFinalResponse( receivedPutFileRequest, PILLAR2_ID, pillar2DestinationId); messageBus.sendMessage(putFileFinalResponse1); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.COMPONENT_COMPLETE); - assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.COMPLETE); + assertEquals(OperationEventType.COMPONENT_COMPLETE, testEventHandler.waitForEvent().getEventType()); + assertEquals(OperationEventType.COMPLETE, testEventHandler.waitForEvent().getEventType()); } - /** - * Creates a new test PutFileClient based on the settings. - * - * Note that the normal way of creating client through the module factory would reuse components with settings from - * previous tests. - * @return A new PutFileClient(Wrapper). - */ + /** + * Creates a new test PutFileClient based on the settings. + *

+ * Note that the normal way of creating client through the module factory would reuse components with settings from + * previous tests. + * + * @return A new PutFileClient(Wrapper). + */ private PutFileClient createPutFileClient() { return new PutFileClientTestWrapper(new ConversationBasedPutFileClient( messageBus, conversationMediator, settingsForCUT, settingsForTestClient.getComponentID()) diff --git a/bitrepository-client/src/test/java/org/bitrepository/modify/putfile/PutFileClientTestWrapper.java b/bitrepository-client/src/test/java/org/bitrepository/modify/putfile/PutFileClientTestWrapper.java index 7866467aa..3dab15541 100644 --- a/bitrepository-client/src/test/java/org/bitrepository/modify/putfile/PutFileClientTestWrapper.java +++ b/bitrepository-client/src/test/java/org/bitrepository/modify/putfile/PutFileClientTestWrapper.java @@ -35,8 +35,8 @@ * Wrapper class for a PutFileClient adding test event logging. */ public class PutFileClientTestWrapper implements PutFileClient { - private PutFileClient wrappedPutClient; - private TestEventManager testEventManager; + private final PutFileClient wrappedPutClient; + private final TestEventManager testEventManager; /** * Constructor. diff --git a/bitrepository-client/src/test/java/org/bitrepository/modify/replacefile/ReplaceFileClientComponentTest.java b/bitrepository-client/src/test/java/org/bitrepository/modify/replacefile/ReplaceFileClientComponentTest.java index 917840ae9..17630a4ce 100644 --- a/bitrepository-client/src/test/java/org/bitrepository/modify/replacefile/ReplaceFileClientComponentTest.java +++ b/bitrepository-client/src/test/java/org/bitrepository/modify/replacefile/ReplaceFileClientComponentTest.java @@ -1,23 +1,23 @@ /* * #%L * Bitrepository Access Client - * + * * $Id: PutFileClientComponentTest.java 626 2011-12-09 13:23:52Z jolf $ * $HeadURL: https://sbforge.org/svn/bitrepository/bitrepository-reference/trunk/bitrepository-modifying-client/src/test/java/org/bitrepository/modify/putfile/PutFileClientComponentTest.java $ * %% * Copyright (C) 2010 - 2011 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% @@ -41,9 +41,10 @@ import org.bitrepository.common.utils.CalendarUtils; import org.bitrepository.common.utils.ChecksumUtils; import org.bitrepository.modify.ModifyComponentFactory; -import org.testng.Assert; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; import javax.xml.datatype.DatatypeConfigurationException; import javax.xml.datatype.DatatypeFactory; @@ -57,7 +58,7 @@ public class ReplaceFileClientComponentTest extends DefaultFixtureClientTest { private TestReplaceFileMessageFactory messageFactory; private DatatypeFactory datatypeFactory; - @BeforeMethod(alwaysRun = true) + @BeforeEach public void initialise() throws DatatypeConfigurationException { messageFactory = new TestReplaceFileMessageFactory(settingsForTestClient.getComponentID()); DEFAULT_CHECKSUM_SPEC = ChecksumUtils.getDefault(settingsForCUT); @@ -66,18 +67,20 @@ public void initialise() throws DatatypeConfigurationException { datatypeFactory = DatatypeFactory.newInstance(); } - @Test(groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public void verifyReplaceFileClientFromFactory() { addDescription("Testing the initialization through the ModifyComponentFactory."); addStep("Use the ModifyComponentFactory to instantiate a ReplaceFileClient.", "It should be an instance of ConversationBasedReplaceFileClient"); ReplaceFileClient rfc = ModifyComponentFactory.getInstance().retrieveReplaceFileClient( settingsForCUT, securityManager, settingsForTestClient.getComponentID()); - Assert.assertTrue(rfc instanceof ConversationBasedReplaceFileClient, "The ReplaceFileClient '" + rfc + Assertions.assertInstanceOf(ConversationBasedReplaceFileClient.class, rfc, "The ReplaceFileClient '" + rfc + "' should be instance of '" + ConversationBasedReplaceFileClient.class.getName() + "'"); } - @Test(groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public void replaceClientTester() throws Exception { addDescription("Tests the ReplaceFileClient. Makes a whole conversation for the replace client for a " + "'good' scenario."); @@ -94,19 +97,19 @@ public void replaceClientTester() throws Exception { addStep("Request a file to be replaced on all pillars (which means only the default pillar).", "A IdentifyPillarsForReplaceFileRequest should be sent to the pillar."); - replaceClient.replaceFile(collectionID, DEFAULT_FILE_ID,PILLAR1_ID, DEFAULT_OLD_CHECKSUM_DATA, + replaceClient.replaceFile(collectionID, DEFAULT_FILE_ID, PILLAR1_ID, DEFAULT_OLD_CHECKSUM_DATA, checksumRequest, address, 10, DEFAULT_NEW_CHECKSUM_DATA, checksumRequest, testEventHandler, null); IdentifyPillarsForReplaceFileRequest receivedIdentifyRequestMessage = collectionReceiver.waitForMessage( IdentifyPillarsForReplaceFileRequest.class); - Assert.assertEquals(receivedIdentifyRequestMessage.getCollectionID(), collectionID); - Assert.assertNotNull(receivedIdentifyRequestMessage.getCorrelationID()); - Assert.assertEquals(receivedIdentifyRequestMessage.getReplyTo(), settingsForCUT.getReceiverDestinationID()); - Assert.assertEquals(receivedIdentifyRequestMessage.getFileID(), DEFAULT_FILE_ID); - Assert.assertEquals(receivedIdentifyRequestMessage.getFrom(), settingsForTestClient.getComponentID()); - Assert.assertEquals(receivedIdentifyRequestMessage.getDestination(), settingsForTestClient.getCollectionDestination()); - Assert.assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.IDENTIFY_REQUEST_SENT); + Assertions.assertEquals(receivedIdentifyRequestMessage.getCollectionID(), collectionID); + Assertions.assertNotNull(receivedIdentifyRequestMessage.getCorrelationID()); + Assertions.assertEquals(receivedIdentifyRequestMessage.getReplyTo(), settingsForCUT.getReceiverDestinationID()); + Assertions.assertEquals(DEFAULT_FILE_ID, receivedIdentifyRequestMessage.getFileID()); + Assertions.assertEquals(receivedIdentifyRequestMessage.getFrom(), settingsForTestClient.getComponentID()); + Assertions.assertEquals(receivedIdentifyRequestMessage.getDestination(), settingsForTestClient.getCollectionDestination()); + Assertions.assertEquals(OperationEventType.IDENTIFY_REQUEST_SENT, testEventHandler.waitForEvent().getEventType()); addStep("Make response for the pillar.", "The client receive the response, identify the pillar and send the " + "request."); @@ -114,29 +117,29 @@ public void replaceClientTester() throws Exception { ReplaceFileRequest receivedReplaceFileRequest; IdentifyPillarsForReplaceFileResponse identifyResponse = messageFactory.createIdentifyPillarsForReplaceFileResponse(receivedIdentifyRequestMessage, - PILLAR1_ID, pillar1DestinationId); + PILLAR1_ID, pillar1DestinationId); messageBus.sendMessage(identifyResponse); receivedReplaceFileRequest = pillar1Receiver.waitForMessage(ReplaceFileRequest.class); - Assert.assertEquals(receivedReplaceFileRequest.getCollectionID(), collectionID); - Assert.assertEquals(receivedReplaceFileRequest.getCorrelationID(), receivedIdentifyRequestMessage.getCorrelationID()); - Assert.assertEquals(receivedReplaceFileRequest.getReplyTo(), settingsForCUT.getReceiverDestinationID()); - Assert.assertEquals(receivedReplaceFileRequest.getFileID(), DEFAULT_FILE_ID); - Assert.assertEquals(receivedReplaceFileRequest.getFrom(), settingsForTestClient.getComponentID()); - Assert.assertEquals(receivedReplaceFileRequest.getDestination(), pillar1DestinationId); + Assertions.assertEquals(receivedReplaceFileRequest.getCollectionID(), collectionID); + Assertions.assertEquals(receivedReplaceFileRequest.getCorrelationID(), receivedIdentifyRequestMessage.getCorrelationID()); + Assertions.assertEquals(receivedReplaceFileRequest.getReplyTo(), settingsForCUT.getReceiverDestinationID()); + Assertions.assertEquals(DEFAULT_FILE_ID, receivedReplaceFileRequest.getFileID()); + Assertions.assertEquals(receivedReplaceFileRequest.getFrom(), settingsForTestClient.getComponentID()); + Assertions.assertEquals(receivedReplaceFileRequest.getDestination(), pillar1DestinationId); addStep("Validate the steps of the ReplaceClient by going through the events.", "Should be 'PillarIdentified', " + "'PillarSelected' and 'RequestSent'"); for (int i = 0; i < settingsForCUT.getRepositorySettings().getCollections().getCollection().get(0).getPillarIDs().getPillarID().size(); i++) { - Assert.assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.COMPONENT_IDENTIFIED); + Assertions.assertEquals(OperationEventType.COMPONENT_IDENTIFIED, testEventHandler.waitForEvent().getEventType()); } - Assert.assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.IDENTIFICATION_COMPLETE); - Assert.assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.REQUEST_SENT); + Assertions.assertEquals(OperationEventType.IDENTIFICATION_COMPLETE, testEventHandler.waitForEvent().getEventType()); + Assertions.assertEquals(OperationEventType.REQUEST_SENT, testEventHandler.waitForEvent().getEventType()); addStep("The pillar sends a progress response to the ReplaceClient.", "Should be caught by the event handler."); ReplaceFileProgressResponse putFileProgressResponse = messageFactory.createReplaceFileProgressResponse( receivedReplaceFileRequest, PILLAR1_ID, pillar1DestinationId); messageBus.sendMessage(putFileProgressResponse); - Assert.assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.PROGRESS); + Assertions.assertEquals(OperationEventType.PROGRESS, testEventHandler.waitForEvent().getEventType()); addStep("Send a final response message to the ReplaceClient.", "Should be caught by the event handler. First a PillarComplete, then a Complete."); @@ -145,14 +148,15 @@ public void replaceClientTester() throws Exception { messageBus.sendMessage(replaceFileFinalResponse); for (int i = 1; i < 2 * settingsForCUT.getRepositorySettings().getCollections().getCollection().get(0).getPillarIDs().getPillarID().size(); i++) { OperationEventType eventType = testEventHandler.waitForEvent().getEventType(); - Assert.assertTrue((eventType == OperationEventType.COMPONENT_COMPLETE) - || (eventType == OperationEventType.PROGRESS), + Assertions.assertTrue((eventType == OperationEventType.COMPONENT_COMPLETE) + || (eventType == OperationEventType.PROGRESS), "Expected either PartiallyComplete or Progress, but was: " + eventType); } - Assert.assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.COMPLETE); + Assertions.assertEquals(OperationEventType.COMPLETE, testEventHandler.waitForEvent().getEventType()); } - @Test(groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public void replaceClientIdentificationTimeout() throws Exception { addDescription("Tests the handling of a failed identification for the ReplaceClient"); addStep("Initialise the number of pillars and the DeleteClient. Sets the identification timeout to 100 ms.", @@ -175,16 +179,17 @@ public void replaceClientIdentificationTimeout() throws Exception { address, 10, DEFAULT_NEW_CHECKSUM_DATA, checksumRequest, testEventHandler, null); collectionReceiver.waitForMessage(IdentifyPillarsForReplaceFileRequest.class); - Assert.assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.IDENTIFY_REQUEST_SENT); + Assertions.assertEquals(OperationEventType.IDENTIFY_REQUEST_SENT, testEventHandler.waitForEvent().getEventType()); addStep("Do not respond. Just await the timeout.", "Should make send a Failure event to the eventhandler."); - Assert.assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.IDENTIFY_TIMEOUT); - Assert.assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.COMPONENT_FAILED); - Assert.assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.FAILED); + Assertions.assertEquals(OperationEventType.IDENTIFY_TIMEOUT, testEventHandler.waitForEvent().getEventType()); + Assertions.assertEquals(OperationEventType.COMPONENT_FAILED, testEventHandler.waitForEvent().getEventType()); + Assertions.assertEquals(OperationEventType.FAILED, testEventHandler.waitForEvent().getEventType()); } - @Test(groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public void replaceClientOperationTimeout() throws Exception { addDescription("Tests the handling of a failed operation for the ReplaceClient"); addStep("Initialise the number of pillars and the DeleteClient. Sets the operation timeout to 100 ms.", @@ -209,31 +214,32 @@ public void replaceClientOperationTimeout() throws Exception { IdentifyPillarsForReplaceFileRequest receivedIdentifyRequestMessage = collectionReceiver.waitForMessage( IdentifyPillarsForReplaceFileRequest.class); - Assert.assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.IDENTIFY_REQUEST_SENT); + Assertions.assertEquals(OperationEventType.IDENTIFY_REQUEST_SENT, testEventHandler.waitForEvent().getEventType()); addStep("Make response for the pillar.", "The client receive the response, identify the pillar and send the " + "request."); IdentifyPillarsForReplaceFileResponse identifyResponse = messageFactory.createIdentifyPillarsForReplaceFileResponse(receivedIdentifyRequestMessage, - PILLAR1_ID, pillar1DestinationId); + PILLAR1_ID, pillar1DestinationId); messageBus.sendMessage(identifyResponse); - Assert.assertNotNull(pillar1Receiver.waitForMessage(ReplaceFileRequest.class)); + Assertions.assertNotNull(pillar1Receiver.waitForMessage(ReplaceFileRequest.class)); addStep("Validate the steps of the ReplaceClient by going through the events.", "Should be 'PillarIdentified', " + "'PillarSelected' and 'RequestSent'"); for (int i = 0; i < settingsForCUT.getRepositorySettings().getCollections().getCollection().get(0).getPillarIDs().getPillarID().size(); i++) { - Assert.assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.COMPONENT_IDENTIFIED); + Assertions.assertEquals(OperationEventType.COMPONENT_IDENTIFIED, testEventHandler.waitForEvent().getEventType()); } - Assert.assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.IDENTIFICATION_COMPLETE); - Assert.assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.REQUEST_SENT); + Assertions.assertEquals(OperationEventType.IDENTIFICATION_COMPLETE, testEventHandler.waitForEvent().getEventType()); + Assertions.assertEquals(OperationEventType.REQUEST_SENT, testEventHandler.waitForEvent().getEventType()); addStep("Do not respond. Just await the timeout.", "Should make send a Failure event to the eventhandler."); - Assert.assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.FAILED); + Assertions.assertEquals(OperationEventType.FAILED, testEventHandler.waitForEvent().getEventType()); } - @Test(groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public void replaceClientPillarFailed() throws Exception { addDescription("Tests the handling of a operation failure for the ReplaceClient. "); addStep("Initialise the number of pillars to one", "Should be OK."); @@ -256,7 +262,7 @@ public void replaceClientPillarFailed() throws Exception { IdentifyPillarsForReplaceFileRequest receivedIdentifyRequestMessage = collectionReceiver.waitForMessage( IdentifyPillarsForReplaceFileRequest.class); - Assert.assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.IDENTIFY_REQUEST_SENT); + Assertions.assertEquals(OperationEventType.IDENTIFY_REQUEST_SENT, testEventHandler.waitForEvent().getEventType()); addStep("Make response for the pillar.", "The client receive the response, identify the pillar and send the " + "request."); @@ -264,17 +270,17 @@ public void replaceClientPillarFailed() throws Exception { ReplaceFileRequest receivedReplaceFileRequest; IdentifyPillarsForReplaceFileResponse identifyResponse = messageFactory.createIdentifyPillarsForReplaceFileResponse(receivedIdentifyRequestMessage, - PILLAR1_ID, pillar1DestinationId); + PILLAR1_ID, pillar1DestinationId); messageBus.sendMessage(identifyResponse); receivedReplaceFileRequest = pillar1Receiver.waitForMessage(ReplaceFileRequest.class); addStep("Validate the steps of the ReplaceClient by going through the events.", "Should be 'PillarIdentified', " + "'PillarSelected' and 'RequestSent'"); for (int i = 0; i < settingsForCUT.getRepositorySettings().getCollections().getCollection().get(0).getPillarIDs().getPillarID().size(); i++) { - Assert.assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.COMPONENT_IDENTIFIED); + Assertions.assertEquals(OperationEventType.COMPONENT_IDENTIFIED, testEventHandler.waitForEvent().getEventType()); } - Assert.assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.IDENTIFICATION_COMPLETE); - Assert.assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.REQUEST_SENT); + Assertions.assertEquals(OperationEventType.IDENTIFICATION_COMPLETE, testEventHandler.waitForEvent().getEventType()); + Assertions.assertEquals(OperationEventType.REQUEST_SENT, testEventHandler.waitForEvent().getEventType()); addStep("Send a failed response message to the ReplaceClient.", "Should be caught by the event handler. First a PillarFailed, then a Complete."); @@ -285,11 +291,12 @@ public void replaceClientPillarFailed() throws Exception { ri.setResponseText("Verifying that a failure can be understood!"); replaceFileFinalResponse.setResponseInfo(ri); messageBus.sendMessage(replaceFileFinalResponse); - Assert.assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.COMPONENT_FAILED); - Assert.assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.FAILED); + Assertions.assertEquals(OperationEventType.COMPONENT_FAILED, testEventHandler.waitForEvent().getEventType()); + Assertions.assertEquals(OperationEventType.FAILED, testEventHandler.waitForEvent().getEventType()); } - @Test(groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public void saltedReturnChecksumsForNewFileWithChecksumPillar() throws Exception { addDescription("Tests that the ReplaceClient handles the presence of a ChecksumPillar correctly, " + "when a salted return checksum (which a checksum pillar can't provide) is requested for the new file."); @@ -309,10 +316,10 @@ public void saltedReturnChecksumsForNewFileWithChecksumPillar() throws Exception IdentifyPillarsForReplaceFileRequest receivedIdentifyRequestMessage = collectionReceiver.waitForMessage( IdentifyPillarsForReplaceFileRequest.class); - Assert.assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.IDENTIFY_REQUEST_SENT); + Assertions.assertEquals(OperationEventType.IDENTIFY_REQUEST_SENT, testEventHandler.waitForEvent().getEventType()); addStep("Send an identification response with a PillarChecksumSpec element set, indicating that this is a " + - "checksum pillar.", + "checksum pillar.", "An COMPONENT_IDENTIFIED event should be generate followed by a COMPONENT_IDENTIFIED, " + "a IDENTIFICATION_COMPLETE and a REQUEST_SENT event. A replace request should be set to the " + "checksum pillar without a request for a salted return checksum for the new file"); @@ -321,11 +328,11 @@ public void saltedReturnChecksumsForNewFileWithChecksumPillar() throws Exception PILLAR1_ID, pillar1DestinationId); markAsChecksumPillarResponse(identifyResponse); messageBus.sendMessage(identifyResponse); - Assert.assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.COMPONENT_IDENTIFIED); - Assert.assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.IDENTIFICATION_COMPLETE); - Assert.assertEquals(testEventHandler.waitForEvent().getEventType(), OperationEventType.REQUEST_SENT); + Assertions.assertEquals(OperationEventType.COMPONENT_IDENTIFIED, testEventHandler.waitForEvent().getEventType()); + Assertions.assertEquals(OperationEventType.IDENTIFICATION_COMPLETE, testEventHandler.waitForEvent().getEventType()); + Assertions.assertEquals(OperationEventType.REQUEST_SENT, testEventHandler.waitForEvent().getEventType()); ReplaceFileRequest receivedReplaceFileRequest1 = pillar1Receiver.waitForMessage(ReplaceFileRequest.class); - Assert.assertNull(receivedReplaceFileRequest1.getChecksumRequestForNewFile()); + Assertions.assertNull(receivedReplaceFileRequest1.getChecksumRequestForNewFile()); } /** @@ -333,6 +340,7 @@ public void saltedReturnChecksumsForNewFileWithChecksumPillar() throws Exception *

* Note that the normal way of creating client through the module factory would reuse components with settings from * previous tests. + * * @return A new PutFileClient(Wrapper). */ private ReplaceFileClient createReplaceFileClient() { diff --git a/bitrepository-client/src/test/java/org/bitrepository/modify/replacefile/ReplaceFileClientTestWrapper.java b/bitrepository-client/src/test/java/org/bitrepository/modify/replacefile/ReplaceFileClientTestWrapper.java index 65e1d6360..a7a92a208 100644 --- a/bitrepository-client/src/test/java/org/bitrepository/modify/replacefile/ReplaceFileClientTestWrapper.java +++ b/bitrepository-client/src/test/java/org/bitrepository/modify/replacefile/ReplaceFileClientTestWrapper.java @@ -36,9 +36,9 @@ */ public class ReplaceFileClientTestWrapper implements ReplaceFileClient { /** The PutClient to wrap. */ - private ReplaceFileClient wrappedReplaceClient; + private final ReplaceFileClient wrappedReplaceClient; /** The manager to monitor the operations.*/ - private TestEventManager testEventManager; + private final TestEventManager testEventManager; /** * @param putClientInstance The instance to wrap and monitor. diff --git a/bitrepository-core/src/main/java/org/bitrepository/common/JaxbHelper.java b/bitrepository-core/src/main/java/org/bitrepository/common/JaxbHelper.java index 5f1aaaeed..bd3992cbd 100644 --- a/bitrepository-core/src/main/java/org/bitrepository/common/JaxbHelper.java +++ b/bitrepository-core/src/main/java/org/bitrepository/common/JaxbHelper.java @@ -43,7 +43,6 @@ import java.io.IOException; import java.io.InputStream; import java.io.Reader; -import java.io.UnsupportedEncodingException; import java.net.URL; import java.nio.charset.StandardCharsets; @@ -121,11 +120,7 @@ public String serializeToXml(Object object) throws JAXBException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); JAXBContext.newInstance(object.getClass()).createMarshaller().marshal(object, baos); String baosContent; - try { - baosContent = baos.toString(StandardCharsets.UTF_8.name()); - } catch (UnsupportedEncodingException e) { - throw new AssertionError("UTF-8 not supported"); - } + baosContent = baos.toString(StandardCharsets.UTF_8); return baosContent; } diff --git a/bitrepository-core/src/main/java/org/bitrepository/common/utils/CountAndTimeUnit.java b/bitrepository-core/src/main/java/org/bitrepository/common/utils/CountAndTimeUnit.java index 44dd707e3..c88f8065d 100644 --- a/bitrepository-core/src/main/java/org/bitrepository/common/utils/CountAndTimeUnit.java +++ b/bitrepository-core/src/main/java/org/bitrepository/common/utils/CountAndTimeUnit.java @@ -1,6 +1,6 @@ package org.bitrepository.common.utils; -import java.util.*; +import java.util.Objects; import java.util.concurrent.TimeUnit; public class CountAndTimeUnit { diff --git a/bitrepository-core/src/main/java/org/bitrepository/common/utils/TimeUtils.java b/bitrepository-core/src/main/java/org/bitrepository/common/utils/TimeUtils.java index 487dbc114..1970e9c01 100644 --- a/bitrepository-core/src/main/java/org/bitrepository/common/utils/TimeUtils.java +++ b/bitrepository-core/src/main/java/org/bitrepository/common/utils/TimeUtils.java @@ -234,25 +234,25 @@ public static String durationToHuman(Duration dur) { } if (dur.toDays() > 0) { - parts.add("" + dur.toDays() + "d"); + parts.add(dur.toDays() + "d"); } if (dur.toHoursPart() > 0) { - parts.add("" + dur.toHoursPart() + "h"); + parts.add(dur.toHoursPart() + "h"); } if (dur.toMinutesPart() > 0) { - parts.add("" + dur.toMinutesPart() + "m"); + parts.add(dur.toMinutesPart() + "m"); } if (dur.toSecondsPart() > 0) { - parts.add("" + dur.toSecondsPart() + "s"); + parts.add(dur.toSecondsPart() + "s"); } if (dur.toNanosPart() > 0) { // If the fraction of second is a whole number of millis, print as such; otherwise print only as nanos Duration fraction = Duration.ofNanos(dur.getNano()); Duration remainderAfterMillis = fraction.minusMillis(fraction.toMillisPart()); if (remainderAfterMillis.isZero()) { - parts.add("" + fraction.toMillisPart() + " ms"); + parts.add(fraction.toMillisPart() + " ms"); } else { - parts.add("" + fraction.toNanosPart() + " ns"); + parts.add(fraction.toNanosPart() + " ns"); } } diff --git a/bitrepository-core/src/main/java/org/bitrepository/protocol/messagebus/SimpleMessageBus.java b/bitrepository-core/src/main/java/org/bitrepository/protocol/messagebus/SimpleMessageBus.java index 23db80c29..e047e1898 100644 --- a/bitrepository-core/src/main/java/org/bitrepository/protocol/messagebus/SimpleMessageBus.java +++ b/bitrepository-core/src/main/java/org/bitrepository/protocol/messagebus/SimpleMessageBus.java @@ -38,6 +38,7 @@ public class SimpleMessageBus implements MessageBus { @Override public void addListener(String destinationId, MessageListener listener) { + System.out.println("DEBUG: SimpleMessageBus@" + System.identityHashCode(this) + " adding listener for destination: " + destinationId); getListeners(destinationId).add(listener); } @@ -69,8 +70,17 @@ public void setCollectionFilter(List collectionIDs) { @Override public void sendMessage(Message content) { - if (filterMessage(content)) { - getListeners(content.getDestination()).forEach(listener -> listener.onMessage(content, new MessageContext(null))); + System.out.println("DEBUG: SimpleMessageBus@" + System.identityHashCode(this) + " sendMessage to destination: " + content.getDestination() + ", collectionID: " + content.getCollectionID() + ", messageType: " + content.getClass().getSimpleName()); + System.out.println("DEBUG: Current filters - collection: " + collectionFilter + ", component: " + componentFilter); + boolean filtered = filterMessage(content); + System.out.println("DEBUG: Message filtered: " + !filtered); + if (filtered) { + Set messageListeners = getListeners(content.getDestination()); + System.out.println("DEBUG: Found " + messageListeners.size() + " listeners for destination: " + content.getDestination()); + messageListeners.forEach(listener -> { + System.out.println("DEBUG: Delivering message to listener: " + listener.getClass().getSimpleName()); + listener.onMessage(content, new MessageContext(null)); + }); } } diff --git a/bitrepository-core/src/main/java/org/bitrepository/protocol/messagebus/destination/DestinationHelper.java b/bitrepository-core/src/main/java/org/bitrepository/protocol/messagebus/destination/DestinationHelper.java index 632f5fd08..5636c84b8 100644 --- a/bitrepository-core/src/main/java/org/bitrepository/protocol/messagebus/destination/DestinationHelper.java +++ b/bitrepository-core/src/main/java/org/bitrepository/protocol/messagebus/destination/DestinationHelper.java @@ -43,7 +43,7 @@ public DestinationHelper(String componentID, String receiverDestinationIDFactory this.componentID = componentID; this.collectionDestinationID = collectionDestinationID; - receiverDestinationIDFactory = createReceiverDestinationIDFactory(receiverDestinationIDFactoryClass); + receiverDestinationIDFactory = createReceiverDestinationIDFactory(receiverDestinationIDFactoryClass.trim()); } /** diff --git a/bitrepository-core/src/test/java/org/bitrepository/common/ArgumentValidatorTest.java b/bitrepository-core/src/test/java/org/bitrepository/common/ArgumentValidatorTest.java index 07a936fbb..f5380743b 100644 --- a/bitrepository-core/src/test/java/org/bitrepository/common/ArgumentValidatorTest.java +++ b/bitrepository-core/src/test/java/org/bitrepository/common/ArgumentValidatorTest.java @@ -22,54 +22,58 @@ package org.bitrepository.common; import org.jaccept.structure.ExtendedTestCase; -import org.testng.Assert; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; -import java.util.Arrays; import java.util.Collection; import java.util.HashSet; +import java.util.List; public class ArgumentValidatorTest extends ExtendedTestCase { - @Test(groups = { "regressiontest" }) + @Test + @Tag("regressiontest") public void testArgumentValidatorObject() throws Exception { addDescription("Test the argument validator for arguments not null"); addStep("Test not null", "Should only throw an exception when a null is given."); ArgumentValidator.checkNotNull(new Object(), "No exception expected."); try { ArgumentValidator.checkNotNull(null, "Exception expected."); - Assert.fail("Should throw an exception here."); + Assertions.fail("Should throw an exception here."); } catch (IllegalArgumentException e) { // expected } } - @Test(groups = { "regressiontest" }) + @Test + @Tag("regressiontest" ) public void testArgumentValidatorString() throws Exception { addDescription("Test the argument validator for arguments for strings"); addStep("Test empty string", "Should only throw an exception when the string is null or empty"); ArgumentValidator.checkNotNullOrEmpty("NO EXCEPTION", "No exception expected."); try { ArgumentValidator.checkNotNullOrEmpty((String) null, "Exception expected."); - Assert.fail("Should throw an exception here."); + Assertions.fail("Should throw an exception here."); } catch (IllegalArgumentException e) { // expected } try { ArgumentValidator.checkNotNullOrEmpty("", "Exception expected."); - Assert.fail("Should throw an exception here."); + Assertions.fail("Should throw an exception here."); } catch (IllegalArgumentException e) { // expected } } - @Test(groups = { "regressiontest" }) + @Test + @Tag("regressiontest" ) public void testArgumentValidatorInteger() throws Exception { addDescription("Test the argument validator for arguments for integers"); addStep("Test not negative", "Should only throw an exception if the integer is negative"); ArgumentValidator.checkNotNegative(1, "No exception expected."); try { ArgumentValidator.checkNotNegative(-1, "Exception expected."); - Assert.fail("Should throw an exception here."); + Assertions.fail("Should throw an exception here."); } catch (IllegalArgumentException e) { // expected } @@ -78,26 +82,27 @@ public void testArgumentValidatorInteger() throws Exception { ArgumentValidator.checkPositive(1, "No exception expected."); try { ArgumentValidator.checkPositive(-1, "Exception expected."); - Assert.fail("Should throw an exception here."); + Assertions.fail("Should throw an exception here."); } catch (IllegalArgumentException e) { // expected } try { ArgumentValidator.checkPositive(0, "Exception expected."); - Assert.fail("Should throw an exception here."); + Assertions.fail("Should throw an exception here."); } catch (IllegalArgumentException e) { // expected } } - @Test(groups = { "regressiontest" }) + @Test + @Tag("regressiontest") public void testArgumentValidatorLong() throws Exception { addDescription("Test the argument validator for arguments for longs"); addStep("Test not negative", "Should only throw an exception if the long is negative"); ArgumentValidator.checkNotNegative(1L, "No exception expected."); try { ArgumentValidator.checkNotNegative(-1L, "Exception expected."); - Assert.fail("Should throw an exception here."); + Assertions.fail("Should throw an exception here."); } catch (IllegalArgumentException e) { // expected } @@ -106,64 +111,67 @@ public void testArgumentValidatorLong() throws Exception { ArgumentValidator.checkPositive(1L, "No exception expected."); try { ArgumentValidator.checkPositive(-1L, "Exception expected."); - Assert.fail("Should throw an exception here."); + Assertions.fail("Should throw an exception here."); } catch (IllegalArgumentException e) { // expected } try { ArgumentValidator.checkPositive(0L, "Exception expected."); - Assert.fail("Should throw an exception here."); + Assertions.fail("Should throw an exception here."); } catch (IllegalArgumentException e) { // expected } } - @Test(groups = { "regressiontest" }) + @Test + @Tag("regressiontest" ) public void testArgumentValidatorCollection() throws Exception { addDescription("Test the argument validator for arguments for collections"); addStep("Check against null or empty collection", "Should throw exception exception when non-empty collection"); try { ArgumentValidator.checkNotNullOrEmpty((Collection) null, "Exception expected."); - Assert.fail("Should throw an exception here."); + Assertions.fail("Should throw an exception here."); } catch (IllegalArgumentException e) { // expected } try { ArgumentValidator.checkNotNullOrEmpty(new HashSet<>(), "Exception expected."); - Assert.fail("Should throw an exception here."); + Assertions.fail("Should throw an exception here."); } catch (IllegalArgumentException e) { // expected } - ArgumentValidator.checkNotNullOrEmpty(Arrays.asList("NO FAILURE"), "No exception expected."); + ArgumentValidator.checkNotNullOrEmpty(List.of("NO FAILURE"), "No exception expected."); } - @Test(groups = { "regressiontest" }) + @Test + @Tag("regressiontest" ) public void testArgumentValidatorArrays() throws Exception { addDescription("Test the argument validator for arguments for arrays"); addStep("Check against null or empty arrays", "Should throw exception exception when non-empty array"); try { ArgumentValidator.checkNotNullOrEmpty((Object[]) null, "Exception expected."); - Assert.fail("Should throw an exception here."); + Assertions.fail("Should throw an exception here."); } catch (IllegalArgumentException e) { // expected } try { ArgumentValidator.checkNotNullOrEmpty(new Object[0], "Exception expected."); - Assert.fail("Should throw an exception here."); + Assertions.fail("Should throw an exception here."); } catch (IllegalArgumentException e) { // expected } ArgumentValidator.checkNotNullOrEmpty(new Object[]{"NO FAILURE"}, "No exception expected."); } - @Test(groups = { "regressiontest" }) + @Test + @Tag("regressiontest") public void testArgumentValidatorBoolean() throws Exception { addDescription("Test the argument validator for arguments for booleans"); addStep("validate checkTrue", "Should fail when false."); ArgumentValidator.checkTrue(true, "No exception expected"); try { ArgumentValidator.checkTrue(false, "Exception expected."); - Assert.fail("Should throw an exception here."); + Assertions.fail("Should throw an exception here."); } catch (IllegalArgumentException e) { // expected } diff --git a/bitrepository-core/src/test/java/org/bitrepository/common/DefaultThreadFactoryTest.java b/bitrepository-core/src/test/java/org/bitrepository/common/DefaultThreadFactoryTest.java index 78b31927d..826cd8e09 100644 --- a/bitrepository-core/src/test/java/org/bitrepository/common/DefaultThreadFactoryTest.java +++ b/bitrepository-core/src/test/java/org/bitrepository/common/DefaultThreadFactoryTest.java @@ -3,9 +3,10 @@ import ch.qos.logback.classic.Level; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.Appender; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.slf4j.LoggerFactory; -import org.testng.annotations.Test; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.Is.is; @@ -21,7 +22,8 @@ public class DefaultThreadFactoryTest { private final String message = "Hey this is the message I want to see"; - @Test(groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public void testUncaughtExceptionHandler() throws Exception { // Technique from https://dzone.com/articles/unit-testing-asserting-line diff --git a/bitrepository-core/src/test/java/org/bitrepository/common/TestLogger.java b/bitrepository-core/src/test/java/org/bitrepository/common/TestLogger.java index 870ac393f..bdd77fd1b 100644 --- a/bitrepository-core/src/test/java/org/bitrepository/common/TestLogger.java +++ b/bitrepository-core/src/test/java/org/bitrepository/common/TestLogger.java @@ -28,7 +28,7 @@ import org.slf4j.LoggerFactory; public class TestLogger { - private Logger log; + private final Logger log; public TestLogger(Class logHandle) { log = LoggerFactory.getLogger(logHandle); diff --git a/bitrepository-core/src/test/java/org/bitrepository/common/exception/UnableToFinishExceptionTest.java b/bitrepository-core/src/test/java/org/bitrepository/common/exception/UnableToFinishExceptionTest.java index 86fe82fb5..6cade7fe5 100644 --- a/bitrepository-core/src/test/java/org/bitrepository/common/exception/UnableToFinishExceptionTest.java +++ b/bitrepository-core/src/test/java/org/bitrepository/common/exception/UnableToFinishExceptionTest.java @@ -5,16 +5,16 @@ * Copyright (C) 2010 - 2012 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% @@ -23,36 +23,38 @@ import org.bitrepository.common.exceptions.UnableToFinishException; import org.jaccept.structure.ExtendedTestCase; -import org.testng.Assert; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; public class UnableToFinishExceptionTest extends ExtendedTestCase { - - @Test(groups = { "regressiontest" }) + + @Test + @Tag("regressiontest") public void testUnableToFinish() throws Exception { addDescription("Test the instantiation of the exception"); addStep("Setup", ""); String errMsg = "TEST-ERROR"; String causeMsg = "CAUSE-EXCEPTION"; - + addStep("Try to throw such an exception", "Should be able to be caught and validated"); try { throw new UnableToFinishException(errMsg); - } catch(Exception e) { - Assert.assertTrue(e instanceof UnableToFinishException); - Assert.assertEquals(e.getMessage(), errMsg); - Assert.assertNull(e.getCause()); + } catch (Exception e) { + Assertions.assertInstanceOf(UnableToFinishException.class, e); + Assertions.assertEquals(errMsg, e.getMessage()); + Assertions.assertNull(e.getCause()); } - + addStep("Throw the exception with an embedded exception", "The embedded exception should be the same."); try { throw new UnableToFinishException(errMsg, new IllegalArgumentException(causeMsg)); - } catch(Exception e) { - Assert.assertTrue(e instanceof UnableToFinishException); - Assert.assertEquals(e.getMessage(), errMsg); - Assert.assertNotNull(e.getCause()); - Assert.assertTrue(e.getCause() instanceof IllegalArgumentException); - Assert.assertEquals(e.getCause().getMessage(), causeMsg); + } catch (Exception e) { + Assertions.assertInstanceOf(UnableToFinishException.class, e); + Assertions.assertEquals(errMsg, e.getMessage()); + Assertions.assertNotNull(e.getCause()); + Assertions.assertInstanceOf(IllegalArgumentException.class, e.getCause()); + Assertions.assertEquals(causeMsg, e.getCause().getMessage()); } } } diff --git a/bitrepository-core/src/test/java/org/bitrepository/common/settings/SettingsLoaderTest.java b/bitrepository-core/src/test/java/org/bitrepository/common/settings/SettingsLoaderTest.java index 2ca793f24..609225f11 100644 --- a/bitrepository-core/src/test/java/org/bitrepository/common/settings/SettingsLoaderTest.java +++ b/bitrepository-core/src/test/java/org/bitrepository/common/settings/SettingsLoaderTest.java @@ -25,8 +25,9 @@ package org.bitrepository.common.settings; import org.jaccept.structure.ExtendedTestCase; -import org.testng.Assert; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; import java.util.List; @@ -34,19 +35,21 @@ public class SettingsLoaderTest extends ExtendedTestCase { private static final String PATH_TO_SETTINGS = "settings/xml/bitrepository-devel"; private static final String PATH_TO_EXAMPLE_SETTINGS = "examples/settings"; - @Test(groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public void testDevelopmentCollectionSettingsLoading() { SettingsProvider settingsLoader = new SettingsProvider(new XMLFileSettingsLoader(PATH_TO_SETTINGS), getClass().getSimpleName()); Settings settings = settingsLoader.getSettings(); List expectedPillarIDs = List.of("Pillar1", "Pillar2"); - Assert.assertEquals( + Assertions.assertEquals( settings.getRepositorySettings().getCollections().getCollection().get(0).getPillarIDs().getPillarID(), expectedPillarIDs); } - @Test(groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public void testExampleSettingsLoading() { SettingsProvider settingsLoader = new SettingsProvider(new XMLFileSettingsLoader(PATH_TO_EXAMPLE_SETTINGS), getClass().getSimpleName()); diff --git a/bitrepository-core/src/test/java/org/bitrepository/common/settings/SettingsTest.java b/bitrepository-core/src/test/java/org/bitrepository/common/settings/SettingsTest.java index 719c5cf3e..5b3b2decd 100644 --- a/bitrepository-core/src/test/java/org/bitrepository/common/settings/SettingsTest.java +++ b/bitrepository-core/src/test/java/org/bitrepository/common/settings/SettingsTest.java @@ -1,48 +1,55 @@ package org.bitrepository.common.settings; import org.jaccept.structure.ExtendedTestCase; -import org.testng.Assert; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; import javax.xml.datatype.DatatypeConfigurationException; import javax.xml.datatype.DatatypeFactory; import java.math.BigInteger; import java.time.Duration; +import static org.junit.jupiter.api.Assertions.assertThrows; + public class SettingsTest extends ExtendedTestCase { private DatatypeFactory factory; - @BeforeMethod(alwaysRun = true) + @BeforeEach public void setUpFactory() throws DatatypeConfigurationException { factory = DatatypeFactory.newInstance(); } - @Test(groups = {"regressiontest"}, expectedExceptions = NullPointerException.class) + @Test + @Tag("regressiontest") public void getDurationFromXmlDurationOrMillisRequiresOneNonNullArg() { - addDescription("Tests that getDurationFromXmlDurationOrMillis() fails when given two nulls"); - addStep("null and null", "NPE"); + assertThrows(NullPointerException.class, () -> { + addDescription("Tests that getDurationFromXmlDurationOrMillis() fails when given two nulls"); + addStep("null and null", "NPE"); - Settings.getDurationFromXmlDurationOrMillis(null, null); + Settings.getDurationFromXmlDurationOrMillis(null, null); + }); } - @Test(groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public void testGetDurationFromXmlDurationOrMillis() { addDescription("Tests conversions and selection by getDurationFromXmlDurationOrMillis()"); addStep("null and some milliseconds", "Duration of millis"); - Assert.assertEquals(Settings.getDurationFromXmlDurationOrMillis(null, BigInteger.valueOf(54321)), + Assertions.assertEquals(Settings.getDurationFromXmlDurationOrMillis(null, BigInteger.valueOf(54321)), Duration.ofMillis(54321)); addStep("XML duration and null", "XML duration converted"); - Assert.assertEquals( + Assertions.assertEquals( Settings.getDurationFromXmlDurationOrMillis( factory.newDuration("PT7M"), null), Duration.ofMinutes(7)); addStep("Conflicting XML duration and millis", "XML duration should be preferred"); - Assert.assertEquals( + Assertions.assertEquals( Settings.getDurationFromXmlDurationOrMillis( factory.newDuration("PT2M"), BigInteger.valueOf(13)), Duration.ofMinutes(2)); diff --git a/bitrepository-core/src/test/java/org/bitrepository/common/settings/XMLFileSettingsLoaderTest.java b/bitrepository-core/src/test/java/org/bitrepository/common/settings/XMLFileSettingsLoaderTest.java index 9bd0c4ede..528799d11 100644 --- a/bitrepository-core/src/test/java/org/bitrepository/common/settings/XMLFileSettingsLoaderTest.java +++ b/bitrepository-core/src/test/java/org/bitrepository/common/settings/XMLFileSettingsLoaderTest.java @@ -26,17 +26,19 @@ import org.bitrepository.settings.repositorysettings.RepositorySettings; import org.jaccept.structure.ExtendedTestCase; -import org.testng.Assert; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; public class XMLFileSettingsLoaderTest extends ExtendedTestCase{ private static final String PATH_TO_SETTINGS = "settings/xml/bitrepository-devel"; - @Test(groups = { "regressiontest" }) + @Test + @Tag("regressiontest") public void testCollectionSettingsLoading() throws Exception { SettingsLoader settingsLoader = new XMLFileSettingsLoader(PATH_TO_SETTINGS); RepositorySettings repositorySettings = settingsLoader.loadSettings(RepositorySettings.class); - Assert.assertNotNull(repositorySettings, "RepositorySettings"); + Assertions.assertNotNull(repositorySettings, "RepositorySettings"); } } diff --git a/bitrepository-core/src/test/java/org/bitrepository/common/utils/Base16UtilsTest.java b/bitrepository-core/src/test/java/org/bitrepository/common/utils/Base16UtilsTest.java index 915a1cd30..5b9606ac1 100644 --- a/bitrepository-core/src/test/java/org/bitrepository/common/utils/Base16UtilsTest.java +++ b/bitrepository-core/src/test/java/org/bitrepository/common/utils/Base16UtilsTest.java @@ -23,8 +23,9 @@ import org.apache.commons.codec.DecoderException; import org.jaccept.structure.ExtendedTestCase; -import org.testng.Assert; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; /** * Utility class for handling encoding and decoding of base64 bytes. @@ -34,26 +35,28 @@ public class Base16UtilsTest extends ExtendedTestCase { private final String DECODED_CHECKSUM = "ff5aca7ae8c80c9a3aeaf9173e4dfd27"; private final byte[] ENCODED_CHECKSUM = new byte[]{-1,90,-54,122,-24,-56,12,-102,58,-22,-7,23,62,77,-3,39}; - @Test(groups = { "regressiontest" }) + @Test + @Tag("regressiontest") public void encodeChecksum() throws Exception { addDescription("Validating the encoding of the checksums."); addStep("Encode the checksum and validate", "It should match the precalculated constant."); byte[] encodedChecksum = Base16Utils.encodeBase16(DECODED_CHECKSUM); - Assert.assertEquals(encodedChecksum.length, ENCODED_CHECKSUM.length, + Assertions.assertEquals(encodedChecksum.length, ENCODED_CHECKSUM.length, "The size of the encoded checksum differs from the expected."); for(int i = 0; i < encodedChecksum.length; i++){ - Assert.assertEquals(encodedChecksum[i], ENCODED_CHECKSUM[i]); + Assertions.assertEquals(encodedChecksum[i], ENCODED_CHECKSUM[i]); } } - @Test(groups = { "regressiontest" }) + @Test + @Tag("regressiontest") public void decodeChecksum() { addDescription("Validating the decoding of the checksums."); addStep("Decode the checksum and validate.", "It should match the precalculated constant."); String decodedChecksum = Base16Utils.decodeBase16(ENCODED_CHECKSUM); - Assert.assertEquals(decodedChecksum, DECODED_CHECKSUM); + Assertions.assertEquals(decodedChecksum, DECODED_CHECKSUM); } @Test @@ -61,18 +64,19 @@ public void decodesNull() { addDescription("Test decoding null"); byte[] data = null; String decoded = Base16Utils.decodeBase16(data); - Assert.assertNull(decoded); + Assertions.assertNull(decoded); } - @Test(groups = { "regressiontest" }) + @Test + @Tag("regressiontest") public void badArgumentTest() { addDescription("Test bad arguments"); - Assert.assertThrows(IllegalArgumentException.class, () -> Base16Utils.encodeBase16(null)); + Assertions.assertThrows(IllegalArgumentException.class, () -> Base16Utils.encodeBase16(null)); addStep("Test with an odd number of characters.", "Should throw a decoder exception"); - Assert.assertThrows(DecoderException.class, () -> Base16Utils.encodeBase16("123")); + Assertions.assertThrows(DecoderException.class, () -> Base16Utils.encodeBase16("123")); addStep("Test with a non hex digit.", "Should throw a decoder exception"); - Assert.assertThrows(DecoderException.class, () -> Base16Utils.encodeBase16("1g")); + Assertions.assertThrows(DecoderException.class, () -> Base16Utils.encodeBase16("1g")); } } diff --git a/bitrepository-core/src/test/java/org/bitrepository/common/utils/CalendarUtilsTest.java b/bitrepository-core/src/test/java/org/bitrepository/common/utils/CalendarUtilsTest.java index 0771e2768..f9d4f2ef8 100644 --- a/bitrepository-core/src/test/java/org/bitrepository/common/utils/CalendarUtilsTest.java +++ b/bitrepository-core/src/test/java/org/bitrepository/common/utils/CalendarUtilsTest.java @@ -5,16 +5,16 @@ * Copyright (C) 2010 - 2012 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% @@ -22,8 +22,9 @@ package org.bitrepository.common.utils; import org.jaccept.structure.ExtendedTestCase; -import org.testng.Assert; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; import javax.xml.datatype.XMLGregorianCalendar; import java.text.ParseException; @@ -35,39 +36,40 @@ public class CalendarUtilsTest extends ExtendedTestCase { long DATE_IN_MILLIS = 123456789L; - - @Test(groups = {"regressiontest"}) + + @Test + @Tag("regressiontest") public void calendarTester() throws Exception { addDescription("Test the calendar utility class"); addStep("Test the convertion of a date", "Should be the same date."); Date date = new Date(DATE_IN_MILLIS); XMLGregorianCalendar calendar = CalendarUtils.getXmlGregorianCalendar(date); - Assert.assertEquals(calendar.toGregorianCalendar().getTimeInMillis(), DATE_IN_MILLIS); + Assertions.assertEquals(calendar.toGregorianCalendar().getTimeInMillis(), DATE_IN_MILLIS); addStep("Test that a 'null' date is equivalent to epoch", "Should be date '0'"); - calendar = CalendarUtils.getXmlGregorianCalendar((Date)null); - Assert.assertEquals(calendar.toGregorianCalendar().getTimeInMillis(), 0); - + calendar = CalendarUtils.getXmlGregorianCalendar((Date) null); + Assertions.assertEquals(0, calendar.toGregorianCalendar().getTimeInMillis()); + addStep("Test epoch", "Should be date '0'"); calendar = CalendarUtils.getEpoch(); - Assert.assertEquals(calendar.toGregorianCalendar().getTimeInMillis(), 0); - + Assertions.assertEquals(0, calendar.toGregorianCalendar().getTimeInMillis()); + addStep("Test that a given time in millis is extractable in millis", "Should be same value"); calendar = CalendarUtils.getFromMillis(DATE_IN_MILLIS); - Assert.assertEquals(calendar.toGregorianCalendar().getTimeInMillis(), DATE_IN_MILLIS); - + Assertions.assertEquals(calendar.toGregorianCalendar().getTimeInMillis(), DATE_IN_MILLIS); + addStep("Test the 'getNow' function", "Should give a value very close to System.currentTimeInMillis"); long beforeNow = System.currentTimeMillis(); calendar = CalendarUtils.getNow(); long afterNow = System.currentTimeMillis(); - Assert.assertTrue(calendar.toGregorianCalendar().getTimeInMillis() <= afterNow); - Assert.assertTrue(calendar.toGregorianCalendar().getTimeInMillis() >= beforeNow); - + Assertions.assertTrue(calendar.toGregorianCalendar().getTimeInMillis() <= afterNow); + Assertions.assertTrue(calendar.toGregorianCalendar().getTimeInMillis() >= beforeNow); + addStep("Test the reverse conversion, from XMLCalendar to Date", "Should give the same value"); date = CalendarUtils.convertFromXMLGregorianCalendar(calendar); - Assert.assertTrue(date.getTime() <= afterNow); - Assert.assertTrue(date.getTime() >= beforeNow); - Assert.assertEquals(date.getTime(), calendar.toGregorianCalendar().getTimeInMillis()); + Assertions.assertTrue(date.getTime() <= afterNow); + Assertions.assertTrue(date.getTime() >= beforeNow); + Assertions.assertEquals(date.getTime(), calendar.toGregorianCalendar().getTimeInMillis()); } @Test @@ -75,43 +77,47 @@ public void displaysNiceTimeZoneId() { addDescription("Test that the time zone ID logged is human readable (for example Europe/Copenhagen)"); ZoneId zoneId = ZoneId.of("Europe/Copenhagen"); String displayName = CalendarUtils.getTimeZoneDisplayName(TimeZone.getTimeZone(zoneId)); - Assert.assertEquals(displayName, "Europe/Copenhagen"); + Assertions.assertEquals("Europe/Copenhagen", displayName); } - @Test(groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public void startDateTest() throws ParseException { addDescription("Test that the start date is considered as localtime and converted into UTC."); CalendarUtils cu = CalendarUtils.getInstance(TimeZone.getTimeZone("Europe/Copenhagen")); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX", Locale.ROOT); Date expectedStartOfDay = sdf.parse("2015-02-25T23:00:00.000Z"); - + Date parsedStartOfDay = cu.makeStartDateObject("2015/02/26"); - Assert.assertEquals(parsedStartOfDay, expectedStartOfDay); + Assertions.assertEquals(parsedStartOfDay, expectedStartOfDay); } - - @Test(groups = {"regressiontest"}) + + @Test + @Tag("regressiontest") public void endDateTest() throws ParseException { addDescription("Test that the end date is considered as localtime and converted into UTC."); CalendarUtils cu = CalendarUtils.getInstance(TimeZone.getTimeZone("Europe/Copenhagen")); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX", Locale.ROOT); Date expectedStartOfDay = sdf.parse("2015-02-26T22:59:59.999Z"); - + Date parsedStartOfDay = cu.makeEndDateObject("2015/02/26"); - Assert.assertEquals(parsedStartOfDay, expectedStartOfDay); + Assertions.assertEquals(parsedStartOfDay, expectedStartOfDay); } - - @Test(groups = {"regressiontest"}) + + @Test + @Tag("regressiontest") public void endDateRolloverTest() throws ParseException { addDescription("Test that the end date is correctly rolls over a year and month change."); CalendarUtils cu = CalendarUtils.getInstance(TimeZone.getTimeZone("Europe/Copenhagen")); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX", Locale.ROOT); Date expectedStartOfDay = sdf.parse("2016-01-01T22:59:59.999Z"); - + Date parsedStartOfDay = cu.makeEndDateObject("2015/12/32"); - Assert.assertEquals(parsedStartOfDay, expectedStartOfDay); + Assertions.assertEquals(parsedStartOfDay, expectedStartOfDay); } - - @Test(groups = {"regressiontest"}) + + @Test + @Tag("regressiontest") public void testBeginningOfDay() throws ParseException { addDescription("Tests that the time is converted to the beginning of the day localtime, not UTC"); CalendarUtils cu = CalendarUtils.getInstance(TimeZone.getTimeZone("Europe/Copenhagen")); @@ -119,45 +125,48 @@ public void testBeginningOfDay() throws ParseException { Date expectedStartOfDayInUTC = sdf.parse("2016-01-31T23:00:00.000Z"); System.out.println("expectedStartOfDayInUTC parsed: " + expectedStartOfDayInUTC.getTime()); Date parsedStartOfDay = cu.makeStartDateObject("2016/02/01"); - Assert.assertEquals(parsedStartOfDay, expectedStartOfDayInUTC); + Assertions.assertEquals(parsedStartOfDay, expectedStartOfDayInUTC); } - - @Test(groups = {"regressiontest"}) + + @Test + @Tag("regressiontest") public void testEndOfDay() throws ParseException { addDescription("Tests that the time is converted to the beginning of the day localtime, not UTC"); CalendarUtils cu = CalendarUtils.getInstance(TimeZone.getTimeZone("Europe/Copenhagen")); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX", Locale.ROOT); Date expectedEndOfDayInUTC = sdf.parse("2016-02-01T22:59:59.999Z"); Date parsedEndOfDay = cu.makeEndDateObject("2016/02/01"); - Assert.assertEquals(parsedEndOfDay, expectedEndOfDayInUTC); + Assertions.assertEquals(parsedEndOfDay, expectedEndOfDayInUTC); } - - @Test(groups = {"regressiontest"}) + + @Test + @Tag("regressiontest") public void testSummerWinterTimeChange() { addDescription("Test that the interval between start and end date on a summertime to " + "wintertime change is 25 hours (-1 millisecond)."); CalendarUtils cu = CalendarUtils.getInstance(TimeZone.getTimeZone("Europe/Copenhagen")); Date startDate = cu.makeStartDateObject("2015/10/25"); - Assert.assertNotNull(startDate); + Assertions.assertNotNull(startDate); Date endDate = cu.makeEndDateObject("2015/10/25"); - Assert.assertNotNull(endDate); + Assertions.assertNotNull(endDate); long MS_PER_HOUR = 1000 * 60 * 60; long expectedIntervalLength = (MS_PER_HOUR * 25) - 1; - Assert.assertEquals(endDate.getTime() - startDate.getTime(), expectedIntervalLength); + Assertions.assertEquals(endDate.getTime() - startDate.getTime(), expectedIntervalLength); } - - @Test(groups = {"regressiontest"}) + + @Test + @Tag("regressiontest") public void testWinterSummerTimeChange() { addDescription("Test that the interval between start and end date on a wintertime to " + "summertime change is 23 hours (-1 millisecond)."); CalendarUtils cu = CalendarUtils.getInstance(TimeZone.getTimeZone("Europe/Copenhagen")); Date startDate = cu.makeStartDateObject("2016/03/27"); - Assert.assertNotNull(startDate); + Assertions.assertNotNull(startDate); Date endDate = cu.makeEndDateObject("2016/03/27"); - Assert.assertNotNull(endDate); + Assertions.assertNotNull(endDate); long MS_PER_HOUR = 1000 * 60 * 60; long expectedIntervalLength = (MS_PER_HOUR * 23) - 1; - Assert.assertEquals(endDate.getTime() - startDate.getTime(), expectedIntervalLength); + Assertions.assertEquals(endDate.getTime() - startDate.getTime(), expectedIntervalLength); } } diff --git a/bitrepository-core/src/test/java/org/bitrepository/common/utils/ChecksumUtilsTest.java b/bitrepository-core/src/test/java/org/bitrepository/common/utils/ChecksumUtilsTest.java index f99f68fba..68ff54b38 100644 --- a/bitrepository-core/src/test/java/org/bitrepository/common/utils/ChecksumUtilsTest.java +++ b/bitrepository-core/src/test/java/org/bitrepository/common/utils/ChecksumUtilsTest.java @@ -1,23 +1,23 @@ /* * #%L * Bitrepository Common - * + * * $Id$ * $HeadURL$ * %% * Copyright (C) 2010 - 2012 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% @@ -29,8 +29,9 @@ import org.bitrepository.common.settings.Settings; import org.bitrepository.common.settings.TestSettingsProvider; import org.jaccept.structure.ExtendedTestCase; -import org.testng.Assert; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; import java.io.ByteArrayInputStream; import java.io.File; @@ -39,7 +40,8 @@ import java.security.NoSuchAlgorithmException; public class ChecksumUtilsTest extends ExtendedTestCase { - @Test(groups = { "regressiontest" }) + @Test + @Tag("regressiontest") public void calculateHmacChecksums() throws Exception { addDescription("Tests whether the utility class for calculating checksums with HMAC is able to " + "correctly calculate predefined examples from : " @@ -54,47 +56,48 @@ public void calculateHmacChecksums() throws Exception { ChecksumSpecTYPE csHmacSHA256 = new ChecksumSpecTYPE(); csHmacSHA256.setChecksumType(ChecksumType.HMAC_SHA256); csHmacSHA256.setChecksumSalt(new byte[]{0}); - - addStep("Test with no text and no key for HMAC_MD5, HMAC_SHA1, and HMAC_SHA256", + + addStep("Test with no text and no key for HMAC_MD5, HMAC_SHA1, and HMAC_SHA256", "Should give expected results."); InputStream data1 = new ByteArrayInputStream(new byte[0]); - Assert.assertEquals(ChecksumUtils.generateChecksum(data1, csHmacMD5), - "74e6f7298a9c2d168935f58c001bad88"); - Assert.assertEquals(ChecksumUtils.generateChecksum(data1, csHmacSHA1), - "fbdb1d1b18aa6c08324b7d64b71fb76370690e1d"); - Assert.assertEquals(ChecksumUtils.generateChecksum(data1, csHmacSHA256), - "b613679a0814d9ec772f95d778c35fc5ff1697c493715653c6c712144292c5ad"); - + Assertions.assertEquals("74e6f7298a9c2d168935f58c001bad88", + ChecksumUtils.generateChecksum(data1, csHmacMD5)); + Assertions.assertEquals("fbdb1d1b18aa6c08324b7d64b71fb76370690e1d", + ChecksumUtils.generateChecksum(data1, csHmacSHA1)); + Assertions.assertEquals("b613679a0814d9ec772f95d778c35fc5ff1697c493715653c6c712144292c5ad", + ChecksumUtils.generateChecksum(data1, csHmacSHA256)); + String message = "The quick brown fox jumps over the lazy dog"; InputStream data2 = new ByteArrayInputStream(message.getBytes(StandardCharsets.UTF_8)); String key = "key"; csHmacMD5.setChecksumSalt(key.getBytes(StandardCharsets.UTF_8)); csHmacSHA1.setChecksumSalt(key.getBytes(StandardCharsets.UTF_8)); csHmacSHA256.setChecksumSalt(key.getBytes(StandardCharsets.UTF_8)); - - addStep("Test with the text '" + message + "' and key '" + key + "' for MD5, SHA1, and SHA256", + + addStep("Test with the text '" + message + "' and key '" + key + "' for MD5, SHA1, and SHA256", "Should give expected results."); - Assert.assertEquals(ChecksumUtils.generateChecksum(data2, csHmacMD5), - "80070713463e7749b90c2dc24911e275"); + Assertions.assertEquals("80070713463e7749b90c2dc24911e275", + ChecksumUtils.generateChecksum(data2, csHmacMD5)); data2.reset(); - Assert.assertEquals(ChecksumUtils.generateChecksum(data2, csHmacSHA1), - "de7c9b85b8b78aa6bc8a7a36f70a90701c9db4d9"); + Assertions.assertEquals("de7c9b85b8b78aa6bc8a7a36f70a90701c9db4d9", + ChecksumUtils.generateChecksum(data2, csHmacSHA1)); data2.reset(); - Assert.assertEquals(ChecksumUtils.generateChecksum(data2, csHmacSHA256), - "f7bc83f430538424b13298e6aa6fb143ef4d59a14946175997479dbc2d1a3cd8"); + Assertions.assertEquals("f7bc83f430538424b13298e6aa6fb143ef4d59a14946175997479dbc2d1a3cd8", + ChecksumUtils.generateChecksum(data2, csHmacSHA256)); data2.reset(); - + addStep("Try calculating HMAC with a null salt", "Should throw NoSuchAlgorithmException"); csHmacMD5.setChecksumSalt(null); try { ChecksumUtils.generateChecksum(data2, csHmacMD5); - Assert.fail("Should throw an IllegalArgumentException here!"); - } catch (IllegalArgumentException e) { + Assertions.fail("Should throw an IllegalArgumentException here!"); + } catch (IllegalArgumentException e) { // expected } } - - @Test(groups = { "regressiontest" }) + + @Test + @Tag("regressiontest") public void calculateDigestChecksums() throws Exception { addDescription("Tests whether the utility class for calculating checksums with MessageDigest is able to " + "correctly calculate the checksums."); @@ -105,41 +108,42 @@ public void calculateDigestChecksums() throws Exception { csSHA1.setChecksumType(ChecksumType.SHA1); ChecksumSpecTYPE csSHA256 = new ChecksumSpecTYPE(); csSHA256.setChecksumType(ChecksumType.SHA256); - - addStep("Test with no text and no key for MD5, SHA1, and SHA256", + + addStep("Test with no text and no key for MD5, SHA1, and SHA256", "Should give expected results."); InputStream data1 = new ByteArrayInputStream(new byte[0]); - Assert.assertEquals(ChecksumUtils.generateChecksum(data1, csMD5), - "d41d8cd98f00b204e9800998ecf8427e"); - Assert.assertEquals(ChecksumUtils.generateChecksum(data1, csSHA1), - "da39a3ee5e6b4b0d3255bfef95601890afd80709"); - Assert.assertEquals(ChecksumUtils.generateChecksum(data1, csSHA256), - "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"); - + Assertions.assertEquals("d41d8cd98f00b204e9800998ecf8427e", + ChecksumUtils.generateChecksum(data1, csMD5)); + Assertions.assertEquals("da39a3ee5e6b4b0d3255bfef95601890afd80709", + ChecksumUtils.generateChecksum(data1, csSHA1)); + Assertions.assertEquals("e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + ChecksumUtils.generateChecksum(data1, csSHA256)); + addStep("Test with text ", "Should giver different checksums"); String message = "The quick brown fox jumps over the lazy dog"; InputStream data2 = new ByteArrayInputStream(message.getBytes(StandardCharsets.UTF_8)); - Assert.assertEquals(ChecksumUtils.generateChecksum(data2, csMD5), - "9e107d9d372bb6826bd81d3542a419d6"); + Assertions.assertEquals("9e107d9d372bb6826bd81d3542a419d6", + ChecksumUtils.generateChecksum(data2, csMD5)); data2.reset(); - Assert.assertEquals(ChecksumUtils.generateChecksum(data2, csSHA1), - "2fd4e1c67a2d28fced849ee1bb76e7391b93eb12"); + Assertions.assertEquals("2fd4e1c67a2d28fced849ee1bb76e7391b93eb12", + ChecksumUtils.generateChecksum(data2, csSHA1)); data2.reset(); - Assert.assertEquals(ChecksumUtils.generateChecksum(data2, csSHA256), - "d7a8fbb307d7809469ca9abcb0082e4f8d5651e46d3cdb762d02d0bf37c9e592"); + Assertions.assertEquals("d7a8fbb307d7809469ca9abcb0082e4f8d5651e46d3cdb762d02d0bf37c9e592", + ChecksumUtils.generateChecksum(data2, csSHA256)); data2.reset(); addStep("add a salt to the checksum", "Should throw an exception"); csMD5.setChecksumSalt("key".getBytes(StandardCharsets.UTF_8)); try { ChecksumUtils.generateChecksum(data1, csMD5); - Assert.fail("Should throw an IllegalArgumentException here!"); - } catch (IllegalArgumentException e) { + Assertions.fail("Should throw an IllegalArgumentException here!"); + } catch (IllegalArgumentException e) { // expected - } + } } - @Test(groups = { "regressiontest" }) + @Test + @Tag("regressiontest") public void testChecksumOnFile() throws Exception { addDescription("Test the checksum calculation on a file"); addStep("Setup", ""); @@ -147,34 +151,35 @@ public void testChecksumOnFile() throws Exception { csMD5.setChecksumType(ChecksumType.MD5); File testFile = new File("src/test/resources/test-files/default-test-file.txt"); - Assert.assertTrue(testFile.isFile()); - - addStep("Calculate the checksum of the file with the different ways of defining the MD5 without salt", + Assertions.assertTrue(testFile.isFile()); + + addStep("Calculate the checksum of the file with the different ways of defining the MD5 without salt", "Same result from each"); String cs1 = ChecksumUtils.generateChecksum(testFile, csMD5); String cs2 = ChecksumUtils.generateChecksum(testFile, ChecksumType.MD5); String cs3 = ChecksumUtils.generateChecksum(testFile, ChecksumType.MD5, null); - - Assert.assertEquals(cs1, cs2); - Assert.assertEquals(cs1, cs3); - Assert.assertEquals(cs2, cs3); + + Assertions.assertEquals(cs1, cs2); + Assertions.assertEquals(cs1, cs3); + Assertions.assertEquals(cs2, cs3); } - - @Test(groups = { "regressiontest" }) + + @Test + @Tag("regressiontest") public void testChecksumAlgorithmValidation() throws Exception { addDescription("Test the algorithm validation for every single possible checksum algorithm."); for (ChecksumType csType : ChecksumType.values()) { - if(csType == ChecksumType.OTHER) { + if (csType == ChecksumType.OTHER) { validateOtherChecksumType(csType); - } else if(csType.name().startsWith("HMAC")) { + } else if (csType.name().startsWith("HMAC")) { validateHmac(csType); } else { validateMessageDigest(csType); } } } - + private void validateOtherChecksumType(ChecksumType algorithm) { addStep("Test '" + algorithm + "'", "Should be invalid no matter the salt!"); ChecksumSpecTYPE csType = new ChecksumSpecTYPE(); @@ -182,14 +187,14 @@ private void validateOtherChecksumType(ChecksumType algorithm) { try { ChecksumUtils.verifyAlgorithm(csType); - Assert.fail("The 'OTHER' algorithms should be invalid no matter the salt: '" + csType); + Assertions.fail("The 'OTHER' algorithms should be invalid no matter the salt: '" + csType); } catch (NoSuchAlgorithmException e) { // expected } - + try { - ChecksumUtils.requiresSalt(algorithm); - Assert.fail("The 'OTHER' algorithms should be invalid no matter the salt: '" + csType); + ChecksumUtils.requiresSalt(algorithm); + Assertions.fail("The 'OTHER' algorithms should be invalid no matter the salt: '" + csType); } catch (NoSuchAlgorithmException e) { // expected } @@ -197,7 +202,7 @@ private void validateOtherChecksumType(ChecksumType algorithm) { csType.setChecksumSalt(new byte[]{0}); try { ChecksumUtils.verifyAlgorithm(csType); - Assert.fail("The 'OTHER' algorithms should be invalid with an empty salt: '" + csType); + Assertions.fail("The 'OTHER' algorithms should be invalid with an empty salt: '" + csType); } catch (NoSuchAlgorithmException e) { // expected } @@ -205,66 +210,67 @@ private void validateOtherChecksumType(ChecksumType algorithm) { csType.setChecksumSalt(new byte[]{1}); try { ChecksumUtils.verifyAlgorithm(csType); - Assert.fail("The 'OTHER' algorithms should be invalid with the salt: '" + csType); + Assertions.fail("The 'OTHER' algorithms should be invalid with the salt: '" + csType); } catch (NoSuchAlgorithmException e) { // expected } } - + private void validateHmac(ChecksumType hmacType) throws NoSuchAlgorithmException { addStep("Test '" + hmacType + "'", "Should be invalid without salt, and valid with no matter whether " + "the salt is empty."); ChecksumSpecTYPE csType = new ChecksumSpecTYPE(); csType.setChecksumType(hmacType); - + try { ChecksumUtils.verifyAlgorithm(csType); - Assert.fail("The HMAC algorithms should be invalid without the salt: '" + csType); + Assertions.fail("The HMAC algorithms should be invalid without the salt: '" + csType); } catch (NoSuchAlgorithmException e) { // expected } - Assert.assertTrue(ChecksumUtils.requiresSalt(hmacType), "HMAC algorithms must require salt."); - + Assertions.assertTrue(ChecksumUtils.requiresSalt(hmacType), "HMAC algorithms must require salt."); + csType.setChecksumSalt(new byte[]{0}); - ChecksumUtils.verifyAlgorithm(csType); + ChecksumUtils.verifyAlgorithm(csType); csType.setChecksumSalt(new byte[]{1}); - ChecksumUtils.verifyAlgorithm(csType); + ChecksumUtils.verifyAlgorithm(csType); } - + private void validateMessageDigest(ChecksumType algorithmType) throws NoSuchAlgorithmException { addStep("Test '" + algorithmType + "'", "Should be valid without salt, valid with an empty salt, " + "and invalid with a proper salt."); ChecksumSpecTYPE csType = new ChecksumSpecTYPE(); csType.setChecksumType(algorithmType); - - ChecksumUtils.verifyAlgorithm(csType); - Assert.assertFalse(ChecksumUtils.requiresSalt(algorithmType), "Non-HMAC algorithms must not require salt."); + ChecksumUtils.verifyAlgorithm(csType); + + Assertions.assertFalse(ChecksumUtils.requiresSalt(algorithmType), "Non-HMAC algorithms must not require salt."); csType.setChecksumSalt(new byte[0]); ChecksumUtils.verifyAlgorithm(csType); - + csType.setChecksumSalt(new byte[]{1}); try { ChecksumUtils.verifyAlgorithm(csType); - Assert.fail("The MessaegDigest algorithms should be invalid with the salt: '" + csType); + Assertions.fail("The MessaegDigest algorithms should be invalid with the salt: '" + csType); } catch (NoSuchAlgorithmException e) { // expected } } - - @Test(groups = { "regressiontest" }) + + @Test + @Tag("regressiontest") public void testDefaultChecksum() throws Exception { addDescription("Test the extraction of the default checksum from settings."); addStep("Setup the settings", "Loading the test settings"); Settings settings = TestSettingsProvider.reloadSettings("ChecksumUtils"); - + addStep("Use utils to extract default checksum spec", "Should be the one defined in Settings."); ChecksumSpecTYPE csType = ChecksumUtils.getDefault(settings); - Assert.assertEquals(csType.getChecksumType().name(), + Assertions.assertEquals(csType.getChecksumType().name(), settings.getRepositorySettings().getProtocolSettings().getDefaultChecksumType()); - Assert.assertNull(csType.getChecksumSalt(), "Should not contain any salt."); + Assertions.assertNull(csType.getChecksumSalt(), "Should not contain any salt."); } } diff --git a/bitrepository-core/src/test/java/org/bitrepository/common/utils/FileIDUtilsTest.java b/bitrepository-core/src/test/java/org/bitrepository/common/utils/FileIDUtilsTest.java index 4baef6c1d..e728f9036 100644 --- a/bitrepository-core/src/test/java/org/bitrepository/common/utils/FileIDUtilsTest.java +++ b/bitrepository-core/src/test/java/org/bitrepository/common/utils/FileIDUtilsTest.java @@ -23,25 +23,27 @@ import org.bitrepository.bitrepositoryelements.FileIDs; import org.jaccept.structure.ExtendedTestCase; -import org.testng.Assert; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; public class FileIDUtilsTest extends ExtendedTestCase { String FILE_ID = "Test-File-Id"; - @Test( groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public void fileIDsTest() throws Exception { addDescription("Test the utility class for generating FileIDs"); addStep("Test 'all file ids'", "is only AllFileIDs"); FileIDs allFileIDs = FileIDsUtils.getAllFileIDs(); - Assert.assertTrue(allFileIDs.isSetAllFileIDs()); - Assert.assertFalse(allFileIDs.isSetFileID()); - Assert.assertNull(allFileIDs.getFileID()); + Assertions.assertTrue(allFileIDs.isSetAllFileIDs()); + Assertions.assertFalse(allFileIDs.isSetFileID()); + Assertions.assertNull(allFileIDs.getFileID()); addStep("Test a specific file id", "Should not be AllFileIDs"); FileIDs specificFileIDs = FileIDsUtils.getSpecificFileIDs(FILE_ID); - Assert.assertFalse(specificFileIDs.isSetAllFileIDs()); - Assert.assertTrue(specificFileIDs.isSetFileID()); - Assert.assertEquals(specificFileIDs.getFileID(), FILE_ID); + Assertions.assertFalse(specificFileIDs.isSetAllFileIDs()); + Assertions.assertTrue(specificFileIDs.isSetFileID()); + Assertions.assertEquals(specificFileIDs.getFileID(), FILE_ID); } } diff --git a/bitrepository-core/src/test/java/org/bitrepository/common/utils/FileIDValidatorTest.java b/bitrepository-core/src/test/java/org/bitrepository/common/utils/FileIDValidatorTest.java index 8bb8dbd88..90957c0e4 100644 --- a/bitrepository-core/src/test/java/org/bitrepository/common/utils/FileIDValidatorTest.java +++ b/bitrepository-core/src/test/java/org/bitrepository/common/utils/FileIDValidatorTest.java @@ -24,20 +24,24 @@ import org.bitrepository.common.settings.Settings; import org.bitrepository.common.settings.TestSettingsProvider; import org.jaccept.structure.ExtendedTestCase; -import org.testng.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class FileIDValidatorTest extends ExtendedTestCase { /** The settings for the tests. Should be instantiated in the setup.*/ Settings settings; - @BeforeClass (alwaysRun = true) + @BeforeAll public void setup() { settings = TestSettingsProvider.reloadSettings(getClass().getSimpleName()); } - @Test( groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public void validatorTest() throws Exception { addDescription("Tests the FileIDValidator class for the input handling based on a given regex."); addStep("Setup the validator", "Should be ok."); @@ -50,23 +54,24 @@ public void validatorTest() throws Exception { String tooShort = ""; addStep("Test a null as argument", "The null should be ignored."); - Assert.assertNull(validator.validateFileID(null)); + Assertions.assertNull(validator.validateFileID(null)); addStep("Test a valid fileID", "Should be valid"); - Assert.assertNull(validator.validateFileID(validFileID)); + Assertions.assertNull(validator.validateFileID(validFileID)); addStep("Test invalid characters", "Should be invalid"); - Assert.assertNotNull(validator.validateFileID(invalidCharacters), "Should fail with bad characters here!"); + Assertions.assertNotNull(validator.validateFileID(invalidCharacters), "Should fail with bad characters here!"); addStep("Test invalid length", "Should be invalid"); - Assert.assertNotNull(validator.validateFileID(tooLong), "Should fail with invalid length here!"); + Assertions.assertNotNull(validator.validateFileID(tooLong), "Should fail with invalid length here!"); addStep("Test too short", "Should be invalid"); - Assert.assertNotNull(validator.validateFileID(tooShort), + Assertions.assertNotNull(validator.validateFileID(tooShort), "Should fail with invalid length here!"); } - @Test( groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public void validatorDefaultTest() throws Exception { addDescription("Tests the FileIDValidator class default restrictions. Only the length should fail."); addStep("Setup the validator, where all file ids are allowed at default.", "Should be ok."); @@ -79,35 +84,36 @@ public void validatorDefaultTest() throws Exception { String tooShort = ""; addStep("Test a null as argument", "The null should be ignored."); - Assert.assertNull(validator.validateFileID(null)); + Assertions.assertNull(validator.validateFileID(null)); addStep("Test a valid fileID", "Should be valid"); - Assert.assertNull(validator.validateFileID(validFileID)); + Assertions.assertNull(validator.validateFileID(validFileID)); addStep("Test odd characters", "Should be valid"); - Assert.assertNull(validator.validateFileID(invalidCharacters)); + Assertions.assertNull(validator.validateFileID(invalidCharacters)); addStep("Test invalid length", "Should be invalid"); - Assert.assertNotNull(validator.validateFileID(tooLong), + Assertions.assertNotNull(validator.validateFileID(tooLong), "Should fail with invalid length here -> too long"); addStep("Test too short", "Should be invalid"); - Assert.assertNotNull(validator.validateFileID(tooShort), + Assertions.assertNotNull(validator.validateFileID(tooShort), "Should fail with invalid length here -> too short"); } - @Test( groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public void badRegexTest() throws Exception { addDescription("Tests the FileIDValidator handling of bad file id pattern."); addStep("Give the validator a 'null' as allowed file id pattern", "Should be a null stored as regex." ); settings.getRepositorySettings().getProtocolSettings().setAllowedFileIDPattern(null); TestFileIDValidator validator = new TestFileIDValidator(settings); - Assert.assertNull(validator.getRegex()); + Assertions.assertNull(validator.getRegex()); addStep("Give the validator an empty string as allowed file id pattern", "Should be a null stored as regex." ); settings.getRepositorySettings().getProtocolSettings().setAllowedFileIDPattern(""); validator = new TestFileIDValidator(settings); - Assert.assertNull(validator.getRegex()); + Assertions.assertNull(validator.getRegex()); } private class TestFileIDValidator extends FileIDValidator { diff --git a/bitrepository-core/src/test/java/org/bitrepository/common/utils/FileUtilsTest.java b/bitrepository-core/src/test/java/org/bitrepository/common/utils/FileUtilsTest.java index 4bf711ce2..385a12ff2 100644 --- a/bitrepository-core/src/test/java/org/bitrepository/common/utils/FileUtilsTest.java +++ b/bitrepository-core/src/test/java/org/bitrepository/common/utils/FileUtilsTest.java @@ -5,16 +5,16 @@ * Copyright (C) 2010 - 2012 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% @@ -23,10 +23,11 @@ import org.apache.activemq.util.ByteArrayInputStream; import org.jaccept.structure.ExtendedTestCase; -import org.testng.Assert; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; import java.io.File; import java.nio.charset.StandardCharsets; @@ -38,195 +39,204 @@ public class FileUtilsTest extends ExtendedTestCase { String MOVED_FILE_NAME = "moved.file.name"; String DATA = "The data for the stream."; - @BeforeMethod(alwaysRun = true) + @BeforeEach public void setupTest() throws Exception { File dir = new File(DIR); - if(dir.exists()) { + if (dir.exists()) { FileUtils.delete(dir); } } - @AfterMethod(alwaysRun = true) + + @AfterEach public void teardownTest() throws Exception { File dir = new File(DIR); - if(dir.exists()) { + if (dir.exists()) { FileUtils.delete(dir); } } - @Test(groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public void createDirectoryTester() throws Exception { addDescription("Test the ability to create directories."); addStep("Test the ability to create a directory", "Should be created by utility."); File dir = new File(DIR); - Assert.assertFalse(dir.exists()); + Assertions.assertFalse(dir.exists()); File madeDir = FileUtils.retrieveDirectory(DIR); - Assert.assertTrue(madeDir.exists()); - Assert.assertTrue(madeDir.isDirectory()); - Assert.assertTrue(dir.isDirectory()); - Assert.assertEquals(dir.getAbsolutePath(), madeDir.getAbsolutePath()); - + Assertions.assertTrue(madeDir.exists()); + Assertions.assertTrue(madeDir.isDirectory()); + Assertions.assertTrue(dir.isDirectory()); + Assertions.assertEquals(dir.getAbsolutePath(), madeDir.getAbsolutePath()); + addStep("Test error scenarios, when the directory path is a file", "Should throw exception"); File testFile = new File(dir, TEST_FILE_NAME); - Assert.assertTrue(testFile.createNewFile()); + Assertions.assertTrue(testFile.createNewFile()); try { FileUtils.retrieveDirectory(testFile.getPath()); - Assert.fail("Should throw an exception"); + Assertions.fail("Should throw an exception"); } catch (IllegalArgumentException e) { // expected } } - - @Test(groups = {"regressiontest"}) + + @Test + @Tag("regressiontest") public void createSubDirectoryTester() throws Exception { addDescription("Test the ability to create sub directories."); addStep("Test the ability to create sub-directories", "Should be created by utility"); File dir = FileUtils.retrieveDirectory(DIR); File subdir = new File(dir, SUB_DIR); - Assert.assertFalse(subdir.exists()); + Assertions.assertFalse(subdir.exists()); File madeSubdir = FileUtils.retrieveSubDirectory(dir, SUB_DIR); - Assert.assertTrue(madeSubdir.exists()); - Assert.assertTrue(madeSubdir.isDirectory()); - Assert.assertTrue(subdir.isDirectory()); - Assert.assertEquals(subdir.getAbsolutePath(), madeSubdir.getAbsolutePath()); - + Assertions.assertTrue(madeSubdir.exists()); + Assertions.assertTrue(madeSubdir.isDirectory()); + Assertions.assertTrue(subdir.isDirectory()); + Assertions.assertEquals(subdir.getAbsolutePath(), madeSubdir.getAbsolutePath()); + addStep("Test that it fails if the 'directory' is actually a file", "Throws exception"); File testFile = new File(dir, TEST_FILE_NAME); - Assert.assertTrue(testFile.createNewFile()); + Assertions.assertTrue(testFile.createNewFile()); try { FileUtils.retrieveSubDirectory(testFile, SUB_DIR); - Assert.fail("Should throw an exception"); + Assertions.fail("Should throw an exception"); } catch (IllegalArgumentException e) { // expected } - + addStep("Test that it fails, if the parent directory does not allow writing", "Throws exception"); FileUtils.delete(subdir); try { dir.setWritable(false); FileUtils.retrieveSubDirectory(dir, SUB_DIR); - Assert.fail("Should throw an exception"); + Assertions.fail("Should throw an exception"); } catch (IllegalStateException e) { // expected } finally { dir.setWritable(true); } } - - @Test(groups = {"regressiontest"}) + + @Test + @Tag("regressiontest") public void createDeleteDirectoryTester() throws Exception { addDescription("Test the ability to delete directories."); addStep("Test deleting a directory with file and subdirectory", "Removes directory, sub-directory and file"); File dir = FileUtils.retrieveDirectory(DIR); File subdir = FileUtils.retrieveSubDirectory(dir, SUB_DIR); - Assert.assertTrue(dir.exists()); - Assert.assertTrue(subdir.exists()); + Assertions.assertTrue(dir.exists()); + Assertions.assertTrue(subdir.exists()); File testFile = new File(dir, TEST_FILE_NAME); - Assert.assertTrue(testFile.createNewFile()); - Assert.assertTrue(testFile.exists()); - + Assertions.assertTrue(testFile.createNewFile()); + Assertions.assertTrue(testFile.exists()); + FileUtils.delete(dir); - Assert.assertFalse(dir.exists()); - Assert.assertFalse(subdir.exists()); - Assert.assertFalse(testFile.exists()); + Assertions.assertFalse(dir.exists()); + Assertions.assertFalse(subdir.exists()); + Assertions.assertFalse(testFile.exists()); } - - @Test(groups = {"regressiontest"}) + + @Test + @Tag("regressiontest") public void deprecateFileTester() throws Exception { addDescription("Test the deprecation of a file."); addStep("Setup", ""); File dir = FileUtils.retrieveDirectory(DIR); File testFile = new File(dir, TEST_FILE_NAME); - Assert.assertFalse(testFile.exists()); - Assert.assertTrue(testFile.createNewFile()); - Assert.assertTrue(testFile.exists()); - + Assertions.assertFalse(testFile.exists()); + Assertions.assertTrue(testFile.createNewFile()); + Assertions.assertTrue(testFile.exists()); + addStep("Deprecate the file", "Should be move to '*.old'"); FileUtils.deprecateFile(testFile); - Assert.assertFalse(testFile.exists()); + Assertions.assertFalse(testFile.exists()); File deprecatedFile = new File(dir, TEST_FILE_NAME + ".old"); - Assert.assertTrue(deprecatedFile.exists()); + Assertions.assertTrue(deprecatedFile.exists()); } - - @Test(groups = {"regressiontest"}) + + @Test + @Tag("regressiontest") public void moveFileTester() throws Exception { addDescription("Test the moving of a file."); addStep("Setup", ""); File dir = FileUtils.retrieveDirectory(DIR); File testFile = new File(dir, TEST_FILE_NAME); File movedFile = new File(dir, MOVED_FILE_NAME); - Assert.assertFalse(testFile.exists()); - Assert.assertFalse(movedFile.exists()); - Assert.assertTrue(testFile.createNewFile()); - Assert.assertTrue(testFile.exists()); - + Assertions.assertFalse(testFile.exists()); + Assertions.assertFalse(movedFile.exists()); + Assertions.assertTrue(testFile.createNewFile()); + Assertions.assertTrue(testFile.exists()); + addStep("Move the file", "The 'moved' should exist, whereas the other should not."); FileUtils.moveFile(testFile, movedFile); - Assert.assertFalse(testFile.exists()); - Assert.assertTrue(movedFile.exists()); + Assertions.assertFalse(testFile.exists()); + Assertions.assertTrue(movedFile.exists()); } - - @Test(groups = {"regressiontest"}) + + @Test + @Tag("regressiontest") public void writeInputstreamTester() throws Exception { addDescription("Test writing an inputstream to a file."); addStep("Setup", ""); File dir = FileUtils.retrieveDirectory(DIR); File testFile = new File(dir, TEST_FILE_NAME); - Assert.assertFalse(testFile.exists()); + Assertions.assertFalse(testFile.exists()); ByteArrayInputStream in = new ByteArrayInputStream(DATA.getBytes(StandardCharsets.UTF_8)); addStep("Write the input stream to the file", "The file should exist and have same size as the data."); FileUtils.writeStreamToFile(in, testFile); - Assert.assertTrue(testFile.exists()); - Assert.assertEquals(testFile.length(), DATA.length()); + Assertions.assertTrue(testFile.exists()); + Assertions.assertEquals(testFile.length(), DATA.length()); } - @Test(groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public void unzipFileTester() throws Exception { addDescription("Test unzipping a file."); addStep("Setup", ""); File dir = FileUtils.retrieveDirectory(DIR); File zipFile = new File("src/test/resources/test-files/test.jar"); - Assert.assertTrue(zipFile.isFile(), zipFile.getAbsolutePath()); - Assert.assertEquals(dir.listFiles().length, 0); + Assertions.assertTrue(zipFile.isFile(), zipFile.getAbsolutePath()); + Assertions.assertEquals(0, dir.listFiles().length); addStep("Unzip the zipfile to the directory", "Should place a file and a directory inside the dir"); FileUtils.unzip(zipFile, dir); - Assert.assertEquals(dir.listFiles().length, 2); + Assertions.assertEquals(2, dir.listFiles().length); } - - @Test(groups = {"regressiontest"}) + + @Test + @Tag("regressiontest") public void cleanupEmptyDirectoriesTester() throws Exception { addDescription("Test the cleanup of empty directories."); File dir = FileUtils.retrieveDirectory(DIR); File subDir = FileUtils.retrieveSubDirectory(dir, SUB_DIR); File subSubDir = FileUtils.retrieveSubDirectory(subDir, SUB_DIR); - + addStep("Cleanup non-empty folder", "Should not do anything"); - Assert.assertTrue(subSubDir.isDirectory()); + Assertions.assertTrue(subSubDir.isDirectory()); FileUtils.cleanupEmptyDirectories(subDir, dir); - Assert.assertTrue(subSubDir.isDirectory()); - Assert.assertTrue(subDir.isDirectory()); - Assert.assertTrue(dir.isDirectory()); - + Assertions.assertTrue(subSubDir.isDirectory()); + Assertions.assertTrue(subDir.isDirectory()); + Assertions.assertTrue(dir.isDirectory()); + addStep("Cleanup when dir and root are the same", "Should do nothing"); - Assert.assertTrue(subSubDir.isDirectory()); + Assertions.assertTrue(subSubDir.isDirectory()); FileUtils.cleanupEmptyDirectories(subSubDir, subSubDir); - Assert.assertTrue(subSubDir.isDirectory()); - + Assertions.assertTrue(subSubDir.isDirectory()); + addStep("Test succes case, when the directory is empty", "Removes sub-dir"); - Assert.assertTrue(subSubDir.isDirectory()); + Assertions.assertTrue(subSubDir.isDirectory()); FileUtils.cleanupEmptyDirectories(subSubDir, dir); - Assert.assertFalse(subSubDir.isDirectory()); - Assert.assertFalse(subDir.isDirectory()); - Assert.assertTrue(dir.isDirectory()); - + Assertions.assertFalse(subSubDir.isDirectory()); + Assertions.assertFalse(subDir.isDirectory()); + Assertions.assertTrue(dir.isDirectory()); + addStep("Test with a file.", "Should do nothing."); File file = new File(dir, TEST_FILE_NAME); - Assert.assertTrue(file.createNewFile()); + Assertions.assertTrue(file.createNewFile()); FileUtils.cleanupEmptyDirectories(file, dir); - Assert.assertTrue(file.exists()); + Assertions.assertTrue(file.exists()); } - + } diff --git a/bitrepository-core/src/test/java/org/bitrepository/common/utils/ResponseInfoUtilsTest.java b/bitrepository-core/src/test/java/org/bitrepository/common/utils/ResponseInfoUtilsTest.java index c4b1d12b6..4d38087a2 100644 --- a/bitrepository-core/src/test/java/org/bitrepository/common/utils/ResponseInfoUtilsTest.java +++ b/bitrepository-core/src/test/java/org/bitrepository/common/utils/ResponseInfoUtilsTest.java @@ -5,16 +5,16 @@ * Copyright (C) 2010 - 2012 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% @@ -24,20 +24,23 @@ import org.bitrepository.bitrepositoryelements.ResponseCode; import org.bitrepository.bitrepositoryelements.ResponseInfo; import org.jaccept.structure.ExtendedTestCase; -import org.testng.Assert; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + public class ResponseInfoUtilsTest extends ExtendedTestCase { - @Test(groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public void responseInfoTester() throws Exception { addDescription("Test the response info."); addStep("Validate the positive identification response", "Should be 'IDENTIFICATION_POSITIVE'"); ResponseInfo ri = ResponseInfoUtils.getPositiveIdentification(); - Assert.assertEquals(ri.getResponseCode(), ResponseCode.IDENTIFICATION_POSITIVE); - + Assertions.assertEquals(ResponseCode.IDENTIFICATION_POSITIVE, ri.getResponseCode()); + addStep("Validate the Progress response", "Should be 'OPERATION_ACCEPTED_PROGRESS'"); ri = ResponseInfoUtils.getInitialProgressResponse(); - Assert.assertEquals(ri.getResponseCode(), ResponseCode.OPERATION_ACCEPTED_PROGRESS); + Assertions.assertEquals(ResponseCode.OPERATION_ACCEPTED_PROGRESS, ri.getResponseCode()); } - + } diff --git a/bitrepository-core/src/test/java/org/bitrepository/common/utils/StreamUtilsTest.java b/bitrepository-core/src/test/java/org/bitrepository/common/utils/StreamUtilsTest.java index cd50c471d..cfab4cd64 100644 --- a/bitrepository-core/src/test/java/org/bitrepository/common/utils/StreamUtilsTest.java +++ b/bitrepository-core/src/test/java/org/bitrepository/common/utils/StreamUtilsTest.java @@ -23,8 +23,9 @@ import org.apache.activemq.util.ByteArrayInputStream; import org.jaccept.structure.ExtendedTestCase; -import org.testng.Assert; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; import java.io.ByteArrayOutputStream; import java.nio.charset.StandardCharsets; @@ -32,7 +33,8 @@ public class StreamUtilsTest extends ExtendedTestCase { String DATA = "The data for the streams."; - @Test(groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public void streamTester() throws Exception { addDescription("Tests the SteamUtils class."); addStep("Setup variables", ""); @@ -42,22 +44,22 @@ public void streamTester() throws Exception { addStep("Test with null arguments", "Should throw exceptions"); try { StreamUtils.copyInputStreamToOutputStream(null, out); - Assert.fail("Should throw an exception here."); + Assertions.fail("Should throw an exception here."); } catch (Exception e) { - Assert.assertTrue(e instanceof IllegalArgumentException); + Assertions.assertInstanceOf(IllegalArgumentException.class, e); } try { StreamUtils.copyInputStreamToOutputStream(in, null); - Assert.fail("Should throw an exception here."); + Assertions.fail("Should throw an exception here."); } catch (Exception e) { - Assert.assertTrue(e instanceof IllegalArgumentException); + Assertions.assertInstanceOf(IllegalArgumentException.class, e); } addStep("Test copying the input stream to the output stream.", "Should contain the same data."); StreamUtils.copyInputStreamToOutputStream(in, out); - Assert.assertEquals(out.toString(StandardCharsets.UTF_8), DATA); + Assertions.assertEquals(out.toString(StandardCharsets.UTF_8), DATA); } } diff --git a/bitrepository-core/src/test/java/org/bitrepository/common/utils/TimeMeasurementUtilsTest.java b/bitrepository-core/src/test/java/org/bitrepository/common/utils/TimeMeasurementUtilsTest.java index 809041fed..daf7fa9c0 100644 --- a/bitrepository-core/src/test/java/org/bitrepository/common/utils/TimeMeasurementUtilsTest.java +++ b/bitrepository-core/src/test/java/org/bitrepository/common/utils/TimeMeasurementUtilsTest.java @@ -1,23 +1,23 @@ /* * #%L * Bitrepository Protocol - * + * * $Id$ * $HeadURL$ * %% * Copyright (C) 2010 - 2011 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% @@ -27,8 +27,9 @@ import org.bitrepository.bitrepositoryelements.TimeMeasureTYPE; import org.bitrepository.bitrepositoryelements.TimeMeasureUnit; import org.jaccept.structure.ExtendedTestCase; -import org.testng.Assert; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; import java.math.BigInteger; @@ -36,66 +37,69 @@ * Tests the TimeMeasureComparator class. */ public class TimeMeasurementUtilsTest extends ExtendedTestCase { - @Test (groups = { "regressiontest" }) + @Test + @Tag("regressiontest") public void testCompareMilliSeconds() { addDescription("Test the comparison between TimeMeasure units."); TimeMeasureTYPE referenceTime = new TimeMeasureTYPE(); referenceTime.setTimeMeasureValue(new BigInteger("2")); referenceTime.setTimeMeasureUnit(TimeMeasureUnit.MILLISECONDS); - + TimeMeasureTYPE compareTime = new TimeMeasureTYPE(); compareTime.setTimeMeasureValue(new BigInteger("3")); compareTime.setTimeMeasureUnit(TimeMeasureUnit.MILLISECONDS); - - Assert.assertTrue(TimeMeasurementUtils.compare(referenceTime, compareTime) < 0, referenceTime + + + Assertions.assertTrue(TimeMeasurementUtils.compare(referenceTime, compareTime) < 0, referenceTime + " should be smaller than " + compareTime); - + compareTime.setTimeMeasureValue(new BigInteger("1")); - Assert.assertTrue(TimeMeasurementUtils.compare(referenceTime, compareTime) > 0, referenceTime + + Assertions.assertTrue(TimeMeasurementUtils.compare(referenceTime, compareTime) > 0, referenceTime + " should be larger than " + compareTime); - + compareTime.setTimeMeasureValue(new BigInteger("2")); - Assert.assertTrue(TimeMeasurementUtils.compare(referenceTime, compareTime) == 0, referenceTime + + Assertions.assertEquals(0, TimeMeasurementUtils.compare(referenceTime, compareTime), referenceTime + " should be same as " + compareTime); } - @Test (groups = { "regressiontest" }) + @Test + @Tag("regressiontest") public void testCompareMilliSecondsToHours() { addDescription("Test the comparison between milliseconds and hours."); long millis = 7200000L; TimeMeasureTYPE referenceTime = new TimeMeasureTYPE(); referenceTime.setTimeMeasureValue(BigInteger.valueOf(millis)); referenceTime.setTimeMeasureUnit(TimeMeasureUnit.MILLISECONDS); - + TimeMeasureTYPE compareTime = new TimeMeasureTYPE(); compareTime.setTimeMeasureValue(new BigInteger("3")); compareTime.setTimeMeasureUnit(TimeMeasureUnit.HOURS); - - Assert.assertTrue(TimeMeasurementUtils.compare(referenceTime, compareTime) < 0, referenceTime + + + Assertions.assertTrue(TimeMeasurementUtils.compare(referenceTime, compareTime) < 0, referenceTime + " should be smaller than " + compareTime); - + compareTime.setTimeMeasureValue(new BigInteger("1")); - Assert.assertTrue(TimeMeasurementUtils.compare(referenceTime, compareTime) > 0, referenceTime + + Assertions.assertTrue(TimeMeasurementUtils.compare(referenceTime, compareTime) > 0, referenceTime + " should be larger than " + compareTime); - + compareTime.setTimeMeasureValue(new BigInteger("2")); - Assert.assertTrue(TimeMeasurementUtils.compare(referenceTime, compareTime) == 0, referenceTime + + Assertions.assertEquals(0, TimeMeasurementUtils.compare(referenceTime, compareTime), referenceTime + " should be same as " + compareTime); - - Assert.assertEquals(TimeMeasurementUtils.getTimeMeasureInLong(referenceTime), millis); + + Assertions.assertEquals(millis, TimeMeasurementUtils.getTimeMeasureInLong(referenceTime)); } - @Test (groups = { "regressiontest" }) + @Test + @Tag("regressiontest") public void testMaxValue() { addDescription("Test the Maximum value"); TimeMeasureTYPE time = TimeMeasurementUtils.getMaximumTime(); - Assert.assertEquals(time.getTimeMeasureValue().longValue(), Long.MAX_VALUE); - Assert.assertEquals(time.getTimeMeasureUnit(), TimeMeasureUnit.HOURS); - + Assertions.assertEquals(Long.MAX_VALUE, time.getTimeMeasureValue().longValue()); + Assertions.assertEquals(TimeMeasureUnit.HOURS, time.getTimeMeasureUnit()); + TimeMeasureTYPE time2 = TimeMeasurementUtils.getTimeMeasurementFromMilliseconds( BigInteger.valueOf(Long.MAX_VALUE)); time2.setTimeMeasureUnit(TimeMeasureUnit.HOURS); - Assert.assertEquals(TimeMeasurementUtils.compare(time, time2), 0); + Assertions.assertEquals(0, TimeMeasurementUtils.compare(time, time2)); } } diff --git a/bitrepository-core/src/test/java/org/bitrepository/common/utils/TimeUtilsTest.java b/bitrepository-core/src/test/java/org/bitrepository/common/utils/TimeUtilsTest.java index 13ecbf7b5..42d23f0e0 100644 --- a/bitrepository-core/src/test/java/org/bitrepository/common/utils/TimeUtilsTest.java +++ b/bitrepository-core/src/test/java/org/bitrepository/common/utils/TimeUtilsTest.java @@ -5,16 +5,16 @@ * Copyright (C) 2010 - 2012 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% @@ -22,8 +22,9 @@ package org.bitrepository.common.utils; import org.jaccept.structure.ExtendedTestCase; -import org.testng.Assert; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; import java.text.DateFormat; import java.text.SimpleDateFormat; @@ -39,40 +40,41 @@ import java.util.Locale; import java.util.concurrent.TimeUnit; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; public class TimeUtilsTest extends ExtendedTestCase { private static final ZonedDateTime BASE = Instant.EPOCH.atZone(ZoneOffset.UTC); - @Test(groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public void timeTester() throws Exception { addDescription("Tests the TimeUtils. Pi days = 271433605 milliseconds"); - addStep("Test that milliseconds can be converted into human readable seconds", + addStep("Test that milliseconds can be converted into human readable seconds", "Pi days % minutes"); long millis = 271433605; String millisInSec = TimeUtils.millisecondsToSeconds(millis % 60000); String expectedSec = "53s"; assertTrue(millisInSec.startsWith(expectedSec)); - - addStep("Test that milliseconds can be converted into human readable minutes.", + + addStep("Test that milliseconds can be converted into human readable minutes.", "Pi days % hours"); String millisInMin = TimeUtils.millisecondsToMinutes(millis % 3600000); String expectedMin = "23m"; assertTrue(millisInMin.startsWith(expectedMin)); - - addStep("Test that milliseconds can be converted into human readable hours.", + + addStep("Test that milliseconds can be converted into human readable hours.", "Pi days % days"); - String millisInHour = TimeUtils.millisecondsToHours(millis % (3600000*24)); + String millisInHour = TimeUtils.millisecondsToHours(millis % (3600000 * 24)); String expectedHours = "3h"; assertTrue(millisInHour.startsWith(expectedHours)); - - addStep("Test that milliseconds can be converted into human readable minutes.", + + addStep("Test that milliseconds can be converted into human readable minutes.", "Pi days"); String millisInDay = TimeUtils.millisecondsToDays(millis); String expectedDays = "3d"; assertTrue(millisInDay.startsWith(expectedDays)); - + addStep("Test the human readable output.", ""); String human = TimeUtils.millisecondsToHuman(millis); assertTrue(human.contains(expectedSec), human); @@ -81,60 +83,65 @@ public void timeTester() throws Exception { assertTrue(human.contains(expectedDays), human); } - @Test(groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public void printsHumanDuration() { - assertEquals(TimeUtils.durationToHumanUsingEstimates(ChronoUnit.YEARS.getDuration()), "1y"); - assertEquals(TimeUtils.durationToHumanUsingEstimates(ChronoUnit.MONTHS.getDuration()), "1m"); - assertEquals(TimeUtils.durationToHumanUsingEstimates(ChronoUnit.DAYS.getDuration()), "1d"); - assertEquals(TimeUtils.durationToHumanUsingEstimates(ChronoUnit.HOURS.getDuration()), "1h"); - assertEquals(TimeUtils.durationToHumanUsingEstimates(ChronoUnit.MINUTES.getDuration()), "1m"); + assertEquals("1y", TimeUtils.durationToHumanUsingEstimates(ChronoUnit.YEARS.getDuration())); + assertEquals("1m", TimeUtils.durationToHumanUsingEstimates(ChronoUnit.MONTHS.getDuration())); + assertEquals("1d", TimeUtils.durationToHumanUsingEstimates(ChronoUnit.DAYS.getDuration())); + assertEquals("1h", TimeUtils.durationToHumanUsingEstimates(ChronoUnit.HOURS.getDuration())); + assertEquals("1m", TimeUtils.durationToHumanUsingEstimates(ChronoUnit.MINUTES.getDuration())); // Don’t print seconds - assertEquals(TimeUtils.durationToHumanUsingEstimates(ChronoUnit.SECONDS.getDuration()), "0m"); - assertEquals(TimeUtils.durationToHumanUsingEstimates(Duration.parse("PT2H3M5S")), "2h 3m"); + assertEquals("0m", TimeUtils.durationToHumanUsingEstimates(ChronoUnit.SECONDS.getDuration())); + assertEquals("2h 3m", TimeUtils.durationToHumanUsingEstimates(Duration.parse("PT2H3M5S"))); addStep("Test the limits of what the method handles", "0m and 500y respectively"); - assertEquals(TimeUtils.durationToHumanUsingEstimates(Duration.ZERO), "0m"); - assertEquals(TimeUtils.durationToHumanUsingEstimates(Duration.ofHours(4_382_910)), "500y"); + assertEquals("0m", TimeUtils.durationToHumanUsingEstimates(Duration.ZERO)); + assertEquals("500y", TimeUtils.durationToHumanUsingEstimates(Duration.ofHours(4_382_910))); } - @Test(groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public void zeroIntervalTest() throws Exception { addDescription("Verifies that a 0 ms interval is represented correctly"); addStep("Call millisecondsToHuman with 0 ms", "The output should be '0 ms'"); String zeroTimeString = TimeUtils.millisecondsToHuman(0); - assertEquals(zeroTimeString, " 0 ms"); + assertEquals(" 0 ms", zeroTimeString); } - @Test(groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public void durationsPrintHumanly() { addDescription("Tests durationToHuman()"); assertTrue(TimeUtils.durationToHuman(Duration.ZERO).contains("0"), "Zero duration should contain a 0 digit"); - assertEquals(TimeUtils.durationToHuman(Duration.ofDays(2)), "2d"); - assertEquals(TimeUtils.durationToHuman(Duration.ofHours(3)), "3h"); - assertEquals(TimeUtils.durationToHuman(Duration.ofMinutes(5)), "5m"); - assertEquals(TimeUtils.durationToHuman(Duration.ofSeconds(7)), "7s"); - assertEquals(TimeUtils.durationToHuman(Duration.ofMillis(11)), "11 ms"); - assertEquals(TimeUtils.durationToHuman(Duration.ofNanos(13)), "13 ns"); + assertEquals("2d", TimeUtils.durationToHuman(Duration.ofDays(2))); + assertEquals("3h", TimeUtils.durationToHuman(Duration.ofHours(3))); + assertEquals("5m", TimeUtils.durationToHuman(Duration.ofMinutes(5))); + assertEquals("7s", TimeUtils.durationToHuman(Duration.ofSeconds(7))); + assertEquals("11 ms", TimeUtils.durationToHuman(Duration.ofMillis(11))); + assertEquals("13 ns", TimeUtils.durationToHuman(Duration.ofNanos(13))); // When there are nanoseconds, don't print millis - assertEquals(TimeUtils.durationToHuman(Duration.ofNanos(999_999_937)), "999999937 ns"); + assertEquals("999999937 ns", TimeUtils.durationToHuman(Duration.ofNanos(999_999_937))); - assertEquals(TimeUtils.durationToHuman(Duration.ofDays(-2)), "minus 2d"); - assertEquals(TimeUtils.durationToHuman(Duration.ofNanos(-13)), "minus 13 ns"); + assertEquals("minus 2d", TimeUtils.durationToHuman(Duration.ofDays(-2))); + assertEquals("minus 13 ns", TimeUtils.durationToHuman(Duration.ofNanos(-13))); Duration allUnits = Duration.parse("P3DT5H7M11.013000017S"); - assertEquals(TimeUtils.durationToHuman(allUnits), "3d 5h 7m 11s 13000017 ns"); + assertEquals("3d 5h 7m 11s 13000017 ns", TimeUtils.durationToHuman(allUnits)); } - @Test(groups = {"regressiontest"}) + + @Test + @Tag("regressiontest") public void differencesPrintHumanly() { addDescription("TimeUtils.humanDifference() should return" + " similar human readable strings to those from millisecondsToHuman()"); addStep("Call humanDifference() with same time twice", "The output should be '0m'"); String zeroTimeString = TimeUtils.humanDifference(BASE, BASE); - assertEquals(zeroTimeString, "0m"); + assertEquals("0m", zeroTimeString); addStep("Call humanDifference() with a difference obtained from a Duration", "Expect corresponding readable output"); @@ -168,10 +175,11 @@ public void differencesPrintHumanly() { 12, 0, 0, 0, testZoneId), ZonedDateTime.of(2021, 2, 2, 11, 59, 29, 0, testZoneId)); - assertEquals(oneDaySomethingString, "1d 23h 59m"); + assertEquals("1d 23h 59m", oneDaySomethingString); } - @Test(groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public void differencesPrintsWithAppropriatePrecision() { // Include hours if months are 6 or less. testHumanDifference("11m", Period.ofMonths(11), Duration.ofHours(23)); @@ -204,59 +212,62 @@ public void differencesPrintsWithAppropriatePrecision() { */ private void testHumanDifference(String expected, TemporalAmount... amounts) { ZonedDateTime end = BASE; - for (TemporalAmount amount: amounts) { + for (TemporalAmount amount : amounts) { end = end.plus(amount); } String differenceString = TimeUtils.humanDifference(BASE, end); - assertEquals(differenceString, expected); + assertEquals(expected, differenceString); } /* * The test only ensures that the output format is fixed. Which timezone the date is - * formatted to depends on the default/system timezone. At some time the use of the old java Date + * formatted to depends on the default/system timezone. At some time the use of the old java Date * api should be discontinued and the new Java Time api used instead. */ - @Test(groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public void shortDateTest() { - DateFormat formatter = new SimpleDateFormat("yyyy/MM/dd HH:mm", Locale.ROOT); + DateFormat formatter = new SimpleDateFormat("yyyy/MM/dd HH:mm", Locale.ROOT); Date date = new Date(1360069129256L); String shortDateString = TimeUtils.shortDate(date); - Assert.assertEquals(shortDateString, formatter.format(date)); + Assertions.assertEquals(shortDateString, formatter.format(date)); } - @Test(groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public void rejectsNegativeDuration() { - Assert.assertThrows(IllegalArgumentException.class, + Assertions.assertThrows(IllegalArgumentException.class, () -> TimeUtils.durationToCountAndTimeUnit(Duration.ofSeconds(Long.MIN_VALUE))); - Assert.assertThrows(IllegalArgumentException.class, + Assertions.assertThrows(IllegalArgumentException.class, () -> TimeUtils.durationToCountAndTimeUnit(Duration.ofNanos(-1))); } - @Test(groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public void convertsDurationToCountAndTimeUnit() { CountAndTimeUnit expectedZero = TimeUtils.durationToCountAndTimeUnit(Duration.ZERO); - Assert.assertEquals(expectedZero.getCount(), 0); - Assert.assertNotNull(expectedZero.getUnit()); + Assertions.assertEquals(0, expectedZero.getCount()); + Assertions.assertNotNull(expectedZero.getUnit()); - Assert.assertEquals(TimeUtils.durationToCountAndTimeUnit(Duration.ofNanos(1)), - new CountAndTimeUnit(1, TimeUnit.NANOSECONDS)); - Assert.assertEquals(TimeUtils.durationToCountAndTimeUnit(Duration.ofNanos(Long.MAX_VALUE)), - new CountAndTimeUnit(Long.MAX_VALUE, TimeUnit.NANOSECONDS)); - Assert.assertEquals( - TimeUtils.durationToCountAndTimeUnit(Duration.of(Long.MAX_VALUE / 1000 + 1, ChronoUnit.MICROS)), - new CountAndTimeUnit(Long.MAX_VALUE / 1000 + 1, TimeUnit.MICROSECONDS)); - Assert.assertEquals(TimeUtils.durationToCountAndTimeUnit(Duration.of(Long.MAX_VALUE, ChronoUnit.MICROS)), - new CountAndTimeUnit(Long.MAX_VALUE, TimeUnit.MICROSECONDS)); - Assert.assertEquals( - TimeUtils.durationToCountAndTimeUnit(Duration.ofMillis(Long.MAX_VALUE / 1000 + 1)), - new CountAndTimeUnit(Long.MAX_VALUE / 1000 + 1, TimeUnit.MILLISECONDS)); - Assert.assertEquals(TimeUtils.durationToCountAndTimeUnit(Duration.ofMillis(Long.MAX_VALUE)), - new CountAndTimeUnit(Long.MAX_VALUE, TimeUnit.MILLISECONDS)); - Assert.assertEquals( - TimeUtils.durationToCountAndTimeUnit(Duration.ofSeconds(Long.MAX_VALUE / 1000 + 1)), - new CountAndTimeUnit(Long.MAX_VALUE / 1000 + 1, TimeUnit.SECONDS)); - Assert.assertEquals(TimeUtils.durationToCountAndTimeUnit(Duration.ofSeconds(Long.MAX_VALUE)), - new CountAndTimeUnit(Long.MAX_VALUE, TimeUnit.SECONDS)); + Assertions.assertEquals(new CountAndTimeUnit(1, TimeUnit.NANOSECONDS), + TimeUtils.durationToCountAndTimeUnit(Duration.ofNanos(1))); + Assertions.assertEquals(new CountAndTimeUnit(Long.MAX_VALUE, TimeUnit.NANOSECONDS), + TimeUtils.durationToCountAndTimeUnit(Duration.ofNanos(Long.MAX_VALUE))); + Assertions.assertEquals( + new CountAndTimeUnit(Long.MAX_VALUE / 1000 + 1, TimeUnit.MICROSECONDS), + TimeUtils.durationToCountAndTimeUnit(Duration.of(Long.MAX_VALUE / 1000 + 1, ChronoUnit.MICROS))); + Assertions.assertEquals(new CountAndTimeUnit(Long.MAX_VALUE, TimeUnit.MICROSECONDS), + TimeUtils.durationToCountAndTimeUnit(Duration.of(Long.MAX_VALUE, ChronoUnit.MICROS))); + Assertions.assertEquals( + new CountAndTimeUnit(Long.MAX_VALUE / 1000 + 1, TimeUnit.MILLISECONDS), + TimeUtils.durationToCountAndTimeUnit(Duration.ofMillis(Long.MAX_VALUE / 1000 + 1))); + Assertions.assertEquals(new CountAndTimeUnit(Long.MAX_VALUE, TimeUnit.MILLISECONDS), + TimeUtils.durationToCountAndTimeUnit(Duration.ofMillis(Long.MAX_VALUE))); + Assertions.assertEquals( + new CountAndTimeUnit(Long.MAX_VALUE / 1000 + 1, TimeUnit.SECONDS), + TimeUtils.durationToCountAndTimeUnit(Duration.ofSeconds(Long.MAX_VALUE / 1000 + 1))); + Assertions.assertEquals(new CountAndTimeUnit(Long.MAX_VALUE, TimeUnit.SECONDS), + TimeUtils.durationToCountAndTimeUnit(Duration.ofSeconds(Long.MAX_VALUE))); } } diff --git a/bitrepository-core/src/test/java/org/bitrepository/common/utils/XmlUtilsTest.java b/bitrepository-core/src/test/java/org/bitrepository/common/utils/XmlUtilsTest.java index 2bf1b2bab..e53389247 100644 --- a/bitrepository-core/src/test/java/org/bitrepository/common/utils/XmlUtilsTest.java +++ b/bitrepository-core/src/test/java/org/bitrepository/common/utils/XmlUtilsTest.java @@ -3,68 +3,75 @@ import org.bitrepository.bitrepositoryelements.TimeMeasureTYPE; import org.bitrepository.bitrepositoryelements.TimeMeasureUnit; import org.jaccept.structure.ExtendedTestCase; -import org.testng.Assert; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; import javax.xml.datatype.DatatypeConfigurationException; import javax.xml.datatype.DatatypeFactory; import java.math.BigInteger; import java.time.Duration; +import static org.junit.jupiter.api.Assertions.assertThrows; + public class XmlUtilsTest extends ExtendedTestCase { private DatatypeFactory factory; - @BeforeMethod(alwaysRun = true) + @BeforeEach public void setUpFactory() throws DatatypeConfigurationException { factory = DatatypeFactory.newInstance(); } - @Test(groups = {"regressiontest"}, expectedExceptions = IllegalArgumentException.class) + @Test + @Tag("regressiontest") public void negativeDurationIsRejected() { - XmlUtils.validateNonNegative(factory.newDuration("-PT0.00001S")); + assertThrows(IllegalArgumentException.class, () -> { + XmlUtils.validateNonNegative(factory.newDuration("-PT0.00001S")); + }); } - @Test(groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public void testXmlDurationToDuration() { addDescription("Tests xmlDurationToDuration in sunshine scenario cases"); addStep("Durations of 0 of some time unit", "Duration.ZERO"); - Assert.assertEquals(XmlUtils.xmlDurationToDuration(factory.newDuration("P0Y")), Duration.ZERO); - Assert.assertEquals(XmlUtils.xmlDurationToDuration(factory.newDuration("P0M")), Duration.ZERO); - Assert.assertEquals(XmlUtils.xmlDurationToDuration(factory.newDuration("P0D")), Duration.ZERO); - Assert.assertEquals(XmlUtils.xmlDurationToDuration(factory.newDuration("PT0H")), Duration.ZERO); - Assert.assertEquals(XmlUtils.xmlDurationToDuration(factory.newDuration("PT0M")), Duration.ZERO); - Assert.assertEquals(XmlUtils.xmlDurationToDuration(factory.newDuration("PT0S")), Duration.ZERO); - Assert.assertEquals(XmlUtils.xmlDurationToDuration(factory.newDuration("PT0.0000S")), - Duration.ZERO); + Assertions.assertEquals(Duration.ZERO, XmlUtils.xmlDurationToDuration(factory.newDuration("P0Y"))); + Assertions.assertEquals(Duration.ZERO, XmlUtils.xmlDurationToDuration(factory.newDuration("P0M"))); + Assertions.assertEquals(Duration.ZERO, XmlUtils.xmlDurationToDuration(factory.newDuration("P0D"))); + Assertions.assertEquals(Duration.ZERO, XmlUtils.xmlDurationToDuration(factory.newDuration("PT0H"))); + Assertions.assertEquals(Duration.ZERO, XmlUtils.xmlDurationToDuration(factory.newDuration("PT0M"))); + Assertions.assertEquals(Duration.ZERO, XmlUtils.xmlDurationToDuration(factory.newDuration("PT0S"))); + Assertions.assertEquals(Duration.ZERO, + XmlUtils.xmlDurationToDuration(factory.newDuration("PT0.0000S"))); addStep("Test correct and precise conversion", "Hours, minutes and seconds are converted with full precision"); - Assert.assertEquals(XmlUtils.xmlDurationToDuration(factory.newDuration("PT3S")), + Assertions.assertEquals(XmlUtils.xmlDurationToDuration(factory.newDuration("PT3S")), Duration.ofSeconds(3)); - Assert.assertEquals(XmlUtils.xmlDurationToDuration(factory.newDuration("PT3.3S")), + Assertions.assertEquals(XmlUtils.xmlDurationToDuration(factory.newDuration("PT3.3S")), Duration.ofSeconds(3, 300_000_000)); - Assert.assertEquals(XmlUtils.xmlDurationToDuration(factory.newDuration("PT3.000000003S")), + Assertions.assertEquals(XmlUtils.xmlDurationToDuration(factory.newDuration("PT3.000000003S")), Duration.ofSeconds(3, 3)); - Assert.assertEquals(XmlUtils.xmlDurationToDuration(factory.newDuration("PT3.123456789S")), + Assertions.assertEquals(XmlUtils.xmlDurationToDuration(factory.newDuration("PT3.123456789S")), Duration.ofSeconds(3, 123_456_789)); - Assert.assertEquals(XmlUtils.xmlDurationToDuration(factory.newDuration("PT4M")), + Assertions.assertEquals(XmlUtils.xmlDurationToDuration(factory.newDuration("PT4M")), Duration.ofMinutes(4)); - Assert.assertEquals(XmlUtils.xmlDurationToDuration(factory.newDuration("PT5H")), + Assertions.assertEquals(XmlUtils.xmlDurationToDuration(factory.newDuration("PT5H")), Duration.ofHours(5)); - Assert.assertEquals(XmlUtils.xmlDurationToDuration(factory.newDuration("PT6H7M8.9S")), + Assertions.assertEquals(XmlUtils.xmlDurationToDuration(factory.newDuration("PT6H7M8.9S")), Duration.ofHours(6).plusMinutes(7).plusSeconds(8).plusMillis(900)); addStep("Test approximate conversion", "Days, months and years are converted using estimated factors"); - Assert.assertEquals(XmlUtils.xmlDurationToDuration(factory.newDuration("P2D")), + Assertions.assertEquals(XmlUtils.xmlDurationToDuration(factory.newDuration("P2D")), Duration.ofDays(2)); - Assert.assertEquals(XmlUtils.xmlDurationToDuration(factory.newDuration("P3DT4M")), + Assertions.assertEquals(XmlUtils.xmlDurationToDuration(factory.newDuration("P3DT4M")), Duration.ofDays(3).plusMinutes(4)); // We require a month to be between 28 and 31 days exclusive @@ -80,18 +87,19 @@ public void testXmlDurationToDuration() { assertBetweenExclusive(convertedTwoYears, minTwoYearsLengthExclusive, maxTwoYearsLengthExclusive); } - @Test(groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public void testNegativeXmlDurationToDuration() { // WorkflowInterval may be negative (meaning don’t run automatically) addDescription("Tests that xmlDurationToDuration() accepts a negative duration and converts it correctly"); addStep("Negative XML durations", "Corresponding negative java.time durations"); - Assert.assertEquals(XmlUtils.xmlDurationToDuration(factory.newDuration("-PT3S")), + Assertions.assertEquals(XmlUtils.xmlDurationToDuration(factory.newDuration("-PT3S")), Duration.ofSeconds(-3)); - Assert.assertEquals(XmlUtils.xmlDurationToDuration(factory.newDuration("-PT0.000001S")), + Assertions.assertEquals(XmlUtils.xmlDurationToDuration(factory.newDuration("-PT0.000001S")), Duration.ofNanos(-1000)); - Assert.assertEquals(XmlUtils.xmlDurationToDuration(factory.newDuration("-PT24H")), + Assertions.assertEquals(XmlUtils.xmlDurationToDuration(factory.newDuration("-PT24H")), Duration.ofHours(-24)); - Assert.assertEquals(XmlUtils.xmlDurationToDuration(factory.newDuration("-P1D")), + Assertions.assertEquals(XmlUtils.xmlDurationToDuration(factory.newDuration("-P1D")), Duration.ofDays(-1)); // We require minus 1 month to be between -31 and -28 days exclusive @@ -108,50 +116,56 @@ public void testNegativeXmlDurationToDuration() { } private static > void assertBetweenExclusive(T actual, T minExclusive, T maxExclusive) { - Assert.assertTrue(actual.compareTo(minExclusive) > 0); - Assert.assertTrue(actual.compareTo(maxExclusive) < 0); + Assertions.assertTrue(actual.compareTo(minExclusive) > 0); + Assertions.assertTrue(actual.compareTo(maxExclusive) < 0); } - @Test(groups = {"regressiontest"}, expectedExceptions = ArithmeticException.class) + @Test + @Tag("regressiontest") public void tooManyDecimalsAreRejected() { - addDescription("Tests that xmlDurationToDuration() rejects more than 9 decimals on seconds"); - addStep("Duration with 10 decimals, PT2.0123456789S", "ArithmeticException"); - XmlUtils.xmlDurationToDuration(factory.newDuration("PT2.0123456789S")); + assertThrows(ArithmeticException.class, () -> { + addDescription("Tests that xmlDurationToDuration() rejects more than 9 decimals on seconds"); + addStep("Duration with 10 decimals, PT2.0123456789S", "ArithmeticException"); + XmlUtils.xmlDurationToDuration(factory.newDuration("PT2.0123456789S")); + }); } - @Test(groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public void testXmlDurationToMilliseconds() { addDescription("Tests xmlDurationToMilliseconds in sunshine scenario cases"); addStep("Test correct and precise conversion", "Hours, minutes and seconds are converted with full precision"); - Assert.assertEquals(XmlUtils.xmlDurationToMilliseconds(factory.newDuration(1)), 1); - Assert.assertEquals(XmlUtils.xmlDurationToMilliseconds(factory.newDuration(1000)), 1000); + Assertions.assertEquals(1, XmlUtils.xmlDurationToMilliseconds(factory.newDuration(1))); + Assertions.assertEquals(1000, XmlUtils.xmlDurationToMilliseconds(factory.newDuration(1000))); - Assert.assertEquals(XmlUtils.xmlDurationToMilliseconds(factory.newDuration("PT0.001S")), 1); - Assert.assertEquals(XmlUtils.xmlDurationToMilliseconds(factory.newDuration("PT0.001999S")), 1); - Assert.assertEquals(XmlUtils.xmlDurationToMilliseconds(factory.newDuration("PT2S")), 2000); + Assertions.assertEquals(1, XmlUtils.xmlDurationToMilliseconds(factory.newDuration("PT0.001S"))); + Assertions.assertEquals(1, XmlUtils.xmlDurationToMilliseconds(factory.newDuration("PT0.001999S"))); + Assertions.assertEquals(2000, XmlUtils.xmlDurationToMilliseconds(factory.newDuration("PT2S"))); } - @Test(groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public void testNegativeXmlDurationToMilliseconds() { - Assert.assertEquals(XmlUtils.xmlDurationToMilliseconds(factory.newDuration("-PT1S")), -1000); + Assertions.assertEquals(-1000, XmlUtils.xmlDurationToMilliseconds(factory.newDuration("-PT1S"))); } - @Test(groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public void convertsToTimeMeasure() { TimeMeasureTYPE shortTimeMeasure = XmlUtils.xmlDurationToTimeMeasure(factory.newDuration(1)); - Assert.assertEquals(shortTimeMeasure.getTimeMeasureUnit(), TimeMeasureUnit.MILLISECONDS); - Assert.assertEquals(shortTimeMeasure.getTimeMeasureValue(), BigInteger.ONE); + Assertions.assertEquals(TimeMeasureUnit.MILLISECONDS, shortTimeMeasure.getTimeMeasureUnit()); + Assertions.assertEquals(BigInteger.ONE, shortTimeMeasure.getTimeMeasureValue()); long hours = 2_562_047_788_015L; TimeMeasureTYPE longTimeMeasure = XmlUtils.xmlDurationToTimeMeasure(factory.newDurationDayTime( true, BigInteger.ZERO, BigInteger.valueOf(hours), BigInteger.ZERO, BigInteger.ZERO)); if (longTimeMeasure.getTimeMeasureUnit() == TimeMeasureUnit.HOURS) { - Assert.assertEquals(longTimeMeasure.getTimeMeasureValue(), BigInteger.valueOf(hours)); + Assertions.assertEquals(longTimeMeasure.getTimeMeasureValue(), BigInteger.valueOf(hours)); } else { - Assert.assertEquals(longTimeMeasure.getTimeMeasureUnit(), TimeMeasureUnit.MILLISECONDS); - Assert.assertEquals(longTimeMeasure.getTimeMeasureValue(), + Assertions.assertEquals(TimeMeasureUnit.MILLISECONDS, longTimeMeasure.getTimeMeasureUnit()); + Assertions.assertEquals(longTimeMeasure.getTimeMeasureValue(), BigInteger.valueOf(Duration.ofHours(hours).toMillis())); } } diff --git a/bitrepository-core/src/test/java/org/bitrepository/protocol/BitrepositoryTestSuite.java b/bitrepository-core/src/test/java/org/bitrepository/protocol/BitrepositoryTestSuite.java new file mode 100644 index 000000000..67df11e3e --- /dev/null +++ b/bitrepository-core/src/test/java/org/bitrepository/protocol/BitrepositoryTestSuite.java @@ -0,0 +1,59 @@ +package org.bitrepository.protocol; + +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.platform.suite.api.ExcludeTags; +import org.junit.platform.suite.api.IncludeTags; +import org.junit.platform.suite.api.SelectClasses; +import org.junit.platform.suite.api.SelectPackages; +import org.junit.platform.suite.api.Suite; + +/** + * BitrepositoryTestSuite is a JUnit 5 suite class that groups and configures multiple test classes + * for the BitRepository project. This suite uses JUnit 5 annotations to select test classes, packages, + * and tags, and extend the suite with custom extensions. + * + *

JUnit 5 Annotations Used:

+ *
    + *
  • {@link Suite}: Indicates that this class is a JUnit 5 suite. It groups multiple test classes + * into a single test suite.
  • + *
  • {@link SelectClasses}: Specifies the test classes to be included in the suite. The value is an array + * of class references to the test classes.
  • + *
  • {@link SelectPackages}: Specifies the test packages to be included in the suite. The value is an array + * of package names.
  • + *
  • {@link IncludeTags}: Specifies the tags to include in the suite. The value is an array of tag names.
  • + *
  • {@link ExcludeTags}: Specifies the tags to exclude from the suite. The value is an array of tag names.
  • + *
  • {@link ExtendWith}: Specifies the extensions to be applied to the suite. The value is an array of + * extension classes.
  • + *
+ * + *

Options in a JUnit 5 Suite:

+ *
    + *
  • Selecting Test Classes: Use the {@link SelectClasses} annotation to specify the test + * classes to be included in the suite. The value is an array of class references to the test classes.
  • + *
  • Selecting Test Packages: Use the {@link SelectPackages} annotation to specify the test + * packages to be included in the suite. The value is an array of package names.
  • + *
  • Selecting Tests by Tag: Use the {@link IncludeTags} and {@link ExcludeTags} annotations + * to specify the tags to include or exclude in the suite. The value is an array of tag names.
  • + *
  • Extending the Suite: Use the {@link ExtendWith} annotation to specify custom extensions + * to be applied to the suite. The value is an array of extension classes.
  • + *
+ * + *

Example Usage:

+ *
+ * {@code
+ * @Suite
+ * @SelectClasses({IntegrationTest.class}) // List your test classes here
+ * @SelectPackages("org.bitrepository.protocol") // List your test packages here
+ * @IncludeTags("integration") // List your include tags here
+ * @ExcludeTags("slow") // List your exclude tags here
+ * @ExtendWith(GlobalSuiteExtension.class)
+ * 
+ */ +@Suite +//@SelectClasses({IntegrationTest.class, ActiveMQMessageBusTest.class}) // List your test classes here +@SelectPackages("org.bitrepository.protocol") +@IncludeTags("regressiontest") +@ExtendWith(GlobalSuiteExtension.class) +public class BitrepositoryTestSuite { + // No need for methods here; this just groups and extends +} diff --git a/bitrepository-core/src/test/java/org/bitrepository/protocol/GlobalSuiteExtension.java b/bitrepository-core/src/test/java/org/bitrepository/protocol/GlobalSuiteExtension.java new file mode 100644 index 000000000..8e952cf68 --- /dev/null +++ b/bitrepository-core/src/test/java/org/bitrepository/protocol/GlobalSuiteExtension.java @@ -0,0 +1,148 @@ +package org.bitrepository.protocol; + +import org.bitrepository.common.settings.Settings; +import org.bitrepository.common.settings.TestSettingsProvider; +import org.bitrepository.common.utils.TestFileHelper; +import org.bitrepository.protocol.bus.LocalActiveMQBroker; +import org.bitrepository.protocol.bus.MessageReceiver; +import org.bitrepository.protocol.fileexchange.HttpServerConfiguration; +import org.bitrepository.protocol.http.EmbeddedHttpServer; +import org.bitrepository.protocol.messagebus.MessageBus; +import org.bitrepository.protocol.messagebus.MessageBusManager; +import org.bitrepository.protocol.messagebus.SimpleMessageBus; +import org.bitrepository.protocol.security.DummySecurityManager; +import org.bitrepository.protocol.security.SecurityManager; +import org.jaccept.TestEventManager; +import org.junit.jupiter.api.extension.AfterAllCallback; +import org.junit.jupiter.api.extension.BeforeAllCallback; +import org.junit.jupiter.api.extension.ExtensionContext; + +import javax.jms.JMSException; +import java.net.MalformedURLException; +import java.net.URL; + +public class GlobalSuiteExtension implements BeforeAllCallback, AfterAllCallback { + + private static boolean initialized = false; + protected static TestEventManager testEventManager = TestEventManager.getInstance(); + public static LocalActiveMQBroker broker; + public static EmbeddedHttpServer server; + public static HttpServerConfiguration httpServerConfiguration; + public static MessageBus messageBus; + private MessageReceiverManager receiverManager; + protected static String alarmDestinationID; + protected static MessageReceiver alarmReceiver; + protected static SecurityManager securityManager; + protected static Settings settingsForCUT; + protected static Settings settingsForTestClient; + protected static String collectionID; + protected String nonDefaultFileId; + protected static String DEFAULT_FILE_ID; + protected static URL DEFAULT_FILE_URL; + protected static String DEFAULT_DOWNLOAD_FILE_ADDRESS; + protected static String DEFAULT_UPLOAD_FILE_ADDRESS; + protected String DEFAULT_AUDIT_INFORMATION; + protected String testMethodName; + + @Override + public void beforeAll(ExtensionContext context) { + if (!initialized) { + initialized = true; + settingsForCUT = loadSettings(getComponentID()); + settingsForTestClient = loadSettings("TestSuiteInitialiser"); + makeUserSpecificSettings(settingsForCUT); + makeUserSpecificSettings(settingsForTestClient); + httpServerConfiguration = new HttpServerConfiguration(settingsForTestClient.getReferenceSettings().getFileExchangeSettings()); + collectionID = settingsForTestClient.getCollections().get(0).getID(); + + securityManager = createSecurityManager(); + DEFAULT_FILE_ID = "DefaultFile"; + try { + DEFAULT_FILE_URL = httpServerConfiguration.getURL(TestFileHelper.DEFAULT_FILE_ID); + DEFAULT_DOWNLOAD_FILE_ADDRESS = DEFAULT_FILE_URL.toExternalForm(); + DEFAULT_UPLOAD_FILE_ADDRESS = DEFAULT_FILE_URL.toExternalForm() + "-" + DEFAULT_FILE_ID; + } catch (MalformedURLException e) { + throw new RuntimeException("Never happens", e); + } + } + } + + @Override + public void afterAll(ExtensionContext context) { + if (initialized) { + teardownMessageBus(); + teardownHttpServer(); + } + } + + protected Settings loadSettings(String componentID) { + return TestSettingsProvider.reloadSettings(componentID); + } + + protected void makeUserSpecificSettings(Settings settings) { + settings.getRepositorySettings().getProtocolSettings() + .setCollectionDestination(settings.getCollectionDestination() + getTopicPostfix()); + settings.getRepositorySettings().getProtocolSettings().setAlarmDestination(settings.getAlarmDestination() + getTopicPostfix()); + } + + protected String getTopicPostfix() { + return "-" + System.getProperty("user.name"); + } + + protected String getComponentID() { + return getClass().getSimpleName(); + } + + protected SecurityManager createSecurityManager() { + return new DummySecurityManager(); + } + + /** + * Hooks up the message bus. + */ + protected void setupMessageBus() { + if (useEmbeddedMessageBus()) { + if (messageBus == null) { + messageBus = new SimpleMessageBus(); + } + } + } + + protected void teardownMessageBus() { + MessageBusManager.clear(); + if (messageBus != null) { + try { + messageBus.close(); + messageBus = null; + } catch (JMSException e) { + throw new RuntimeException(e); + } + } + + if (broker != null) { + try { + broker.stop(); + broker = null; + } catch (Exception e) { + // No reason to pollute the test output with this + } + } + } + + /** + * Shutdown the embedded http server if any. + */ + protected void teardownHttpServer() { + if (useEmbeddedHttpServer()) { + server.stop(); + } + } + + public boolean useEmbeddedMessageBus() { + return System.getProperty("useEmbeddedMessageBus", "true").equals("true"); + } + + public boolean useEmbeddedHttpServer() { + return System.getProperty("useEmbeddedHttpServer", "false").equals("true"); + } +} \ No newline at end of file diff --git a/bitrepository-core/src/test/java/org/bitrepository/protocol/IntegrationTest.java b/bitrepository-core/src/test/java/org/bitrepository/protocol/IntegrationTest.java index ece1da863..9f53f8d90 100644 --- a/bitrepository-core/src/test/java/org/bitrepository/protocol/IntegrationTest.java +++ b/bitrepository-core/src/test/java/org/bitrepository/protocol/IntegrationTest.java @@ -39,25 +39,26 @@ import org.bitrepository.protocol.messagebus.SimpleMessageBus; import org.bitrepository.protocol.security.DummySecurityManager; import org.bitrepository.protocol.security.SecurityManager; +import org.bitrepository.protocol.utils.TestWatcherExtension; import org.jaccept.TestEventManager; import org.jaccept.structure.ExtendedTestCase; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.TestInfo; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.extension.RegisterExtension; import org.slf4j.LoggerFactory; -import org.testng.ITestContext; -import org.testng.ITestResult; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.AfterSuite; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.BeforeTest; import javax.jms.JMSException; -import java.lang.reflect.Method; import java.net.MalformedURLException; import java.net.URL; import java.util.List; -public abstract class IntegrationTest extends ExtendedTestCase { +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +@ExtendWith(TestWatcherExtension.class) +//@ExtendWith(GlobalSuiteExtension.class) +public class IntegrationTest extends ExtendedTestCase { protected static TestEventManager testEventManager = TestEventManager.getInstance(); public static LocalActiveMQBroker broker; public static EmbeddedHttpServer server; @@ -70,17 +71,18 @@ public abstract class IntegrationTest extends ExtendedTestCase { protected static Settings settingsForCUT; protected static Settings settingsForTestClient; protected static String collectionID; - protected String NON_DEFAULT_FILE_ID; - protected static String DEFAULT_FILE_ID; - protected static URL DEFAULT_FILE_URL; - protected static String DEFAULT_DOWNLOAD_FILE_ADDRESS; - protected static String DEFAULT_UPLOAD_FILE_ADDRESS; - protected String DEFAULT_AUDIT_INFORMATION; - + protected String nonDefaultFileId; + protected static String defaultFileId; + protected static URL defaultFileUrl; + protected static String defaultDownloadFileAddress; + protected static String defaultUploadFileAddress; + protected String defaultAuditInformation; + + @RegisterExtension + TestWatcherExtension testWatcher = new TestWatcherExtension(); protected String testMethodName; - @BeforeSuite(alwaysRun = true) - public void initializeSuite(ITestContext testContext) { + private void initializationMethod() { settingsForCUT = loadSettings(getComponentID()); settingsForTestClient = loadSettings("TestSuiteInitialiser"); makeUserSpecificSettings(settingsForCUT); @@ -89,11 +91,11 @@ public void initializeSuite(ITestContext testContext) { collectionID = settingsForTestClient.getCollections().get(0).getID(); securityManager = createSecurityManager(); - DEFAULT_FILE_ID = "DefaultFile"; + defaultFileId = "DefaultFile"; try { - DEFAULT_FILE_URL = httpServerConfiguration.getURL(TestFileHelper.DEFAULT_FILE_ID); - DEFAULT_DOWNLOAD_FILE_ADDRESS = DEFAULT_FILE_URL.toExternalForm(); - DEFAULT_UPLOAD_FILE_ADDRESS = DEFAULT_FILE_URL.toExternalForm() + "-" + DEFAULT_FILE_ID; + defaultFileUrl = httpServerConfiguration.getURL(TestFileHelper.DEFAULT_FILE_ID); + defaultDownloadFileAddress = defaultFileUrl.toExternalForm(); + defaultUploadFileAddress = defaultFileUrl.toExternalForm() + "-" + defaultFileId; } catch (MalformedURLException e) { throw new RuntimeException("Never happens"); } @@ -112,12 +114,16 @@ protected void addReceiver(MessageReceiver receiver) { receiverManager.addReceiver(receiver); } - @BeforeClass(alwaysRun = true) public void initMessagebus() { + initializationMethod(); setupMessageBus(); + if (System.getProperty("enableLogStatus", "false").equals("true")) { + LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); + StatusPrinter.print(lc); + } } - @AfterSuite(alwaysRun = true) + @AfterAll public void shutdownSuite() { teardownMessageBus(); teardownHttpServer(); @@ -126,12 +132,13 @@ public void shutdownSuite() { /** * Defines the standard BitRepositoryCollection configuration */ - @BeforeMethod(alwaysRun = true) - public final void beforeMethod(Method method) { - testMethodName = method.getName(); + @BeforeEach + public final void beforeMethod(TestInfo testInfo) { + testMethodName = testInfo.getTestMethod().get().getName(); setupSettings(); - NON_DEFAULT_FILE_ID = TestFileHelper.createUniquePrefix(testMethodName); - DEFAULT_AUDIT_INFORMATION = testMethodName; + nonDefaultFileId = TestFileHelper.createUniquePrefix(testMethodName); + defaultAuditInformation = testMethodName; + initMessagebus(); receiverManager = new MessageReceiverManager(messageBus); registerMessageReceivers(); messageBus.setCollectionFilter(List.of()); @@ -140,15 +147,15 @@ public final void beforeMethod(Method method) { initializeCUT(); } + protected void initializeCUT() { + } - protected void initializeCUT() {} - - @AfterMethod(alwaysRun = true) - public final void afterMethod(ITestResult testResult) { + // @AfterEach + public final void afterMethod() { if (receiverManager != null) { receiverManager.stopListeners(); } - if (testResult.isSuccess()) { + if (testWatcher.isTestSuccessful()) { afterMethodVerification(); } shutdownCUT(); @@ -172,7 +179,8 @@ protected void clearReceivers() { /** * May be overridden by specific tests wishing to do stuff. Remember to call super if this is overridden. */ - protected void shutdownCUT() {} + protected void shutdownCUT() { + } /** * Initializes the settings. Will postfix the alarm and collection topics with '-${user.name} @@ -193,20 +201,12 @@ protected Settings loadSettings(String componentID) { return TestSettingsProvider.reloadSettings(componentID); } - private void makeUserSpecificSettings(Settings settings) { + protected void makeUserSpecificSettings(Settings settings) { settings.getRepositorySettings().getProtocolSettings() .setCollectionDestination(settings.getCollectionDestination() + getTopicPostfix()); settings.getRepositorySettings().getProtocolSettings().setAlarmDestination(settings.getAlarmDestination() + getTopicPostfix()); } - @BeforeTest(alwaysRun = true) - public void writeLogStatus() { - if (System.getProperty("enableLogStatus", "false").equals("true")) { - LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); - StatusPrinter.print(lc); - } - } - /** * Indicated whether an embedded active MQ should be started and used */ @@ -235,7 +235,7 @@ protected void setupMessageBus() { /** * Shutdown the message bus. */ - private void teardownMessageBus() { + public void teardownMessageBus() { MessageBusManager.clear(); if (messageBus != null) { try { @@ -259,7 +259,7 @@ private void teardownMessageBus() { /** * Shutdown the embedded http server if any. */ - protected void teardownHttpServer() { + public void teardownHttpServer() { if (useEmbeddedHttpServer()) { server.stop(); } diff --git a/bitrepository-core/src/test/java/org/bitrepository/protocol/MessageCreationTest.java b/bitrepository-core/src/test/java/org/bitrepository/protocol/MessageCreationTest.java index 99b2f2b2b..9628fb864 100644 --- a/bitrepository-core/src/test/java/org/bitrepository/protocol/MessageCreationTest.java +++ b/bitrepository-core/src/test/java/org/bitrepository/protocol/MessageCreationTest.java @@ -31,7 +31,8 @@ import org.bitrepository.common.JaxbHelper; import org.bitrepository.protocol.message.ExampleMessageFactory; import org.jaccept.structure.ExtendedTestCase; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; import org.w3c.dom.Document; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; @@ -48,12 +49,15 @@ import java.nio.charset.StandardCharsets; import java.util.Iterator; +import static org.junit.jupiter.api.Assertions.assertThrows; + /** * Test whether we are able to create message objects from xml. The input XML is the example code defined in the * message-xml, thereby also testing whether this is valid. * */ public class MessageCreationTest extends ExtendedTestCase { - @Test(groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public void messageCreationTest() throws Exception { addDescription("Tests if we are able to create message objects from xml. The input XML is the example code " + "defined in the message-xml, thereby also testing whether this is valid."); @@ -66,17 +70,21 @@ public void messageCreationTest() throws Exception { } } - @Test(groups = {"regressiontest"}, expectedExceptions = SAXException.class) + @Test + @Tag("regressiontest") public void badDateMessageTest() throws IOException, SAXException, JAXBException { - addDescription("Test to ensure that messages carrying dates must provide offset."); - String messagePath = ExampleMessageFactory.PATH_TO_EXAMPLES + "BadMessages/" + - "BadDateAlarmMessage" + ExampleMessageFactory.EXAMPLE_FILE_POSTFIX; - InputStream messageIS = Thread.currentThread().getContextClassLoader().getResourceAsStream(messagePath); - assert messageIS != null; - String message = IOUtils.toString(messageIS, StandardCharsets.UTF_8); - JaxbHelper jaxbHelper = new JaxbHelper(ExampleMessageFactory.PATH_TO_SCHEMA, ExampleMessageFactory.SCHEMA_NAME); - jaxbHelper.validate(new ByteArrayInputStream(message.getBytes(StandardCharsets.UTF_8))); - AlarmMessage am = jaxbHelper.loadXml(AlarmMessage.class, new ByteArrayInputStream(message.getBytes(StandardCharsets.UTF_8))); + assertThrows(SAXException.class, () -> { + + addDescription("Test to ensure that messages carrying dates must provide offset."); + String messagePath = ExampleMessageFactory.PATH_TO_EXAMPLES + "BadMessages/" + + "BadDateAlarmMessage" + ExampleMessageFactory.EXAMPLE_FILE_POSTFIX; + InputStream messageIS = Thread.currentThread().getContextClassLoader().getResourceAsStream(messagePath); + assert messageIS != null; + String message = IOUtils.toString(messageIS, StandardCharsets.UTF_8); + JaxbHelper jaxbHelper = new JaxbHelper(ExampleMessageFactory.PATH_TO_SCHEMA, ExampleMessageFactory.SCHEMA_NAME); + jaxbHelper.validate(new ByteArrayInputStream(message.getBytes(StandardCharsets.UTF_8))); + AlarmMessage am = jaxbHelper.loadXml(AlarmMessage.class, new ByteArrayInputStream(message.getBytes(StandardCharsets.UTF_8))); + }); } /** diff --git a/bitrepository-core/src/test/java/org/bitrepository/protocol/MessageReceiverManager.java b/bitrepository-core/src/test/java/org/bitrepository/protocol/MessageReceiverManager.java index 72b8a5c55..f60253ade 100644 --- a/bitrepository-core/src/test/java/org/bitrepository/protocol/MessageReceiverManager.java +++ b/bitrepository-core/src/test/java/org/bitrepository/protocol/MessageReceiverManager.java @@ -51,7 +51,9 @@ public void startListeners() { public void stopListeners() { for (MessageReceiver receiver : messageReceivers) { - messageBus.removeListener(receiver.getDestination(), receiver.getMessageListener()); + if (messageBus != null) { + messageBus.removeListener(receiver.getDestination(), receiver.getMessageListener()); + } } } diff --git a/bitrepository-core/src/test/java/org/bitrepository/protocol/bus/ActiveMQMessageBusTest.java b/bitrepository-core/src/test/java/org/bitrepository/protocol/bus/ActiveMQMessageBusTest.java index d5b9bf884..95e072e20 100644 --- a/bitrepository-core/src/test/java/org/bitrepository/protocol/bus/ActiveMQMessageBusTest.java +++ b/bitrepository-core/src/test/java/org/bitrepository/protocol/bus/ActiveMQMessageBusTest.java @@ -8,12 +8,12 @@ * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * + * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . @@ -27,7 +27,8 @@ import org.bitrepository.protocol.ProtocolComponentFactory; import org.bitrepository.protocol.activemq.ActiveMQMessageBus; import org.bitrepository.protocol.message.ExampleMessageFactory; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; import javax.jms.Message; import javax.jms.MessageListener; @@ -36,7 +37,8 @@ import java.util.concurrent.LinkedBlockingDeque; import java.util.concurrent.TimeUnit; -import static org.testng.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; + /** * Runs the GeneralMessageBusTest using a LocalActiveMQBroker (if useEmbeddedMessageBus is true) and a suitable @@ -56,14 +58,15 @@ protected void setupMessageBus() { } - @Test(groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public final void collectionFilterTest() throws Exception { addDescription("Test that message bus filters identify requests to other collection, eg. ignores these."); addStep("Send an identify request with a undefined 'Collection' header property, " + "eg. this identify requests should be handled by everybody.", "Verify that the message bus accepts this message."); String myCollectionID = "MyCollection"; - messageBus.setCollectionFilter(Arrays.asList(new String[]{myCollectionID})); + messageBus.setCollectionFilter(Arrays.asList(myCollectionID)); RawMessagebus rawMessagebus = new RawMessagebus( settingsForTestClient.getMessageBusConfiguration(), securityManager); @@ -90,7 +93,8 @@ public final void collectionFilterTest() throws Exception { collectionReceiver.checkNoMessageIsReceived(IdentifyPillarsForDeleteFileRequest.class); } - @Test(groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public final void sendMessageToSpecificComponentTest() throws Exception { addDescription("Test that message bus correct uses the 'to' header property to indicated that the message " + "is meant for a specific component"); @@ -113,16 +117,17 @@ public void onMessage(Message message) { messageToSend.setTo(receiverID); messageBus.sendMessage(messageToSend); Message receivedMessage = messageList.poll(3, TimeUnit.SECONDS); - assertEquals(receivedMessage.getStringProperty(ActiveMQMessageBus.MESSAGE_TO_KEY), receiverID); + assertEquals(receiverID, receivedMessage.getStringProperty(ActiveMQMessageBus.MESSAGE_TO_KEY)); } - @Test(groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public final void toFilterTest() throws Exception { addDescription("Test that message bus filters identify requests to other components, eg. ignores these."); addStep("Send an identify request with a undefined 'To' header property, " + "eg. this identify requests should be handled by all components.", "Verify that the identify request bus accepts this identify request."); - messageBus.setComponentFilter(Arrays.asList(new String[]{ settingsForTestClient.getComponentID() })); + messageBus.setComponentFilter(Arrays.asList(settingsForTestClient.getComponentID())); RawMessagebus rawMessagebus = new RawMessagebus( settingsForTestClient.getMessageBusConfiguration(), securityManager); diff --git a/bitrepository-core/src/test/java/org/bitrepository/protocol/bus/GeneralMessageBusTest.java b/bitrepository-core/src/test/java/org/bitrepository/protocol/bus/GeneralMessageBusTest.java index 168c014bf..32a1f1a02 100644 --- a/bitrepository-core/src/test/java/org/bitrepository/protocol/bus/GeneralMessageBusTest.java +++ b/bitrepository-core/src/test/java/org/bitrepository/protocol/bus/GeneralMessageBusTest.java @@ -27,12 +27,12 @@ import org.bitrepository.bitrepositorymessages.AlarmMessage; import org.bitrepository.protocol.IntegrationTest; import org.bitrepository.protocol.message.ExampleMessageFactory; -import org.bitrepository.protocol.messagebus.MessageBusManager; import org.jaccept.TestEventManager; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; -import java.util.Arrays; +import java.util.List; /** * Class for testing the interface with the message bus. @@ -47,13 +47,14 @@ protected void registerMessageReceivers() { addReceiver(collectionReceiver); } - @AfterMethod(alwaysRun = true) + @AfterEach public void tearDown() { - messageBus.setComponentFilter(Arrays.asList(new String[]{})); - messageBus.setCollectionFilter(Arrays.asList(new String[]{})); + messageBus.setComponentFilter(List.of()); + messageBus.setCollectionFilter(List.of()); } - @Test(groups = { "regressiontest" }) + @Test + @Tag("regressiontest" ) public final void busActivityTest() throws Exception { addDescription("Tests whether it is possible to create a message listener, " + "and then set it to listen to the topic. Then puts a message" + @@ -70,7 +71,8 @@ public final void busActivityTest() throws Exception { alarmReceiver.waitForMessage(message.getClass()); } - @Test(groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public final void twoListenersForTopicTest() throws Exception { addDescription("Verifies that two listeners on the same topic both receive the message"); TestEventManager testEventManager = TestEventManager.getInstance(); @@ -94,7 +96,8 @@ public final void twoListenersForTopicTest() throws Exception { receiver2.waitForMessage(AlarmMessage.class); } - @Test(groups = { "specificationonly" }) + @Test + @Tag("specificationonly" ) public final void messageBusFailoverTest() { addDescription("Verifies that we can switch to at second message bus " + "in the middle of a conversation, if the connection is lost. " + @@ -102,7 +105,8 @@ public final void messageBusFailoverTest() { "message bus"); } - @Test(groups = { "specificationonly" }) + @Test + @Tag("specificationonly" ) public final void messageBusReconnectTest() { addDescription("Test whether we are able to reconnect to the message " + "bus if the connection is lost"); diff --git a/bitrepository-core/src/test/java/org/bitrepository/protocol/bus/LocalActiveMQBroker.java b/bitrepository-core/src/test/java/org/bitrepository/protocol/bus/LocalActiveMQBroker.java index 124499168..0648f9aba 100644 --- a/bitrepository-core/src/test/java/org/bitrepository/protocol/bus/LocalActiveMQBroker.java +++ b/bitrepository-core/src/test/java/org/bitrepository/protocol/bus/LocalActiveMQBroker.java @@ -32,7 +32,7 @@ public class LocalActiveMQBroker { private final Logger log = LoggerFactory.getLogger(getClass()); - private BrokerService broker; + private final BrokerService broker; public LocalActiveMQBroker(MessageBusConfiguration configuration) { broker = new BrokerService(); diff --git a/bitrepository-core/src/test/java/org/bitrepository/protocol/bus/MessageReceiver.java b/bitrepository-core/src/test/java/org/bitrepository/protocol/bus/MessageReceiver.java index b2690167e..530e29914 100644 --- a/bitrepository-core/src/test/java/org/bitrepository/protocol/bus/MessageReceiver.java +++ b/bitrepository-core/src/test/java/org/bitrepository/protocol/bus/MessageReceiver.java @@ -28,9 +28,9 @@ import org.bitrepository.protocol.MessageContext; import org.bitrepository.protocol.messagebus.MessageListener; import org.jaccept.TestEventManager; +import org.junit.jupiter.api.Assertions; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.testng.Assert; import javax.jms.ExceptionListener; import javax.jms.JMSException; @@ -119,7 +119,7 @@ public T waitForMessage(Class messageType, long timeout, TimeUnit unit) { log.debug("Read message after ({} ms): {}", waitTime, message); } else { log.info("Wait for {} message timed out ({} ms).", messageType.getSimpleName(), waitTime); - Assert.fail("Wait for " + messageType.getSimpleName() + " message timed out (" + waitTime + " ms)."); + Assertions.fail("Wait for " + messageType.getSimpleName() + " message timed out (" + waitTime + " ms)."); } return message; } @@ -136,7 +136,7 @@ public void checkNoMessageIsReceived(Class messageType) { throw new RuntimeException(e); // Should never happen } if (message != null) { - Assert.fail("Received unexpected message " + message); + Assertions.fail("Received unexpected message " + message); } } @@ -171,7 +171,7 @@ public void clearMessages() { } private class MessageModel { - private Map, BlockingQueue> messageMap = new HashMap<>(); + private final Map, BlockingQueue> messageMap = new HashMap<>(); private Collection pillarFilter; private void addMessage(T message) { diff --git a/bitrepository-core/src/test/java/org/bitrepository/protocol/bus/MultiThreadedMessageBusTest.java b/bitrepository-core/src/test/java/org/bitrepository/protocol/bus/MultiThreadedMessageBusTest.java index e731ab923..05b41789b 100644 --- a/bitrepository-core/src/test/java/org/bitrepository/protocol/bus/MultiThreadedMessageBusTest.java +++ b/bitrepository-core/src/test/java/org/bitrepository/protocol/bus/MultiThreadedMessageBusTest.java @@ -1,23 +1,23 @@ /* * #%L * Bitmagasin integrationstest - * + * * $Id$ * $HeadURL$ * %% * Copyright (C) 2010 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% @@ -31,9 +31,10 @@ import org.bitrepository.protocol.ProtocolComponentFactory; import org.bitrepository.protocol.message.ExampleMessageFactory; import org.bitrepository.protocol.messagebus.MessageListener; -import org.testng.Assert; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; @@ -43,15 +44,17 @@ * Class for testing the interface with the message bus. */ public class MultiThreadedMessageBusTest extends IntegrationTest { - /** The time to wait when sending a message before it definitely should - * have been consumed by a listener.*/ + /** + * The time to wait when sending a message before it definitely should + * have been consumed by a listener. + */ static final int TIME_FOR_WAIT = 2500; private final static int threadCount = 3; private int count = 0; private final static String FINISH = "FINISH"; - private BlockingQueue finishQueue = new LinkedBlockingQueue<>(1); + private final BlockingQueue finishQueue = new LinkedBlockingQueue<>(1); MultiMessageListener listener; - + @Override protected void setupMessageBus() { if (useEmbeddedMessageBus() && broker == null) { @@ -62,8 +65,9 @@ protected void setupMessageBus() { settingsForTestClient, securityManager), testEventManager); } - - @Test(groups = { "regressiontest" }) + + @Test + @Tag("regressiontest") public final void manyTheadsBeforeFinish() throws Exception { addDescription("Tests whether it is possible to start the handling of many threads simultaneously."); IdentifyPillarsForGetFileRequest content = @@ -71,37 +75,37 @@ public final void manyTheadsBeforeFinish() throws Exception { listener = new MultiMessageListener(); messageBus.addListener("BusActivityTest", listener); content.setDestination("BusActivityTest"); - + addStep("Send one message for each listener", "When all have receiver, then they give respond on 'finishQueue'"); - for(int i = 0; i < threadCount; i++) { + for (int i = 0; i < threadCount; i++) { messageBus.sendMessage(content); } - Assert.assertEquals(finishQueue.poll(TIME_FOR_WAIT, TimeUnit.MILLISECONDS), FINISH); - Assert.assertEquals(count, threadCount); + Assertions.assertEquals(FINISH, finishQueue.poll(TIME_FOR_WAIT, TimeUnit.MILLISECONDS)); + Assertions.assertEquals(threadCount, count); } - @AfterMethod(alwaysRun = true) + @AfterEach public void removeListener() { messageBus.removeListener("BusActivityTest", listener); } protected class MultiMessageListener implements MessageListener { - private BlockingQueue queue = new LinkedBlockingQueue<>(threadCount); - + private final BlockingQueue queue = new LinkedBlockingQueue<>(threadCount); + @Override public final void onMessage(Message message, MessageContext messageContext) { try { testIfFinished(); - Assert.assertNotNull(queue.poll(TIME_FOR_WAIT, TimeUnit.MILLISECONDS)); + Assertions.assertNotNull(queue.poll(TIME_FOR_WAIT, TimeUnit.MILLISECONDS)); } catch (InterruptedException e) { - Assert.fail("Should not throw an exception: ", e); + Assertions.fail("Should not throw an exception: ", e); } } - + private void testIfFinished() throws InterruptedException { count++; - if(count >= threadCount) { - for(int i = 0; i < threadCount; i++) { + if (count >= threadCount) { + for (int i = 0; i < threadCount; i++) { queue.put("Count '" + i + "'"); } finishQueue.put(FINISH); diff --git a/bitrepository-core/src/test/java/org/bitrepository/protocol/fileexchange/LocalFileExchangeTest.java b/bitrepository-core/src/test/java/org/bitrepository/protocol/fileexchange/LocalFileExchangeTest.java index 2e3b1ae1d..4275a4804 100644 --- a/bitrepository-core/src/test/java/org/bitrepository/protocol/fileexchange/LocalFileExchangeTest.java +++ b/bitrepository-core/src/test/java/org/bitrepository/protocol/fileexchange/LocalFileExchangeTest.java @@ -6,9 +6,11 @@ import org.bitrepository.settings.referencesettings.FileExchangeSettings; import org.fusesource.hawtbuf.ByteArrayInputStream; import org.jaccept.structure.ExtendedTestCase; -import org.testng.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; import java.io.ByteArrayOutputStream; import java.io.File; @@ -24,11 +26,12 @@ import java.nio.file.Files; import java.nio.file.Paths; -public class LocalFileExchangeTest extends ExtendedTestCase { +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +public class LocalFileExchangeTest extends ExtendedTestCase { final static String BASE_FILE_EXCHANGE_DIR = "target/fileexchange/"; private FileExchange exchange; - @BeforeClass(alwaysRun = true) + @BeforeAll public void setup() throws IOException { createFileExchangeDir(); FileExchangeSettings settings = new FileExchangeSettings(); @@ -44,17 +47,18 @@ private void createFileExchangeDir() throws IOException { } } - @Test(groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public void getUrlTest() throws MalformedURLException { String testFile = "getUrlTestfile"; - + File basedir = new File(BASE_FILE_EXCHANGE_DIR); URL expectedUrl = new URL("file:" + basedir.getAbsolutePath() + "/" + testFile); - + URL actualUrl = exchange.getURL(testFile); - Assert.assertEquals(actualUrl, expectedUrl); + Assertions.assertEquals(actualUrl, expectedUrl); File actualFile = new File(actualUrl.getFile()); - Assert.assertFalse(actualFile.exists()); + Assertions.assertFalse(actualFile.exists()); } /** @@ -74,78 +78,78 @@ public void putFileByFileContainingHashTest() throws Exception { StandardCharsets.UTF_8)); URL fileExchangeUrl = exchange.putFile(testFile); - Assert.assertEquals(fileExchangeUrl, expectedUrl); + Assertions.assertEquals(fileExchangeUrl, expectedUrl); File actualFile = new File(fileExchangeUrl.toURI()); - Assert.assertTrue(actualFile.exists()); + Assertions.assertTrue(actualFile.exists()); String fileExchangeContent = readTestFileContent(actualFile); - Assert.assertEquals(fileExchangeContent, testFileContent); + Assertions.assertEquals(testFileContent, fileExchangeContent); actualFile.delete(); } - + @Test public void putFileByFileTest() throws IOException { String testFileName = "putFileByFileTestFile"; String testFileLocation = "target/" + testFileName; String testFileContent = "lorem ipsum1"; File testFile = createTestFile(testFileLocation, testFileContent); - + File basedir = new File(BASE_FILE_EXCHANGE_DIR); URL expectedUrl = new URL("file:" + basedir.getAbsolutePath() + "/" + testFileName); - + URL fileExchangeUrl = exchange.putFile(testFile); - Assert.assertEquals(fileExchangeUrl, expectedUrl); - + Assertions.assertEquals(fileExchangeUrl, expectedUrl); + File actualFile = new File(fileExchangeUrl.getFile()); - Assert.assertTrue(actualFile.exists()); + Assertions.assertTrue(actualFile.exists()); String fileExchangeContent = readTestFileContent(actualFile); - Assert.assertEquals(fileExchangeContent, testFileContent); + Assertions.assertEquals(testFileContent, fileExchangeContent); actualFile.delete(); } - + @Test public void putFileByStreamTest() throws IOException { String testFileName = "putFileByStreamTestFile"; String testFileContent = "lorem ipsum2"; - + InputStream is = new ByteArrayInputStream(testFileContent.getBytes(StandardCharsets.UTF_8)); URL fileExchangeUrl = exchange.getURL(testFileName); exchange.putFile(is, fileExchangeUrl); - + File fileExchangeFile = new File(fileExchangeUrl.getFile()); String fileExchangeContent = readTestFileContent(fileExchangeFile); - Assert.assertEquals(fileExchangeContent, testFileContent); + Assertions.assertEquals(testFileContent, fileExchangeContent); fileExchangeFile.delete(); } - + @Test public void getFileByInputStreamTest() throws IOException { String testFileName = "getFileByInputStreamTestFile"; String testFileContent = "lorem ipsum3"; String testFileLocation = "target/" + testFileName; - + File testFile = createTestFile(testFileLocation, testFileContent); URL testFileUrl = testFile.toURI().toURL(); - + InputStream is = exchange.getFile(testFileUrl); String fileContent = IOUtils.toString(is, StandardCharsets.UTF_8); - Assert.assertEquals(fileContent, testFileContent); + Assertions.assertEquals(testFileContent, fileContent); } - + @Test public void getFileByOutputStreamTest() throws IOException { String testFileName = "getFileByOutputStreamTestFile"; String testFileContent = "lorem ipsum4"; String testFileLocation = "target/" + testFileName; - + File testFile = createTestFile(testFileLocation, testFileContent); URL testFileUrl = testFile.toURI().toURL(); - + OutputStream os = new ByteArrayOutputStream(); - + exchange.getFile(os, testFileUrl); - Assert.assertEquals(os.toString(), testFileContent); + Assertions.assertEquals(testFileContent, os.toString()); } - + @Test public void getFileByAddressTest() throws IOException { String testFileName = "getFileByAddressTestFile"; @@ -154,39 +158,39 @@ public void getFileByAddressTest() throws IOException { File testFile = createTestFile(testFileLocation, testFileContent); URL testFileUrl = testFile.toURI().toURL(); - + File destination = new File("target/getFileByAddressTestOutputFile"); destination.deleteOnExit(); - + exchange.getFile(destination, testFileUrl.toString()); String destinationContent = readTestFileContent(destination); - Assert.assertEquals(destinationContent, testFileContent); + Assertions.assertEquals(testFileContent, destinationContent); } @Test public void deleteFileTest() throws IOException, URISyntaxException { String testFileName = "putFileByStreamTestFile"; String testFileContent = "lorem ipsum6"; - + InputStream is = new ByteArrayInputStream(testFileContent.getBytes(StandardCharsets.UTF_8)); URL fileExchangeUrl = exchange.getURL(testFileName); exchange.putFile(is, fileExchangeUrl); - + File fileExchangeFile = new File(fileExchangeUrl.getFile()); - Assert.assertTrue(fileExchangeFile.exists()); + Assertions.assertTrue(fileExchangeFile.exists()); exchange.deleteFile(fileExchangeUrl); - Assert.assertFalse(fileExchangeFile.exists()); + Assertions.assertFalse(fileExchangeFile.exists()); } - + private File createTestFile(String filename, String content) throws IOException { Files.write(Paths.get(filename), content.getBytes(StandardCharsets.UTF_8)); File f = Paths.get(filename).toFile(); f.deleteOnExit(); return f; } - + private String readTestFileContent(File testFile) throws IOException { return Files.readString(Paths.get(testFile.toURI())); } - + } diff --git a/bitrepository-core/src/test/java/org/bitrepository/protocol/fileexchange/TestFileStore.java b/bitrepository-core/src/test/java/org/bitrepository/protocol/fileexchange/TestFileStore.java index 2955814f9..7a48018e8 100644 --- a/bitrepository-core/src/test/java/org/bitrepository/protocol/fileexchange/TestFileStore.java +++ b/bitrepository-core/src/test/java/org/bitrepository/protocol/fileexchange/TestFileStore.java @@ -37,6 +37,7 @@ import java.io.InputStream; import java.util.ArrayList; import java.util.Collection; +import java.util.Collections; import java.util.List; /** @@ -112,7 +113,6 @@ public FileInfo downloadFileForValidation(String fileID, String collectionID, In @Override public void moveToArchive(String fileID, String collectionID) { // This does nothing. - return; } @Override @@ -129,9 +129,7 @@ public FileInfo getFileInfo(String fileID, String collectionID) { public Collection getAllFileIds(String collectionID) { String[] ids = new File(storageDir).list(); List res = new ArrayList<>(); - for(String id : ids) { - res.add(id); - } + Collections.addAll(res, ids); return res; } diff --git a/bitrepository-core/src/test/java/org/bitrepository/protocol/http/HttpFileExchangeTest.java b/bitrepository-core/src/test/java/org/bitrepository/protocol/http/HttpFileExchangeTest.java index 736e463ff..ecc0bc3e2 100644 --- a/bitrepository-core/src/test/java/org/bitrepository/protocol/http/HttpFileExchangeTest.java +++ b/bitrepository-core/src/test/java/org/bitrepository/protocol/http/HttpFileExchangeTest.java @@ -26,16 +26,19 @@ import org.bitrepository.settings.referencesettings.FileExchangeSettings; import org.bitrepository.settings.referencesettings.ProtocolType; import org.jaccept.structure.ExtendedTestCase; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; import java.math.BigInteger; import java.net.MalformedURLException; import java.net.URL; -import static org.testng.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; + public class HttpFileExchangeTest extends ExtendedTestCase { - @Test(groups = { "regressiontest" }) + @Test + @Tag("regressiontest" ) public void checkUrlEncodingOfFilenamesTest() throws MalformedURLException { addDescription("Tests that the filename is url-encoded correctly for a configured webdav server"); Settings mySettings = TestSettingsProvider.reloadSettings("uploadTest"); diff --git a/bitrepository-core/src/test/java/org/bitrepository/protocol/messagebus/ReceivedMessageHandlerTest.java b/bitrepository-core/src/test/java/org/bitrepository/protocol/messagebus/ReceivedMessageHandlerTest.java index 9aa28b5a0..29f0f8fd9 100644 --- a/bitrepository-core/src/test/java/org/bitrepository/protocol/messagebus/ReceivedMessageHandlerTest.java +++ b/bitrepository-core/src/test/java/org/bitrepository/protocol/messagebus/ReceivedMessageHandlerTest.java @@ -29,7 +29,8 @@ import org.bitrepository.settings.referencesettings.MessageThreadPool; import org.bitrepository.settings.referencesettings.MessageThreadPools; import org.jaccept.structure.ExtendedTestCase; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; import java.math.BigInteger; import java.util.Arrays; @@ -41,7 +42,8 @@ public class ReceivedMessageHandlerTest extends ExtendedTestCase { - @Test(groups = { "regressiontest" }) + @Test + @Tag("regressiontest" ) public void singleMessageDispatch() { addDescription("Tests that a single message is dispatched correctly"); ReceivedMessageHandler handler = new ReceivedMessageHandler(null); @@ -52,7 +54,8 @@ public void singleMessageDispatch() { verify(defaultListener, timeout(100)).onMessage(testMessage, testMessageContext); } - @Test(groups = { "regressiontest" }) + @Test + @Tag("regressiontest") public void parallelMessageDispatch() { addDescription("Tests that two messages can be handled in parallel in the default pool configuration."); addFixture("Create a ReceivedMessageHandler with a null configuration. This should create a " + @@ -76,7 +79,8 @@ public void parallelMessageDispatch() { verifyNoMoreInteractions(secondListener); } - @Test(groups = { "regressiontest" }) + @Test + @Tag("regressiontest" ) public void manyMessageDispatch() { addDescription("Tests that many (50) messages can be handled in parallel in the default pool configuration."); addFixture("Create a ReceivedMessageHandler with a null configuration. This should create a " + @@ -104,7 +108,8 @@ public void manyMessageDispatch() { verifyNoMoreInteractions(lastListener); } - @Test(groups = { "regressiontest" }) + @Test + @Tag("regressiontest") public void singleThreadMessageDispatch() { addDescription("Tests that two messages will be handled in sequence if a singleThreaded pool is configured."); addFixture("Create a ReceivedMessageHandler with a single pool of size 1."); @@ -125,7 +130,8 @@ public void singleThreadMessageDispatch() { verify(secondListener, timeout(100)).onMessage(testMessage, null); } - @Test(groups = { "regressiontest" }) + @Test + @Tag("regressiontest") public void specificMessagePools() { addDescription("Tests that different message types can be handled by different executors."); addFixture("Create a ReceivedMessageHandler with a two pools, one for status requests and one for put requests. " + @@ -159,7 +165,8 @@ public void specificMessagePools() { verifyNoMoreInteractions(thirdStatusListener); } - @Test(groups = { "regressiontest" }) + @Test + @Tag("regressiontest") public void specificMessageNamePoolAndDefaultPool() { addDescription("Tests it is possible to specify a pool for a specific message type, with a " + "default pool for the remainder."); @@ -192,7 +199,8 @@ public void specificMessageNamePoolAndDefaultPool() { verifyNoMoreInteractions(thirdStatusListener); } - @Test(groups = { "regressiontest" }) + @Test + @Tag("regressiontest" ) public void specificMessageCategoryPoolAndDefaultPool() { addDescription("Tests it is possible to specify a pool for a specific message category, with a " + "default pool for the remainder."); @@ -224,7 +232,8 @@ public void specificMessageCategoryPoolAndDefaultPool() { verifyNoMoreInteractions(thirdStatusListener); } - @Test(groups = { "regressiontest" }) + @Test + @Tag("regressiontest") public void specificCollectionPoolAndDefaultPool() { addDescription("Tests it is possible to specify a pool for a specific collection, with a " + "default pool for the remainder."); @@ -264,7 +273,8 @@ public void specificCollectionPoolAndDefaultPool() { verify(secondCollection1Listener, timeout(100)).onMessage(collection1Message, null); } - @Test(groups = { "regressiontest" }) + @Test + @Tag("regressiontest") public void specificCollectionPoolWithSpecificMessageTypePool() { addDescription("Tests it is possible to specify a pool for a specific collection for only a specific" + "message type."); diff --git a/bitrepository-core/src/test/java/org/bitrepository/protocol/performancetest/MessageBusDelayTest.java b/bitrepository-core/src/test/java/org/bitrepository/protocol/performancetest/MessageBusDelayTest.java index 710914fbd..d4d9f1b57 100644 --- a/bitrepository-core/src/test/java/org/bitrepository/protocol/performancetest/MessageBusDelayTest.java +++ b/bitrepository-core/src/test/java/org/bitrepository/protocol/performancetest/MessageBusDelayTest.java @@ -32,8 +32,10 @@ import org.bitrepository.protocol.security.SecurityManager; import org.jaccept.TestEventManager; import org.jaccept.structure.ExtendedTestCase; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; import java.io.FileOutputStream; import java.nio.charset.StandardCharsets; @@ -43,6 +45,7 @@ import java.util.List; import java.util.concurrent.TimeUnit; +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class MessageBusDelayTest extends ExtendedTestCase { private Settings settings; private SecurityManager securityManager; @@ -51,17 +54,20 @@ public class MessageBusDelayTest extends ExtendedTestCase { private static final int NUMBER_OF_TESTS = 100; private static final boolean WRITE_RESULTS_TO_DISC = true; - @BeforeClass(alwaysRun = true) + @BeforeAll public void setup() { settings = TestSettingsProvider.reloadSettings(getClass().getSimpleName()); securityManager = new DummySecurityManager(); } - @Test(groups = {"StressTest"}) + @Test + @Tag("StressTest") +// @Disabled public void testManyTimes() { for (int i = 0; i < NUMBER_OF_TESTS; i++) { try { performStatisticalAnalysisOfMessageDelay(); + System.out.println("Test " + i + " done."); } catch (Exception e) { System.err.println("Unknown exception caught: " + e); } diff --git a/bitrepository-core/src/test/java/org/bitrepository/protocol/performancetest/MessageBusNumberOfListenersStressTest.java b/bitrepository-core/src/test/java/org/bitrepository/protocol/performancetest/MessageBusNumberOfListenersStressTest.java index 066c4eb50..871f35b2d 100644 --- a/bitrepository-core/src/test/java/org/bitrepository/protocol/performancetest/MessageBusNumberOfListenersStressTest.java +++ b/bitrepository-core/src/test/java/org/bitrepository/protocol/performancetest/MessageBusNumberOfListenersStressTest.java @@ -39,9 +39,10 @@ import org.bitrepository.protocol.security.SecurityManager; import org.bitrepository.settings.repositorysettings.MessageBusConfiguration; import org.jaccept.structure.ExtendedTestCase; -import org.testng.Assert; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; import java.io.File; import java.io.FileOutputStream; @@ -110,7 +111,7 @@ public class MessageBusNumberOfListenersStressTest extends ExtendedTestCase { private static boolean sendMoreMessages = true; private Settings settings; - @BeforeMethod + @BeforeEach public void initializeSettings() { settings = TestSettingsProvider.getSettings(getClass().getSimpleName()); } @@ -121,7 +122,8 @@ public void initializeSettings() { * * @throws Exception Can possibly throw an exception. */ - @Test(groups = {"StressTest"}) + @Test + @Tag("StressTest") public void testManyListenersOnLocalMessageBus() throws Exception { addDescription("Tests how many messages can be handled within a given timeframe when a given number of " + "listeners are receiving them."); @@ -155,7 +157,8 @@ public void testManyListenersOnLocalMessageBus() throws Exception { } } - @Test(groups = {"StressTest"}) + @Test + @Tag("StressTest") public void testManyListenersOnDistributedMessageBus() throws Exception { addDescription("Tests how many messages can be handled within a given timeframe when a given number of " + "listeners are receiving them."); @@ -228,12 +231,12 @@ public void testListeners(MessageBusConfiguration conf, SecurityManager security addStep("Verifying the amount of message sent '" + idReached + "' has been received by all '" + NUMBER_OF_LISTENERS + "' listeners", "Should be the same amount for each listener, and the same " + "amount as the correlation ID of the message"); - Assert.assertEquals(messageReceived, idReached * NUMBER_OF_LISTENERS, + Assertions.assertEquals(messageReceived, idReached * NUMBER_OF_LISTENERS, "Reached message Id " + idReached + " thus each message of the " + NUMBER_OF_LISTENERS + " listener " + "should have received " + idReached + " message, though they have received " + messageReceived + " message all together."); for (NotificationMessageListener listener : listeners) { - Assert.assertTrue((listener.getCount() == idReached), + Assertions.assertTrue((listener.getCount() == idReached), "Should have received " + idReached + " messages, but has received " + listener.getCount()); } @@ -242,7 +245,7 @@ public void testListeners(MessageBusConfiguration conf, SecurityManager security // the console output (due to shutdown 'warnings'). Thus write the results in a file. if (WRITE_RESULTS_TO_FILE) { FileOutputStream out = new FileOutputStream(new File(OUTPUT_FILE_NAME), true); - out.write(new String("idReached: " + idReached + ", NumberOfListeners: " + NUMBER_OF_LISTENERS + out.write(("idReached: " + idReached + ", NumberOfListeners: " + NUMBER_OF_LISTENERS + ", messagesReceived: " + messageReceived + " on bus " + conf.getURL() + "\n").getBytes()); out.flush(); diff --git a/bitrepository-core/src/test/java/org/bitrepository/protocol/performancetest/MessageBusNumberOfMessagesStressTest.java b/bitrepository-core/src/test/java/org/bitrepository/protocol/performancetest/MessageBusNumberOfMessagesStressTest.java index 3c6742ec0..e41ba24ac 100644 --- a/bitrepository-core/src/test/java/org/bitrepository/protocol/performancetest/MessageBusNumberOfMessagesStressTest.java +++ b/bitrepository-core/src/test/java/org/bitrepository/protocol/performancetest/MessageBusNumberOfMessagesStressTest.java @@ -1,23 +1,23 @@ /* * #%L * Bitmagasin integrationstest - * + * * $Id$ * $HeadURL$ * %% * Copyright (C) 2010 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% @@ -38,21 +38,25 @@ import org.bitrepository.protocol.security.DummySecurityManager; import org.bitrepository.protocol.security.SecurityManager; import org.jaccept.structure.ExtendedTestCase; -import org.testng.Assert; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; import java.util.Date; /** - * Stress testing of the messagebus. + * Stress testing of the messagebus. */ public class MessageBusNumberOfMessagesStressTest extends ExtendedTestCase { - /** The name of the queue to send the messages.*/ + /** + * The name of the queue to send the messages. + */ private static String QUEUE = "TEST-QUEUE"; private Settings settings; - @BeforeMethod + @BeforeEach public void initializeSettings() { settings = TestSettingsProvider.getSettings(getClass().getSimpleName()); } @@ -61,7 +65,8 @@ public void initializeSettings() { * Tests the amount of messages sent over a message bus, which is not placed locally. * Require sending at least five messages per second. */ - @Test( groups = {"StressTest"} ) + @Test + @Tag("StressTest") public void SendManyMessagesDistributed() throws Exception { addDescription("Tests how many messages can be handled within a given timeframe."); addStep("Define constants", "This should not be possible to fail."); @@ -86,15 +91,15 @@ public void SendManyMessagesDistributed() throws Exception { } } - addStep("Stopped sending at '" + new Date() + "'", "Should have send more than '" + messagePerSec + addStep("Stopped sending at '" + new Date() + "'", "Should have send more than '" + messagePerSec + "' messages per sec."); int count = listener.getCount(); - Assert.assertTrue(count > (messagePerSec * timeFrame/1000), "There where send '" + count - + "' messages in '" + timeFrame/1000 + "' seconds, but it is required to handle at least '" + Assertions.assertTrue(count > (messagePerSec * timeFrame / 1000), "There where send '" + count + + "' messages in '" + timeFrame / 1000 + "' seconds, but it is required to handle at least '" + messagePerSec + "' per second!"); - System.out.println("Sent '" + count + "' messages in '" + timeFrame/1000 + "' seconds."); + System.out.println("Sent '" + count + "' messages in '" + timeFrame / 1000 + "' seconds."); } finally { - if(listener != null) { + if (listener != null) { listener.stop(); listener = null; } @@ -102,10 +107,12 @@ public void SendManyMessagesDistributed() throws Exception { } /** - * Tests the amount of messages send through a local messagebus. - * It should be at least 20 per second. + * Tests the amount of messages send through a local messagebus. + * It should be at least 20 per second. */ - @Test( groups = {"StressTest"} ) + @Test + @Tag("StressTest") + @Disabled public void SendManyMessagesLocally() throws Exception { addDescription("Tests how many messages can be handled within a given timeframe."); addStep("Define constants", "This should not be possible to fail."); @@ -118,7 +125,7 @@ public void SendManyMessagesLocally() throws Exception { MessageBusConfigurationFactory.createEmbeddedMessageBusConfiguration() ); LocalActiveMQBroker broker = new LocalActiveMQBroker(settings.getMessageBusConfiguration()); - Assert.assertNotNull(broker); + Assertions.assertNotNull(broker); ResendMessageListener listener = null; @@ -139,15 +146,15 @@ public void SendManyMessagesLocally() throws Exception { } } - addStep("Stopped sending at '" + new Date() + "'", "Should have send more than '" + messagePerSec + addStep("Stopped sending at '" + new Date() + "'", "Should have send more than '" + messagePerSec + "' messages per sec."); int count = listener.getCount(); - Assert.assertTrue(count > (messagePerSec * timeFrame/1000), "There where send '" + count - + "' messages in '" + timeFrame/1000 + "' seconds, but it is required to handle at least '" + Assertions.assertTrue(count > (messagePerSec * timeFrame / 1000), "There where send '" + count + + "' messages in '" + timeFrame / 1000 + "' seconds, but it is required to handle at least '" + messagePerSec + "' per second!"); - System.out.println("Sent '" + count + "' messages in '" + timeFrame/1000 + "' seconds."); + System.out.println("Sent '" + count + "' messages in '" + timeFrame / 1000 + "' seconds."); } finally { - if(listener != null) { + if (listener != null) { listener.stop(); } broker.stop(); @@ -160,13 +167,18 @@ public void SendManyMessagesLocally() throws Exception { * It keeps track of the amount of messages received. */ private static class ResendMessageListener implements MessageListener { - /** The message bus.*/ + /** + * The message bus. + */ private final MessageBus bus; - /** The amount of messages received.*/ + /** + * The amount of messages received. + */ private int count; /** * Constructor. + * * @param conf The configurations for declaring the message bus. */ public ResendMessageListener(Settings conf) { @@ -187,6 +199,7 @@ public void stop() { /** * Retrieval of the amount of messages caught by the listener. + * * @return The number of message received by this. */ public int getCount() { @@ -195,6 +208,7 @@ public int getCount() { /** * Starts sending messages. + * * @throws Exception If a problem with creating the message occurs. */ public void startSending() throws Exception { diff --git a/bitrepository-core/src/test/java/org/bitrepository/protocol/performancetest/MessageBusSizeOfMessageStressTest.java b/bitrepository-core/src/test/java/org/bitrepository/protocol/performancetest/MessageBusSizeOfMessageStressTest.java index 68be6421c..0de233945 100644 --- a/bitrepository-core/src/test/java/org/bitrepository/protocol/performancetest/MessageBusSizeOfMessageStressTest.java +++ b/bitrepository-core/src/test/java/org/bitrepository/protocol/performancetest/MessageBusSizeOfMessageStressTest.java @@ -42,9 +42,10 @@ import org.bitrepository.protocol.security.SecurityManager; import org.bitrepository.settings.repositorysettings.MessageBusConfiguration; import org.jaccept.structure.ExtendedTestCase; -import org.testng.Assert; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; import java.util.Date; @@ -59,7 +60,7 @@ public class MessageBusSizeOfMessageStressTest extends ExtendedTestCase { private final long TIME_FRAME = 60000L; private Settings settings; - @BeforeMethod + @BeforeEach public void initializeSettings() { settings = TestSettingsProvider.getSettings(getClass().getSimpleName()); } @@ -68,7 +69,8 @@ public void initializeSettings() { * Tests the amount of messages sent over a message bus, which is not placed locally. * Requires sending at least five per second. */ - /* @Test( groups = {"StressTest"} ) */ + /* @Test + @Tag("StressTest"} ) */ public void SendLargeMessagesDistributed() throws Exception { addDescription("Tests how many messages can be handled within a given timeframe."); addStep("Define constants", "This should not be possible to fail."); @@ -96,7 +98,7 @@ public void SendLargeMessagesDistributed() throws Exception { addStep("Validating messages have been sent.", "Should be OK"); int count = listener.getCount(); - Assert.assertTrue(count > 0, "Some message should have been sent."); + Assertions.assertTrue(count > 0, "Some message should have been sent."); System.out.println("Sent '" + count + "' messages in '" + TIME_FRAME / 1000 + "' seconds."); } finally { if (listener != null) { @@ -109,7 +111,8 @@ public void SendLargeMessagesDistributed() throws Exception { * Tests the amount of messages sent through a local messagebus. * It should be at least 20 per second. */ - @Test(groups = {"StressTest"}) + @Test + @Tag("StressTest") public void SendLargeMessagesLocally() throws Exception { addDescription("Tests how many messages can be handled within a given timeframe."); addStep("Define constants", "This should not be possible to fail."); @@ -117,9 +120,9 @@ public void SendLargeMessagesLocally() throws Exception { addStep("Make configuration for the messagebus and define the local broker.", "Both should be created."); MessageBusConfiguration conf = MessageBusConfigurationFactory.createEmbeddedMessageBusConfiguration(); - Assert.assertNotNull(conf); + Assertions.assertNotNull(conf); LocalActiveMQBroker broker = new LocalActiveMQBroker(conf); - Assert.assertNotNull(broker); + Assertions.assertNotNull(broker); ResendMessageListener listener = null; diff --git a/bitrepository-core/src/test/java/org/bitrepository/protocol/performancetest/MessageBusTimeToSendMessagesStressTest.java b/bitrepository-core/src/test/java/org/bitrepository/protocol/performancetest/MessageBusTimeToSendMessagesStressTest.java index f5827a9c4..1e11100c6 100644 --- a/bitrepository-core/src/test/java/org/bitrepository/protocol/performancetest/MessageBusTimeToSendMessagesStressTest.java +++ b/bitrepository-core/src/test/java/org/bitrepository/protocol/performancetest/MessageBusTimeToSendMessagesStressTest.java @@ -39,9 +39,10 @@ import org.bitrepository.protocol.security.SecurityManager; import org.bitrepository.settings.repositorysettings.MessageBusConfiguration; import org.jaccept.structure.ExtendedTestCase; -import org.testng.Assert; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; import java.util.Date; @@ -60,7 +61,7 @@ public class MessageBusTimeToSendMessagesStressTest extends ExtendedTestCase { private static Date startSending; private Settings settings; - @BeforeMethod + @BeforeEach public void initializeSettings() { settings = TestSettingsProvider.getSettings(getClass().getSimpleName()); } @@ -68,7 +69,8 @@ public void initializeSettings() { * Tests the amount of messages sent over a message bus, which is not placed locally. * Require sending at least five per second. */ - /* @Test( groups = {"StressTest"} ) */ + /* @Test + @Tag("StressTest"} ) */ public void SendManyMessagesDistributed() { addDescription("Tests how fast a given number of messages can be handled."); addStep("Define constants", "This should not be possible to fail."); @@ -116,7 +118,8 @@ public void SendManyMessagesDistributed() { * Tests the amount of messages sent through a local messagebus. * It should be at least 20 per second. */ - @Test( groups = {"StressTest"} ) + @Test + @Tag("StressTest") public void SendManyMessagesLocally() throws Exception { addDescription("Tests how many messages can be handled within a given timeframe."); addStep("Define constants", "This should not be possible to fail."); @@ -124,9 +127,9 @@ public void SendManyMessagesLocally() throws Exception { addStep("Make configuration for the messagebus and define the local broker.", "Both should be created."); MessageBusConfiguration conf = MessageBusConfigurationFactory.createEmbeddedMessageBusConfiguration(); - Assert.assertNotNull(conf); + Assertions.assertNotNull(conf); LocalActiveMQBroker broker = new LocalActiveMQBroker(conf); - Assert.assertNotNull(broker); + Assertions.assertNotNull(broker); CountMessagesListener listener = null; SecurityManager securityManager = new DummySecurityManager(); diff --git a/bitrepository-core/src/test/java/org/bitrepository/protocol/security/CertificateIDTest.java b/bitrepository-core/src/test/java/org/bitrepository/protocol/security/CertificateIDTest.java index 9cdb8b02d..143e33699 100644 --- a/bitrepository-core/src/test/java/org/bitrepository/protocol/security/CertificateIDTest.java +++ b/bitrepository-core/src/test/java/org/bitrepository/protocol/security/CertificateIDTest.java @@ -27,20 +27,20 @@ import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.bouncycastle.util.encoders.Base64; import org.jaccept.structure.ExtendedTestCase; -import org.testng.Assert; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; import javax.security.auth.x500.X500Principal; -import java.io.ByteArrayInputStream; import java.math.BigInteger; import java.nio.charset.StandardCharsets; import java.security.Security; -import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; public class CertificateIDTest extends ExtendedTestCase { - @Test(groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public void positiveCertificateIdentificationTest() throws Exception { addDescription("Tests that a certificate can be identified based on the correct signature."); addStep("Create CertificateID object based on the certificate used to sign the data", "CertificateID object not null"); @@ -58,10 +58,11 @@ public void positiveCertificateIdentificationTest() throws Exception { CertificateID certificateIDFromSignature = new CertificateID(signer.getSID().getIssuer(), signer.getSID().getSerialNumber()); addStep("Assert that the two CertificateID objects are equal", "Assert succeeds"); - Assert.assertEquals(certificateIDfromCertificate, certificateIDFromSignature); + Assertions.assertEquals(certificateIDfromCertificate, certificateIDFromSignature); } - @Test(groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public void negativeCertificateIdentificationTest() throws Exception { addDescription("Tests that a certificate is not identified based on a incorrect signature."); addStep("Create CertificateID object based on a certificate not used for signing the data", "CertificateID object not null"); @@ -79,10 +80,11 @@ public void negativeCertificateIdentificationTest() throws Exception { CertificateID certificateIDFromSignature = new CertificateID(signer.getSID().getIssuer(), signer.getSID().getSerialNumber()); addStep("Assert that the two CertificateID objects are not equal", "Assert succeeds"); - Assert.assertNotSame(certificateIDFromCertificate, certificateIDFromSignature); + Assertions.assertNotSame(certificateIDFromCertificate, certificateIDFromSignature); } - @Test(groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public void equalTest() throws Exception { addDescription("Tests the equality of CertificateIDs"); addStep("Setup", ""); @@ -94,43 +96,43 @@ public void equalTest() throws Exception { CertificateID certificateID1 = new CertificateID(issuer, serial); addStep("Validate the content of the certificateID", "Should be same as x509Certificate"); - Assert.assertEquals(certificateID1.getIssuer(), issuer); - Assert.assertEquals(certificateID1.getSerial(), serial); + Assertions.assertEquals(certificateID1.getIssuer(), issuer); + Assertions.assertEquals(certificateID1.getSerial(), serial); addStep("Test whether it equals it self", "should give positive result"); - Assert.assertEquals(certificateID1, certificateID1); + Assertions.assertEquals(certificateID1, certificateID1); addStep("Test with a null as argument", "Should give negative result"); - Assert.assertNotEquals(certificateID1, null); + Assertions.assertNotEquals(null, certificateID1); addStep("Test with another class", "Should give negative result"); - Assert.assertNotEquals(new Object(), certificateID1); + Assertions.assertNotEquals(new Object(), certificateID1); addStep("Test with same issuer but no serial", "Should give negative result"); - Assert.assertNotEquals(new CertificateID(issuer, null), certificateID1); + Assertions.assertNotEquals(new CertificateID(issuer, null), certificateID1); addStep("Test with same serial but no issuer", "Should give negative result"); - Assert.assertNotEquals(new CertificateID((X500Principal) null, serial), certificateID1); + Assertions.assertNotEquals(new CertificateID((X500Principal) null, serial), certificateID1); addStep("Test the positive case, with both the issuer and serial ", "Should give positive result"); - Assert.assertEquals(new CertificateID(issuer, serial), certificateID1); + Assertions.assertEquals(new CertificateID(issuer, serial), certificateID1); addStep("Setup an empty certificate", ""); CertificateID certificateID2 = new CertificateID((X500Principal) null, null); addStep("Test empty certificate against issuer but no serial", "Should give negative result"); - Assert.assertNotEquals(new CertificateID(issuer, null), certificateID2); + Assertions.assertNotEquals(new CertificateID(issuer, null), certificateID2); addStep("Test empty certificate against serial but no issuer", "Should give negative result"); - Assert.assertNotEquals(new CertificateID((X500Principal) null, serial), certificateID2); + Assertions.assertNotEquals(new CertificateID((X500Principal) null, serial), certificateID2); addStep("Test empty certificate against serial and issuer", "Should give negative result"); - Assert.assertNotEquals(new CertificateID(issuer, serial), certificateID2); + Assertions.assertNotEquals(new CertificateID(issuer, serial), certificateID2); addStep("Test the positive case, with neither issuer nor serial", "Should give positive result"); - Assert.assertEquals(new CertificateID((X500Principal) null, null), certificateID2); + Assertions.assertEquals(new CertificateID((X500Principal) null, null), certificateID2); addStep("Check the hash codes for the two certificate", "Should not be the same"); - Assert.assertTrue(certificateID1.hashCode() != certificateID2.hashCode()); + Assertions.assertTrue(certificateID1.hashCode() != certificateID2.hashCode()); } } diff --git a/bitrepository-core/src/test/java/org/bitrepository/protocol/security/PermissionStoreTest.java b/bitrepository-core/src/test/java/org/bitrepository/protocol/security/PermissionStoreTest.java index dc0c48324..9a5be20b9 100644 --- a/bitrepository-core/src/test/java/org/bitrepository/protocol/security/PermissionStoreTest.java +++ b/bitrepository-core/src/test/java/org/bitrepository/protocol/security/PermissionStoreTest.java @@ -27,25 +27,27 @@ import org.bouncycastle.cms.SignerInformation; import org.bouncycastle.util.encoders.Base64; import org.jaccept.structure.ExtendedTestCase; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; import java.math.BigInteger; import java.security.cert.X509Certificate; -import static org.testng.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; public class PermissionStoreTest extends ExtendedTestCase { private static final String componentID = "TEST"; private PermissionStore permissionStore; - @BeforeMethod(alwaysRun = true) + @BeforeEach public void setUp() throws Exception { permissionStore = new PermissionStore(); permissionStore.loadPermissions(SecurityTestConstants.getDefaultPermissions(), componentID); } - @Test(groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public void positiveCertificateRetrievalTest() throws Exception { addDescription("Tests that a certificate can be retrieved based on the correct signerId."); addStep("Create signer to lookup certificate", "No exceptions"); @@ -60,7 +62,8 @@ public void positiveCertificateRetrievalTest() throws Exception { assertEquals(positiveCertificate, certificateFromStore); } - @Test(groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public void negativeCertificateRetrievalTest() throws Exception { addDescription("Tests that a certificate cannot be retrieved based on the wrong signerId."); addStep("Create signer and modify its ID so lookup will fail", "No exceptions"); @@ -79,17 +82,20 @@ public void negativeCertificateRetrievalTest() throws Exception { assertEquals(positiveCertificate, certificateFromStore); } - //@Test(groups = {"regressiontest"}) + //@Test +// @Tag("regressiontest"}) public void certificatePermissionCheckTest() { addDescription("Tests that a certificate only allows for the expected permission."); } - //@Test(groups = {"regressiontest"}) + //@Test +// @Tag("regressiontest"}) public void unknownCertificatePermissionCheckTest() { addDescription("Tests that a unknown certificate results in expected refusal."); } - @Test(groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public void certificateFingerprintTest() throws Exception { addDescription("Tests that a certificate fingerprint can correctly be retrieved for a signer."); addFixture("Create signer to lookup fingerprint"); diff --git a/bitrepository-core/src/test/java/org/bitrepository/protocol/security/SecurityManagerTest.java b/bitrepository-core/src/test/java/org/bitrepository/protocol/security/SecurityManagerTest.java index da047e206..ee4597d9f 100644 --- a/bitrepository-core/src/test/java/org/bitrepository/protocol/security/SecurityManagerTest.java +++ b/bitrepository-core/src/test/java/org/bitrepository/protocol/security/SecurityManagerTest.java @@ -38,13 +38,13 @@ import org.bitrepository.settings.repositorysettings.PermissionSet; import org.bouncycastle.util.encoders.Base64; import org.jaccept.structure.ExtendedTestCase; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.testng.Assert; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; -import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.List; @@ -54,7 +54,7 @@ public class SecurityManagerTest extends ExtendedTestCase { private PermissionStore permissionStore; private Settings settings; - @BeforeMethod(alwaysRun = true) + @BeforeEach public void setUp() throws Exception { settings = TestSettingsProvider.reloadSettings(getClass().getSimpleName()); settings.getRepositorySettings().getProtocolSettings().setRequireMessageAuthentication(true); @@ -77,12 +77,13 @@ private void setupSecurityManager(Settings settings) { SecurityTestConstants.getComponentID()); } - @Test(groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public void operationAuthorizationBehaviourTest() throws Exception { addDescription("Tests that a signature only allows the correct requests."); List collections = settings.getRepositorySettings().getCollections().getCollection(); - Assert.assertEquals(collections.size(), 2, + Assertions.assertEquals(2, collections.size(), "There should be two collections present to test the collection limited authorization"); settings.getRepositorySettings().setPermissionSet(getCollectionLimitedPermissionSet()); setupSecurityManager(settings); @@ -95,13 +96,13 @@ public void operationAuthorizationBehaviourTest() throws Exception { securityManager.authorizeOperation(PutFileRequest.class.getSimpleName(), SecurityTestConstants.getTestData(), TestCertProvider.getPositiveCertSignature(), collectionID1); } catch (OperationAuthorizationException e) { - Assert.fail(e.getMessage()); + Assertions.fail(e.getMessage()); } try { securityManager.authorizeOperation(PutFileRequest.class.getSimpleName(), SecurityTestConstants.getTestData(), TestCertProvider.getPositiveCertSignature(), collectionID2); } catch (OperationAuthorizationException e) { - Assert.fail(e.getMessage()); + Assertions.fail(e.getMessage()); } addStep("Check that GET_FILE is only allowed for the first collection.", @@ -112,18 +113,19 @@ public void operationAuthorizationBehaviourTest() throws Exception { securityManager.authorizeOperation(GetFileRequest.class.getSimpleName(), SecurityTestConstants.getTestData(), TestCertProvider.getPositiveCertSignature(), collectionID1); } catch (OperationAuthorizationException e) { - Assert.fail(e.getMessage()); + Assertions.fail(e.getMessage()); } try { securityManager.authorizeOperation(GetFileRequest.class.getSimpleName(), SecurityTestConstants.getTestData(), TestCertProvider.getPositiveCertSignature(), collectionID2); - Assert.fail("SecurityManager did not throw the expected OperationAuthorizationException"); + Assertions.fail("SecurityManager did not throw the expected OperationAuthorizationException"); } catch (OperationAuthorizationException ignored) { } } - @Test(groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public void certificateAuthorizationBehaviourTest() throws Exception { addDescription("Tests that a certificate is only allowed by registered users (component)."); addStep("Check that the registered component is allowed.", "The registered component is allowed."); @@ -134,20 +136,21 @@ public void certificateAuthorizationBehaviourTest() throws Exception { securityManager.authorizeCertificateUse(SecurityTestConstants.getAllowedCertificateUser(), SecurityTestConstants.getTestData(), TestCertProvider.getPositiveCertSignature()); } catch (CertificateUseException e) { - Assert.fail(e.getMessage()); + Assertions.fail(e.getMessage()); } - Assert.assertNotNull(getSigningCertPermission().getPermission().get(0).getCertificate().getAllowedCertificateUsers()); + Assertions.assertNotNull(getSigningCertPermission().getPermission().get(0).getCertificate().getAllowedCertificateUsers()); addStep("Check that an unregistered component is not allowed.", "The unregistered component is not allowed."); try { securityManager.authorizeCertificateUse(SecurityTestConstants.getDisallowedCertificateUser(), SecurityTestConstants.getTestData(), TestCertProvider.getPositiveCertSignature()); - Assert.fail("SecurityManager did not throw the expected CertificateUseException"); + Assertions.fail("SecurityManager did not throw the expected CertificateUseException"); } catch (CertificateUseException ignored) { } } - @Test(groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public void positiveSigningAuthenticationRoundtripTest() throws Exception { addDescription("Tests that a roundtrip of signing a request and afterwards authenticating is succeeds."); addStep("Sign a chunk of data.", "Data is signed successfully"); @@ -155,7 +158,7 @@ public void positiveSigningAuthenticationRoundtripTest() throws Exception { try { signature = securityManager.signMessage(SecurityTestConstants.getTestData()); } catch (MessageSigningException e) { - Assert.fail("Failed signing test data!", e); + Assertions.fail("Failed signing test data!", e); } permissionStore.loadPermissions(getSigningCertPermission(), SecurityTestConstants.getComponentID()); @@ -167,11 +170,12 @@ public void positiveSigningAuthenticationRoundtripTest() throws Exception { try { securityManager.authenticateMessage(SecurityTestConstants.getTestData(), signature); } catch (MessageAuthenticationException e) { - Assert.fail("Failed authenticating test data!", e); + Assertions.fail("Failed authenticating test data!", e); } } - @Test(groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public void negativeSigningAuthenticationRoundtripUnkonwnCertificateTest() throws Exception { addDescription("Tests that a roundtrip of signing a request and afterwards authenticating it fails due to " + "a unknown certificate."); @@ -180,7 +184,7 @@ public void negativeSigningAuthenticationRoundtripUnkonwnCertificateTest() throw try { signature = securityManager.signMessage(SecurityTestConstants.getTestData()); } catch (MessageSigningException e) { - Assert.fail("Failed signing test data!", e); + Assertions.fail("Failed signing test data!", e); } String signatureString = new String(Base64.encode(signature.getBytes(SecurityModuleConstants.defaultEncodingType)), StandardCharsets.UTF_8); @@ -189,13 +193,14 @@ public void negativeSigningAuthenticationRoundtripUnkonwnCertificateTest() throw addStep("Check signature matches the data", "Signature cant be matched as certificate is unknown."); try { securityManager.authenticateMessage(SecurityTestConstants.getTestData(), signature);//signatureString); - Assert.fail("Authentication did not fail as expected"); + Assertions.fail("Authentication did not fail as expected"); } catch (MessageAuthenticationException e) { log.info(e.getMessage()); } } - @Test(groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public void negativeSigningAuthenticationRoundtripBadDataTest() throws Exception { addDescription("Tests that a roundtrip of signing a request and afterwards authenticating it fails " + "due to bad data"); @@ -205,7 +210,7 @@ public void negativeSigningAuthenticationRoundtripBadDataTest() throws Exception try { signature = securityManager.signMessage(SecurityTestConstants.getTestData()); } catch (MessageSigningException e) { - Assert.fail("Failed signing test data!", e); + Assertions.fail("Failed signing test data!", e); } permissionStore.loadPermissions(getSigningCertPermission(), SecurityTestConstants.getComponentID()); @@ -217,7 +222,7 @@ public void negativeSigningAuthenticationRoundtripBadDataTest() throws Exception String corruptData = SecurityTestConstants.getTestData() + "foobar"; try { securityManager.authenticateMessage(corruptData, signature); - Assert.fail("Authentication did not fail as expected!"); + Assertions.fail("Authentication did not fail as expected!"); } catch (MessageAuthenticationException e) { log.info(e.getMessage()); } diff --git a/bitrepository-core/src/test/java/org/bitrepository/protocol/security/SignatureGeneratorTest.java b/bitrepository-core/src/test/java/org/bitrepository/protocol/security/SignatureGeneratorTest.java index 486ba4c04..724b07d98 100644 --- a/bitrepository-core/src/test/java/org/bitrepository/protocol/security/SignatureGeneratorTest.java +++ b/bitrepository-core/src/test/java/org/bitrepository/protocol/security/SignatureGeneratorTest.java @@ -3,7 +3,7 @@ import org.bitrepository.common.settings.Settings; import org.bitrepository.common.settings.TestSettingsProvider; import org.bitrepository.protocol.security.exception.MessageSigningException; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Test; public class SignatureGeneratorTest { /* diff --git a/bitrepository-core/src/test/java/org/bitrepository/protocol/security/exception/CertificateUseExceptionTest.java b/bitrepository-core/src/test/java/org/bitrepository/protocol/security/exception/CertificateUseExceptionTest.java index c0c4a63c7..64c243572 100644 --- a/bitrepository-core/src/test/java/org/bitrepository/protocol/security/exception/CertificateUseExceptionTest.java +++ b/bitrepository-core/src/test/java/org/bitrepository/protocol/security/exception/CertificateUseExceptionTest.java @@ -5,16 +5,16 @@ * Copyright (C) 2010 - 2012 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% @@ -22,37 +22,40 @@ package org.bitrepository.protocol.security.exception; import org.jaccept.structure.ExtendedTestCase; -import org.testng.Assert; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + public class CertificateUseExceptionTest extends ExtendedTestCase { - - @Test(groups = { "regressiontest" }) + + @Test + @Tag("regressiontest") public void testCertificateUseException() throws Exception { addDescription("Test the instantiation of the exception"); addStep("Setup", ""); String errMsg = "TEST-ERROR"; String causeMsg = "CAUSE-EXCEPTION"; - + addStep("Try to throw such an exception", "Should be able to be caught and validated"); try { throw new CertificateUseException(errMsg); - } catch(Exception e) { - Assert.assertTrue(e instanceof CertificateUseException); - Assert.assertEquals(e.getMessage(), errMsg); - Assert.assertNull(e.getCause()); + } catch (Exception e) { + Assertions.assertInstanceOf(CertificateUseException.class, e); + Assertions.assertEquals(errMsg, e.getMessage()); + Assertions.assertNull(e.getCause()); } - + addStep("Throw the exception with an embedded exception", "The embedded exception should be the same."); try { throw new CertificateUseException(errMsg, new IllegalArgumentException(causeMsg)); - } catch(Exception e) { - Assert.assertTrue(e instanceof CertificateUseException); - Assert.assertEquals(e.getMessage(), errMsg); - Assert.assertNotNull(e.getCause()); - Assert.assertTrue(e.getCause() instanceof IllegalArgumentException); - Assert.assertEquals(e.getCause().getMessage(), causeMsg); + } catch (Exception e) { + Assertions.assertInstanceOf(CertificateUseException.class, e); + Assertions.assertEquals(errMsg, e.getMessage()); + Assertions.assertNotNull(e.getCause()); + Assertions.assertInstanceOf(IllegalArgumentException.class, e.getCause()); + Assertions.assertEquals(causeMsg, e.getCause().getMessage()); } } - + } diff --git a/bitrepository-core/src/test/java/org/bitrepository/protocol/security/exception/MessageAuthenticationExceptionTest.java b/bitrepository-core/src/test/java/org/bitrepository/protocol/security/exception/MessageAuthenticationExceptionTest.java index be1cb3bfd..e056a2b32 100644 --- a/bitrepository-core/src/test/java/org/bitrepository/protocol/security/exception/MessageAuthenticationExceptionTest.java +++ b/bitrepository-core/src/test/java/org/bitrepository/protocol/security/exception/MessageAuthenticationExceptionTest.java @@ -5,16 +5,16 @@ * Copyright (C) 2010 - 2012 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% @@ -22,37 +22,40 @@ package org.bitrepository.protocol.security.exception; import org.jaccept.structure.ExtendedTestCase; -import org.testng.Assert; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + public class MessageAuthenticationExceptionTest extends ExtendedTestCase { - - @Test(groups = { "regressiontest" }) + + @Test + @Tag("regressiontest") public void testMessageAuthenticationException() throws Exception { addDescription("Test the instantiation of the exception"); addStep("Setup", ""); String errMsg = "TEST-ERROR"; String causeMsg = "CAUSE-EXCEPTION"; - + addStep("Try to throw such an exception", "Should be able to be caught and validated"); try { throw new MessageAuthenticationException(errMsg); - } catch(Exception e) { - Assert.assertTrue(e instanceof MessageAuthenticationException); - Assert.assertEquals(e.getMessage(), errMsg); - Assert.assertNull(e.getCause()); + } catch (Exception e) { + Assertions.assertInstanceOf(MessageAuthenticationException.class, e); + Assertions.assertEquals(errMsg, e.getMessage()); + Assertions.assertNull(e.getCause()); } - + addStep("Throw the exception with an embedded exception", "The embedded exception should be the same."); try { throw new MessageAuthenticationException(errMsg, new IllegalArgumentException(causeMsg)); - } catch(Exception e) { - Assert.assertTrue(e instanceof MessageAuthenticationException); - Assert.assertEquals(e.getMessage(), errMsg); - Assert.assertNotNull(e.getCause()); - Assert.assertTrue(e.getCause() instanceof IllegalArgumentException); - Assert.assertEquals(e.getCause().getMessage(), causeMsg); + } catch (Exception e) { + Assertions.assertInstanceOf(MessageAuthenticationException.class, e); + Assertions.assertEquals(errMsg, e.getMessage()); + Assertions.assertNotNull(e.getCause()); + Assertions.assertInstanceOf(IllegalArgumentException.class, e.getCause()); + Assertions.assertEquals(causeMsg, e.getCause().getMessage()); } } - + } diff --git a/bitrepository-core/src/test/java/org/bitrepository/protocol/security/exception/MessageSignerExceptionTest.java b/bitrepository-core/src/test/java/org/bitrepository/protocol/security/exception/MessageSignerExceptionTest.java index 9887b6e21..f810af478 100644 --- a/bitrepository-core/src/test/java/org/bitrepository/protocol/security/exception/MessageSignerExceptionTest.java +++ b/bitrepository-core/src/test/java/org/bitrepository/protocol/security/exception/MessageSignerExceptionTest.java @@ -5,16 +5,16 @@ * Copyright (C) 2010 - 2012 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% @@ -22,37 +22,39 @@ package org.bitrepository.protocol.security.exception; import org.jaccept.structure.ExtendedTestCase; -import org.testng.Assert; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; public class MessageSignerExceptionTest extends ExtendedTestCase { - - @Test(groups = { "regressiontest" }) + + @Test + @Tag("regressiontest") public void testMessageSigningException() throws Exception { addDescription("Test the instantiation of the exception"); addStep("Setup", ""); String errMsg = "TEST-ERROR"; String causeMsg = "CAUSE-EXCEPTION"; - + addStep("Try to throw such an exception", "Should be able to be caught and validated"); try { throw new MessageSigningException(errMsg); - } catch(Exception e) { - Assert.assertTrue(e instanceof MessageSigningException); - Assert.assertEquals(e.getMessage(), errMsg); - Assert.assertNull(e.getCause()); + } catch (Exception e) { + Assertions.assertInstanceOf(MessageSigningException.class, e); + Assertions.assertEquals(errMsg, e.getMessage()); + Assertions.assertNull(e.getCause()); } - + addStep("Throw the exception with an embedded exception", "The embedded exception should be the same."); try { throw new MessageSigningException(errMsg, new IllegalArgumentException(causeMsg)); - } catch(Exception e) { - Assert.assertTrue(e instanceof MessageSigningException); - Assert.assertEquals(e.getMessage(), errMsg); - Assert.assertNotNull(e.getCause()); - Assert.assertTrue(e.getCause() instanceof IllegalArgumentException); - Assert.assertEquals(e.getCause().getMessage(), causeMsg); + } catch (Exception e) { + Assertions.assertInstanceOf(MessageSigningException.class, e); + Assertions.assertEquals(errMsg, e.getMessage()); + Assertions.assertNotNull(e.getCause()); + Assertions.assertInstanceOf(IllegalArgumentException.class, e.getCause()); + Assertions.assertEquals(causeMsg, e.getCause().getMessage()); } } - + } diff --git a/bitrepository-core/src/test/java/org/bitrepository/protocol/security/exception/OperationAuthorizationExceptionTest.java b/bitrepository-core/src/test/java/org/bitrepository/protocol/security/exception/OperationAuthorizationExceptionTest.java index 7bb62de02..e5382a030 100644 --- a/bitrepository-core/src/test/java/org/bitrepository/protocol/security/exception/OperationAuthorizationExceptionTest.java +++ b/bitrepository-core/src/test/java/org/bitrepository/protocol/security/exception/OperationAuthorizationExceptionTest.java @@ -5,16 +5,16 @@ * Copyright (C) 2010 - 2012 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% @@ -22,37 +22,40 @@ package org.bitrepository.protocol.security.exception; import org.jaccept.structure.ExtendedTestCase; -import org.testng.Assert; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + public class OperationAuthorizationExceptionTest extends ExtendedTestCase { - - @Test(groups = { "regressiontest" }) + + @Test + @Tag("regressiontest") public void testOperationAuthorizationException() throws Exception { addDescription("Test the instantiation of the exception"); addStep("Setup", ""); String errMsg = "TEST-ERROR"; String causeMsg = "CAUSE-EXCEPTION"; - + addStep("Try to throw such an exception", "Should be able to be caught and validated"); try { throw new OperationAuthorizationException(errMsg); - } catch(Exception e) { - Assert.assertTrue(e instanceof OperationAuthorizationException); - Assert.assertEquals(e.getMessage(), errMsg); - Assert.assertNull(e.getCause()); + } catch (Exception e) { + Assertions.assertInstanceOf(OperationAuthorizationException.class, e); + Assertions.assertEquals(errMsg, e.getMessage()); + Assertions.assertNull(e.getCause()); } - + addStep("Throw the exception with an embedded exception", "The embedded exception should be the same."); try { throw new OperationAuthorizationException(errMsg, new IllegalArgumentException(causeMsg)); - } catch(Exception e) { - Assert.assertTrue(e instanceof OperationAuthorizationException); - Assert.assertEquals(e.getMessage(), errMsg); - Assert.assertNotNull(e.getCause()); - Assert.assertTrue(e.getCause() instanceof IllegalArgumentException); - Assert.assertEquals(e.getCause().getMessage(), causeMsg); + } catch (Exception e) { + Assertions.assertInstanceOf(OperationAuthorizationException.class, e); + Assertions.assertEquals(errMsg, e.getMessage()); + Assertions.assertNotNull(e.getCause()); + Assertions.assertInstanceOf(IllegalArgumentException.class, e.getCause()); + Assertions.assertEquals(causeMsg, e.getCause().getMessage()); } } - + } diff --git a/bitrepository-core/src/test/java/org/bitrepository/protocol/security/exception/PermissionStoreExceptionTest.java b/bitrepository-core/src/test/java/org/bitrepository/protocol/security/exception/PermissionStoreExceptionTest.java index ee3143a4a..736bff55a 100644 --- a/bitrepository-core/src/test/java/org/bitrepository/protocol/security/exception/PermissionStoreExceptionTest.java +++ b/bitrepository-core/src/test/java/org/bitrepository/protocol/security/exception/PermissionStoreExceptionTest.java @@ -5,16 +5,16 @@ * Copyright (C) 2010 - 2012 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% @@ -22,37 +22,40 @@ package org.bitrepository.protocol.security.exception; import org.jaccept.structure.ExtendedTestCase; -import org.testng.Assert; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + public class PermissionStoreExceptionTest extends ExtendedTestCase { - - @Test(groups = { "regressiontest" }) + + @Test + @Tag("regressiontest") public void testPermissionStoreException() throws Exception { addDescription("Test the instantiation of the exception"); addStep("Setup", ""); String errMsg = "TEST-ERROR"; String causeMsg = "CAUSE-EXCEPTION"; - + addStep("Try to throw such an exception", "Should be able to be caught and validated"); try { throw new PermissionStoreException(errMsg); - } catch(Exception e) { - Assert.assertTrue(e instanceof PermissionStoreException); - Assert.assertEquals(e.getMessage(), errMsg); - Assert.assertNull(e.getCause()); + } catch (Exception e) { + Assertions.assertInstanceOf(PermissionStoreException.class, e); + Assertions.assertEquals(errMsg, e.getMessage()); + Assertions.assertNull(e.getCause()); } - + addStep("Throw the exception with an embedded exception", "The embedded exception should be the same."); try { throw new PermissionStoreException(errMsg, new IllegalArgumentException(causeMsg)); - } catch(Exception e) { - Assert.assertTrue(e instanceof PermissionStoreException); - Assert.assertEquals(e.getMessage(), errMsg); - Assert.assertNotNull(e.getCause()); - Assert.assertTrue(e.getCause() instanceof IllegalArgumentException); - Assert.assertEquals(e.getCause().getMessage(), causeMsg); + } catch (Exception e) { + Assertions.assertInstanceOf(PermissionStoreException.class, e); + Assertions.assertEquals(errMsg, e.getMessage()); + Assertions.assertNotNull(e.getCause()); + Assertions.assertInstanceOf(IllegalArgumentException.class, e.getCause()); + Assertions.assertEquals(causeMsg, e.getCause().getMessage()); } } - + } diff --git a/bitrepository-core/src/test/java/org/bitrepository/protocol/security/exception/SecurityExceptionTest.java b/bitrepository-core/src/test/java/org/bitrepository/protocol/security/exception/SecurityExceptionTest.java index 89150025d..742068b07 100644 --- a/bitrepository-core/src/test/java/org/bitrepository/protocol/security/exception/SecurityExceptionTest.java +++ b/bitrepository-core/src/test/java/org/bitrepository/protocol/security/exception/SecurityExceptionTest.java @@ -5,16 +5,16 @@ * Copyright (C) 2010 - 2012 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% @@ -22,37 +22,39 @@ package org.bitrepository.protocol.security.exception; import org.jaccept.structure.ExtendedTestCase; -import org.testng.Assert; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; public class SecurityExceptionTest extends ExtendedTestCase { - - @Test(groups = { "regressiontest" }) + + @Test + @Tag("regressiontest") public void testSecurityException() throws Exception { addDescription("Test the instantiation of the exception"); addStep("Setup", ""); String errMsg = "TEST-ERROR"; String causeMsg = "CAUSE-EXCEPTION"; - + addStep("Try to throw such an exception", "Should be able to be caught and validated"); try { throw new SecurityException(errMsg); - } catch(Exception e) { - Assert.assertTrue(e instanceof SecurityException); - Assert.assertEquals(e.getMessage(), errMsg); - Assert.assertNull(e.getCause()); + } catch (Exception e) { + Assertions.assertInstanceOf(SecurityException.class, e); + Assertions.assertEquals(errMsg, e.getMessage()); + Assertions.assertNull(e.getCause()); } - + addStep("Throw the exception with an embedded exception", "The embedded exception should be the same."); try { throw new SecurityException(errMsg, new IllegalArgumentException(causeMsg)); - } catch(Exception e) { - Assert.assertTrue(e instanceof SecurityException); - Assert.assertEquals(e.getMessage(), errMsg); - Assert.assertNotNull(e.getCause()); - Assert.assertTrue(e.getCause() instanceof IllegalArgumentException); - Assert.assertEquals(e.getCause().getMessage(), causeMsg); + } catch (Exception e) { + Assertions.assertInstanceOf(SecurityException.class, e); + Assertions.assertEquals(errMsg, e.getMessage()); + Assertions.assertNotNull(e.getCause()); + Assertions.assertInstanceOf(IllegalArgumentException.class, e.getCause()); + Assertions.assertEquals(causeMsg, e.getCause().getMessage()); } } - + } diff --git a/bitrepository-core/src/test/java/org/bitrepository/protocol/security/exception/UnregisteredPermissionTest.java b/bitrepository-core/src/test/java/org/bitrepository/protocol/security/exception/UnregisteredPermissionTest.java index 4bbe97ae6..cba292911 100644 --- a/bitrepository-core/src/test/java/org/bitrepository/protocol/security/exception/UnregisteredPermissionTest.java +++ b/bitrepository-core/src/test/java/org/bitrepository/protocol/security/exception/UnregisteredPermissionTest.java @@ -5,16 +5,16 @@ * Copyright (C) 2010 - 2012 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% @@ -22,37 +22,40 @@ package org.bitrepository.protocol.security.exception; import org.jaccept.structure.ExtendedTestCase; -import org.testng.Assert; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + public class UnregisteredPermissionTest extends ExtendedTestCase { - - @Test(groups = { "regressiontest" }) + + @Test + @Tag("regressiontest") public void testUnregisteredPermissionException() throws Exception { addDescription("Test the instantiation of the exception"); addStep("Setup", ""); String errMsg = "TEST-ERROR"; String causeMsg = "CAUSE-EXCEPTION"; - + addStep("Try to throw such an exception", "Should be able to be caught and validated"); try { throw new UnregisteredPermissionException(errMsg); - } catch(Exception e) { - Assert.assertTrue(e instanceof UnregisteredPermissionException); - Assert.assertEquals(e.getMessage(), errMsg); - Assert.assertNull(e.getCause()); + } catch (Exception e) { + Assertions.assertInstanceOf(UnregisteredPermissionException.class, e); + Assertions.assertEquals(errMsg, e.getMessage()); + Assertions.assertNull(e.getCause()); } - + addStep("Throw the exception with an embedded exception", "The embedded exception should be the same."); try { throw new UnregisteredPermissionException(errMsg, new IllegalArgumentException(causeMsg)); - } catch(Exception e) { - Assert.assertTrue(e instanceof UnregisteredPermissionException); - Assert.assertEquals(e.getMessage(), errMsg); - Assert.assertNotNull(e.getCause()); - Assert.assertTrue(e.getCause() instanceof IllegalArgumentException); - Assert.assertEquals(e.getCause().getMessage(), causeMsg); + } catch (Exception e) { + Assertions.assertInstanceOf(UnregisteredPermissionException.class, e); + Assertions.assertEquals(errMsg, e.getMessage()); + Assertions.assertNotNull(e.getCause()); + Assertions.assertInstanceOf(IllegalArgumentException.class, e.getCause()); + Assertions.assertEquals(causeMsg, e.getCause().getMessage()); } } - + } diff --git a/bitrepository-core/src/test/java/org/bitrepository/protocol/utils/ConfigLoaderTest.java b/bitrepository-core/src/test/java/org/bitrepository/protocol/utils/ConfigLoaderTest.java index 63f61a3c9..95abba7e7 100644 --- a/bitrepository-core/src/test/java/org/bitrepository/protocol/utils/ConfigLoaderTest.java +++ b/bitrepository-core/src/test/java/org/bitrepository/protocol/utils/ConfigLoaderTest.java @@ -23,38 +23,40 @@ import org.bitrepository.common.utils.FileUtils; import org.jaccept.structure.ExtendedTestCase; -import org.testng.Assert; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; import java.io.File; public class ConfigLoaderTest extends ExtendedTestCase { String GOOD_FILE_PATH = "logback-test.xml"; - @BeforeMethod(alwaysRun = true) + @BeforeEach public void setup() { FileUtils.copyFile(new File("src/test/resources/logback-test.xml"), new File(GOOD_FILE_PATH)); } - @AfterMethod(alwaysRun = true) + @AfterEach public void teardown() { FileUtils.delete(new File(GOOD_FILE_PATH)); } - @Test(groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public void testLoadingConfig() throws Exception { addDescription("Test the loading of a configuration file for the config loader."); addStep("Setup variables", ""); String badFilePath = "iDoNotExist.xml"; - Assert.assertFalse(new File(badFilePath).exists()); - Assert.assertTrue(new File(GOOD_FILE_PATH).exists()); + Assertions.assertFalse(new File(badFilePath).exists()); + Assertions.assertTrue(new File(GOOD_FILE_PATH).exists()); addStep("Test with a invalid file path", "Should throw an exception"); try { new LogbackConfigLoader(badFilePath); - Assert.fail("Should throw an exception"); + Assertions.fail("Should throw an exception"); } catch (IllegalArgumentException e) { // expected } @@ -66,7 +68,7 @@ public void testLoadingConfig() throws Exception { try { new LogbackConfigLoader(GOOD_FILE_PATH); - Assert.fail("Should throw an exception"); + Assertions.fail("Should throw an exception"); } catch (IllegalArgumentException e) { // expected } diff --git a/bitrepository-core/src/test/java/org/bitrepository/protocol/utils/FileExchangeResolverTest.java b/bitrepository-core/src/test/java/org/bitrepository/protocol/utils/FileExchangeResolverTest.java index 558bdab3b..f3b5bcfb9 100644 --- a/bitrepository-core/src/test/java/org/bitrepository/protocol/utils/FileExchangeResolverTest.java +++ b/bitrepository-core/src/test/java/org/bitrepository/protocol/utils/FileExchangeResolverTest.java @@ -6,12 +6,13 @@ import org.bitrepository.protocol.http.HttpsFileExchange; import org.bitrepository.settings.referencesettings.FileExchangeSettings; import org.bitrepository.settings.referencesettings.ProtocolType; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Test; import java.net.MalformedURLException; import java.net.URL; -import static org.testng.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; public class FileExchangeResolverTest { @Test @@ -19,7 +20,7 @@ public void resolveFileProtocol() { FileExchangeSettings settings = new FileExchangeSettings(); settings.setProtocolType(ProtocolType.FILE); FileExchange exchange = FileExchangeResolver.getFileExchange(settings); - assertEquals(exchange.getClass(), LocalFileExchange.class); + assertEquals(LocalFileExchange.class, exchange.getClass()); } @Test @@ -27,7 +28,7 @@ public void resolveHttpProtocol() { FileExchangeSettings settings = new FileExchangeSettings(); settings.setProtocolType(ProtocolType.HTTP); FileExchange exchange = FileExchangeResolver.getFileExchange(settings); - assertEquals(exchange.getClass(), HttpFileExchange.class); + assertEquals(HttpFileExchange.class, exchange.getClass()); } @Test @@ -35,33 +36,35 @@ public void resolveHttpsProtocol() { FileExchangeSettings settings = new FileExchangeSettings(); settings.setProtocolType(ProtocolType.HTTPS); FileExchange exchange = FileExchangeResolver.getFileExchange(settings); - assertEquals(exchange.getClass(), HttpsFileExchange.class); + assertEquals(HttpsFileExchange.class, exchange.getClass()); } @Test public void resolveFileProtocolURL() throws MalformedURLException { URL url = new URL("file:///home/user/Desktop/my-cool-file.txt"); FileExchange exchange = FileExchangeResolver.getBasicFileExchangeFromURL(url); - assertEquals(exchange.getClass(), LocalFileExchange.class); + assertEquals(LocalFileExchange.class, exchange.getClass()); } @Test public void resolveHttpProtocolURL() throws MalformedURLException { URL url = new URL("http://localhost:80/myfile.txt"); FileExchange exchange = FileExchangeResolver.getBasicFileExchangeFromURL(url); - assertEquals(exchange.getClass(), HttpFileExchange.class); + assertEquals(HttpFileExchange.class, exchange.getClass()); } @Test public void resolveHttpsProtocolURL() throws MalformedURLException { URL url = new URL("https://localhost:443/myfile.txt"); FileExchange exchange = FileExchangeResolver.getBasicFileExchangeFromURL(url); - assertEquals(exchange.getClass(), HttpsFileExchange.class); + assertEquals(HttpsFileExchange.class, exchange.getClass()); } - @Test(expectedExceptions = {IllegalArgumentException.class}) + @Test public void resolveBadProtocolURL() throws MalformedURLException { - URL badURL = new URL("ftp://some/path"); - FileExchangeResolver.getBasicFileExchangeFromURL(badURL); + assertThrows(IllegalArgumentException.class, () -> { + URL badURL = new URL("ftp://some/path"); + FileExchangeResolver.getBasicFileExchangeFromURL(badURL); + }); } } diff --git a/bitrepository-core/src/test/java/org/bitrepository/protocol/utils/MessageDataTypeValidatorTest.java b/bitrepository-core/src/test/java/org/bitrepository/protocol/utils/MessageDataTypeValidatorTest.java index 0cb10618d..4c015d152 100644 --- a/bitrepository-core/src/test/java/org/bitrepository/protocol/utils/MessageDataTypeValidatorTest.java +++ b/bitrepository-core/src/test/java/org/bitrepository/protocol/utils/MessageDataTypeValidatorTest.java @@ -6,45 +6,54 @@ import org.bitrepository.bitrepositoryelements.ChecksumType; import org.bitrepository.common.utils.Base16Utils; import org.bitrepository.common.utils.CalendarUtils; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertThrows; public class MessageDataTypeValidatorTest { - @Test(expectedExceptions = {IllegalArgumentException.class}) + @Test public void validateChecksumSpecTest() { - ChecksumSpecTYPE noChecksumTypeSpec = new ChecksumSpecTYPE(); - MessageDataTypeValidator.validate(noChecksumTypeSpec, "noChecksumTypeSpec"); + assertThrows(IllegalArgumentException.class, () -> { + ChecksumSpecTYPE noChecksumTypeSpec = new ChecksumSpecTYPE(); + MessageDataTypeValidator.validate(noChecksumTypeSpec, "noChecksumTypeSpec"); + }); } - @Test(expectedExceptions = {IllegalArgumentException.class}) + @Test public void validateChecksumDataForFileNoChecksumTest() { - ChecksumDataForFileTYPE noChecksumSpec = new ChecksumDataForFileTYPE(); - ChecksumSpecTYPE checksumTypeSpec = new ChecksumSpecTYPE(); - checksumTypeSpec.setChecksumType(ChecksumType.MD5); - noChecksumSpec.setChecksumSpec(checksumTypeSpec); - noChecksumSpec.setCalculationTimestamp(CalendarUtils.getNow()); - - MessageDataTypeValidator.validate(noChecksumSpec, "noChecksumSpec"); + assertThrows(IllegalArgumentException.class, () -> { + ChecksumDataForFileTYPE noChecksumSpec = new ChecksumDataForFileTYPE(); + ChecksumSpecTYPE checksumTypeSpec = new ChecksumSpecTYPE(); + checksumTypeSpec.setChecksumType(ChecksumType.MD5); + noChecksumSpec.setChecksumSpec(checksumTypeSpec); + noChecksumSpec.setCalculationTimestamp(CalendarUtils.getNow()); + MessageDataTypeValidator.validate(noChecksumSpec, "noChecksumSpec"); + }); } - @Test(expectedExceptions = {IllegalArgumentException.class}) + @Test public void validateChecksumDataForFileNoTimestampTest() throws DecoderException { - ChecksumDataForFileTYPE noChecksumSpec = new ChecksumDataForFileTYPE(); - ChecksumSpecTYPE checksumTypeSpec = new ChecksumSpecTYPE(); - checksumTypeSpec.setChecksumType(ChecksumType.MD5); - noChecksumSpec.setChecksumSpec(checksumTypeSpec); - noChecksumSpec.setChecksumValue(Base16Utils.encodeBase16("abab")); + assertThrows(IllegalArgumentException.class, () -> { + ChecksumDataForFileTYPE noChecksumSpec = new ChecksumDataForFileTYPE(); + ChecksumSpecTYPE checksumTypeSpec = new ChecksumSpecTYPE(); + checksumTypeSpec.setChecksumType(ChecksumType.MD5); + noChecksumSpec.setChecksumSpec(checksumTypeSpec); + noChecksumSpec.setChecksumValue(Base16Utils.encodeBase16("abab")); - MessageDataTypeValidator.validate(noChecksumSpec, "noChecksumSpec"); + MessageDataTypeValidator.validate(noChecksumSpec, "noChecksumSpec"); + }); } - @Test(expectedExceptions = {IllegalArgumentException.class}) + @Test public void validateChecksumDataForFileNoChecksumSpecTest() throws DecoderException { - ChecksumDataForFileTYPE noChecksumSpec = new ChecksumDataForFileTYPE(); - noChecksumSpec.setChecksumValue(Base16Utils.encodeBase16("abab")); - noChecksumSpec.setCalculationTimestamp(CalendarUtils.getNow()); + assertThrows(IllegalArgumentException.class, () -> { + ChecksumDataForFileTYPE noChecksumSpec = new ChecksumDataForFileTYPE(); + noChecksumSpec.setChecksumValue(Base16Utils.encodeBase16("abab")); + noChecksumSpec.setCalculationTimestamp(CalendarUtils.getNow()); - MessageDataTypeValidator.validate(noChecksumSpec, "noChecksumSpec"); + MessageDataTypeValidator.validate(noChecksumSpec, "noChecksumSpec"); + }); } //@Test(expectedExceptions = {IllegalArgumentException.class}) diff --git a/bitrepository-core/src/test/java/org/bitrepository/protocol/utils/MessageUtilsTest.java b/bitrepository-core/src/test/java/org/bitrepository/protocol/utils/MessageUtilsTest.java index 368cbe233..967db37f2 100644 --- a/bitrepository-core/src/test/java/org/bitrepository/protocol/utils/MessageUtilsTest.java +++ b/bitrepository-core/src/test/java/org/bitrepository/protocol/utils/MessageUtilsTest.java @@ -25,11 +25,13 @@ import org.bitrepository.bitrepositoryelements.ResponseInfo; import org.bitrepository.bitrepositorymessages.MessageResponse; import org.jaccept.structure.ExtendedTestCase; -import org.testng.Assert; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; public class MessageUtilsTest extends ExtendedTestCase { - @Test(groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public void testPositiveIdentification() { addDescription("Tests isPositiveIdentifyResponse method in the message utility class."); MessageResponse response = new MessageResponse(); @@ -38,18 +40,19 @@ public void testPositiveIdentification() { addStep("validate that it can see a positive identify response", "Should return true for positive identify."); response.getResponseInfo().setResponseCode(ResponseCode.IDENTIFICATION_POSITIVE); - Assert.assertTrue(MessageUtils.isPositiveIdentifyResponse(response)); + Assertions.assertTrue(MessageUtils.isPositiveIdentifyResponse(response)); response.getResponseInfo().setResponseCode(ResponseCode.IDENTIFICATION_NEGATIVE); - Assert.assertFalse(MessageUtils.isPositiveIdentifyResponse(response)); + Assertions.assertFalse(MessageUtils.isPositiveIdentifyResponse(response)); response.getResponseInfo().setResponseCode(ResponseCode.OPERATION_COMPLETED); - Assert.assertFalse(MessageUtils.isPositiveIdentifyResponse(response)); + Assertions.assertFalse(MessageUtils.isPositiveIdentifyResponse(response)); response.getResponseInfo().setResponseCode(ResponseCode.OPERATION_PROGRESS); - Assert.assertFalse(MessageUtils.isPositiveIdentifyResponse(response)); + Assertions.assertFalse(MessageUtils.isPositiveIdentifyResponse(response)); response.getResponseInfo().setResponseCode(ResponseCode.OPERATION_ACCEPTED_PROGRESS); - Assert.assertFalse(MessageUtils.isPositiveIdentifyResponse(response)); + Assertions.assertFalse(MessageUtils.isPositiveIdentifyResponse(response)); } - @Test(groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public void testIdentificationResponse() { addDescription("Tests isIdentifyResponse method in the message utility class."); MessageResponse response = new MessageResponse(); @@ -58,15 +61,16 @@ public void testIdentificationResponse() { addStep("validate that it can see a identify response", "Should only return true for identify responses."); response.getResponseInfo().setResponseCode(ResponseCode.IDENTIFICATION_NEGATIVE); - Assert.assertTrue(MessageUtils.isIdentifyResponse(response)); + Assertions.assertTrue(MessageUtils.isIdentifyResponse(response)); response.getResponseInfo().setResponseCode(ResponseCode.IDENTIFICATION_POSITIVE); - Assert.assertTrue(MessageUtils.isIdentifyResponse(response)); + Assertions.assertTrue(MessageUtils.isIdentifyResponse(response)); response.getResponseInfo().setResponseCode(ResponseCode.FAILURE); - Assert.assertFalse(MessageUtils.isIdentifyResponse(response)); + Assertions.assertFalse(MessageUtils.isIdentifyResponse(response)); } - @Test(groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public void testProgressResponse() { addDescription("Tests isPositiveProgressResponse method in the message utility class."); MessageResponse response = new MessageResponse(); @@ -76,17 +80,17 @@ public void testProgressResponse() { addStep("validate progress response", "Should only return true for 'operation_progress', " + "'operation_accepted_progress' and 'identification_positive'."); response.getResponseInfo().setResponseCode(ResponseCode.IDENTIFICATION_NEGATIVE); - Assert.assertFalse(MessageUtils.isPositiveProgressResponse(response)); + Assertions.assertFalse(MessageUtils.isPositiveProgressResponse(response)); response.getResponseInfo().setResponseCode(ResponseCode.IDENTIFICATION_POSITIVE); - Assert.assertTrue(MessageUtils.isPositiveProgressResponse(response)); + Assertions.assertTrue(MessageUtils.isPositiveProgressResponse(response)); response.getResponseInfo().setResponseCode(ResponseCode.OPERATION_COMPLETED); - Assert.assertFalse(MessageUtils.isPositiveProgressResponse(response)); + Assertions.assertFalse(MessageUtils.isPositiveProgressResponse(response)); response.getResponseInfo().setResponseCode(ResponseCode.OPERATION_PROGRESS); - Assert.assertTrue(MessageUtils.isPositiveProgressResponse(response)); + Assertions.assertTrue(MessageUtils.isPositiveProgressResponse(response)); response.getResponseInfo().setResponseCode(ResponseCode.OPERATION_ACCEPTED_PROGRESS); - Assert.assertTrue(MessageUtils.isPositiveProgressResponse(response)); + Assertions.assertTrue(MessageUtils.isPositiveProgressResponse(response)); response.getResponseInfo().setResponseCode(ResponseCode.FAILURE); - Assert.assertFalse(MessageUtils.isIdentifyResponse(response)); + Assertions.assertFalse(MessageUtils.isIdentifyResponse(response)); } } diff --git a/bitrepository-core/src/test/java/org/bitrepository/protocol/utils/TestWatcherExtension.java b/bitrepository-core/src/test/java/org/bitrepository/protocol/utils/TestWatcherExtension.java new file mode 100644 index 000000000..917784d18 --- /dev/null +++ b/bitrepository-core/src/test/java/org/bitrepository/protocol/utils/TestWatcherExtension.java @@ -0,0 +1,22 @@ +package org.bitrepository.protocol.utils; + +import org.junit.jupiter.api.extension.ExtensionContext; +import org.junit.jupiter.api.extension.TestWatcher; + +public class TestWatcherExtension implements TestWatcher { + private boolean testSuccessful = true; + + @Override + public void testAborted(ExtensionContext context, Throwable cause) { + testSuccessful = false; + } + + @Override + public void testFailed(ExtensionContext context, Throwable cause) { + testSuccessful = false; + } + + public boolean isTestSuccessful() { + return testSuccessful; + } +} \ No newline at end of file diff --git a/bitrepository-core/src/test/java/org/bitrepository/settings/SettingsProviderTest.java b/bitrepository-core/src/test/java/org/bitrepository/settings/SettingsProviderTest.java index f202465da..2d8f0de97 100644 --- a/bitrepository-core/src/test/java/org/bitrepository/settings/SettingsProviderTest.java +++ b/bitrepository-core/src/test/java/org/bitrepository/settings/SettingsProviderTest.java @@ -24,23 +24,26 @@ import org.bitrepository.common.settings.Settings; import org.bitrepository.common.settings.SettingsProvider; import org.bitrepository.common.settings.XMLFileSettingsLoader; -import org.testng.Assert; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; public class SettingsProviderTest { private static final String PATH_TO_TEST_SETTINGS = "settings/xml/bitrepository-devel"; - @Test(groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public void componentIDTest() { String myComponentID = "TestComponentID"; SettingsProvider settingsLoader = new SettingsProvider(new XMLFileSettingsLoader(PATH_TO_TEST_SETTINGS), myComponentID); Settings settings = settingsLoader.getSettings(); - Assert.assertEquals(settings.getComponentID(), myComponentID); + Assertions.assertEquals(myComponentID, settings.getComponentID()); } - @Test(groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public void reloadTest() { String myComponentID = "TestComponentID"; SettingsProvider settingsLoader = @@ -51,13 +54,13 @@ public void reloadTest() { String newCollectionID = "newCollectionID"; settings.getRepositorySettings().getCollections().getCollection().get(0).setID(newCollectionID); - Assert.assertEquals(settings.getRepositorySettings().getCollections().getCollection().get(0).getID(), - newCollectionID); - Assert.assertEquals(settings.getCollections().get(0).getID(), newCollectionID); + Assertions.assertEquals(newCollectionID, + settings.getRepositorySettings().getCollections().getCollection().get(0).getID()); + Assertions.assertEquals(newCollectionID, settings.getCollections().get(0).getID()); settingsLoader.reloadSettings(); settings = settingsLoader.getSettings(); - Assert.assertEquals(settings.getRepositorySettings().getCollections().getCollection().get(0).getID(), originalCollectionID); - Assert.assertEquals(settings.getCollections().get(0).getID(), originalCollectionID); + Assertions.assertEquals(settings.getRepositorySettings().getCollections().getCollection().get(0).getID(), originalCollectionID); + Assertions.assertEquals(settings.getCollections().get(0).getID(), originalCollectionID); } } diff --git a/bitrepository-integrity-service/src/main/java/org/bitrepository/integrityservice/cache/database/IntegrityDBTools.java b/bitrepository-integrity-service/src/main/java/org/bitrepository/integrityservice/cache/database/IntegrityDBTools.java index 05feafb83..43da38cdf 100644 --- a/bitrepository-integrity-service/src/main/java/org/bitrepository/integrityservice/cache/database/IntegrityDBTools.java +++ b/bitrepository-integrity-service/src/main/java/org/bitrepository/integrityservice/cache/database/IntegrityDBTools.java @@ -65,7 +65,6 @@ public void removeCollection(String collectionID) throws IntegrityDBStateExcepti String removeCollectionSql = "DELETE FROM collections WHERE collectionID = ? CASCADE"; DatabaseUtils.executeStatement(dbConnector, removeCollectionSql, collectionID); - ; } diff --git a/bitrepository-integrity-service/src/main/java/org/bitrepository/integrityservice/collector/IntegrityCollectorEventHandler.java b/bitrepository-integrity-service/src/main/java/org/bitrepository/integrityservice/collector/IntegrityCollectorEventHandler.java index b1843757d..6af80d6a0 100644 --- a/bitrepository-integrity-service/src/main/java/org/bitrepository/integrityservice/collector/IntegrityCollectorEventHandler.java +++ b/bitrepository-integrity-service/src/main/java/org/bitrepository/integrityservice/collector/IntegrityCollectorEventHandler.java @@ -41,7 +41,6 @@ import java.util.Objects; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; -import java.util.concurrent.TimeUnit; /** * The EventHandler for the integrity collector. diff --git a/bitrepository-integrity-service/src/main/java/org/bitrepository/integrityservice/collector/SimpleChecksumEventHandler.java b/bitrepository-integrity-service/src/main/java/org/bitrepository/integrityservice/collector/SimpleChecksumEventHandler.java index e3da1d0ce..22f600306 100644 --- a/bitrepository-integrity-service/src/main/java/org/bitrepository/integrityservice/collector/SimpleChecksumEventHandler.java +++ b/bitrepository-integrity-service/src/main/java/org/bitrepository/integrityservice/collector/SimpleChecksumEventHandler.java @@ -39,7 +39,6 @@ import java.util.Objects; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; -import java.util.concurrent.TimeUnit; /** * Simple eventHandler for retrieving checksum results. diff --git a/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/IntegrityAlerterTest.java b/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/IntegrityAlerterTest.java index 3065ff497..175841cef 100644 --- a/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/IntegrityAlerterTest.java +++ b/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/IntegrityAlerterTest.java @@ -5,16 +5,16 @@ * Copyright (C) 2010 - 2012 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% @@ -26,11 +26,15 @@ import org.bitrepository.integrityservice.alerter.IntegrityAlarmDispatcher; import org.bitrepository.integrityservice.alerter.IntegrityAlerter; import org.bitrepository.protocol.IntegrationTest; -import org.testng.Assert; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + public class IntegrityAlerterTest extends IntegrationTest { - @Test(groups = {"regressiontest", "integritytest"}) + @Test + @Tag("regressiontest") + @Tag("integritytest") public void testIntegrityFailed() { addDescription("Test the IntegrityFailed method for the IntegrityAlerter"); @@ -38,19 +42,21 @@ public void testIntegrityFailed() { IntegrityAlerter alerter = new IntegrityAlarmDispatcher(settingsForCUT, messageBus, null); alerter.integrityFailed("Testaintegrity alarm", collectionID); AlarmMessage alarmMessage = alarmReceiver.waitForMessage(AlarmMessage.class); - Assert.assertEquals(alarmMessage.getAlarm().getAlarmCode(), AlarmCode.INTEGRITY_ISSUE); + Assertions.assertEquals(AlarmCode.INTEGRITY_ISSUE, alarmMessage.getAlarm().getAlarmCode()); } - - @Test(groups = {"regressiontest", "integritytest"}) + + @Test + @Tag("regressiontest") + @Tag("integritytest") public void testOperationFailed() { addDescription("Test the OperationFailed method for the IntegrityAlerter"); - + addStep("Call the function for integrity failure.", "A integrity alarm should be generate."); IntegrityAlerter alerter = new IntegrityAlarmDispatcher(settingsForCUT, messageBus, null); alerter.operationFailed("Testing the ability to fail.", collectionID); AlarmMessage alarmMessage = alarmReceiver.waitForMessage(AlarmMessage.class); - Assert.assertEquals(alarmMessage.getAlarm().getAlarmCode(), AlarmCode.FAILED_OPERATION); + Assertions.assertEquals(AlarmCode.FAILED_OPERATION, alarmMessage.getAlarm().getAlarmCode()); } } diff --git a/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/IntegrityDatabaseTestCase.java b/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/IntegrityDatabaseTestCase.java index 95aa07bcf..3c05cf6eb 100644 --- a/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/IntegrityDatabaseTestCase.java +++ b/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/IntegrityDatabaseTestCase.java @@ -34,8 +34,8 @@ import org.bitrepository.service.database.DatabaseUtils; import org.bitrepository.service.database.DerbyDatabaseDestroyer; import org.jaccept.structure.ExtendedTestCase; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeMethod; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; import javax.xml.datatype.DatatypeConfigurationException; import java.math.BigInteger; @@ -44,7 +44,7 @@ public abstract class IntegrityDatabaseTestCase extends ExtendedTestCase { protected Settings settings; - @BeforeMethod (alwaysRun = true) + @BeforeEach public void setup() throws Exception { settings = TestSettingsProvider.reloadSettings("IntegrityCheckingUnderTest"); customizeSettings(); @@ -56,16 +56,16 @@ public void setup() throws Exception { integrityDatabaseCreator.createIntegrityDatabase(settings, null); } - @AfterMethod (alwaysRun = true) + @AfterEach public void clearDatabase() throws Exception { DBConnector connector = new DBConnector(settings.getReferenceSettings().getIntegrityServiceSettings().getIntegrityDatabase()); - DatabaseUtils.executeStatement(connector, "DELETE FROM fileinfo", new Object[0]); - DatabaseUtils.executeStatement(connector, "DELETE FROM collection_progress", new Object[0]); - DatabaseUtils.executeStatement(connector, "DELETE FROM pillarstats", new Object[0]); - DatabaseUtils.executeStatement(connector, "DELETE FROM collectionstats", new Object[0]); - DatabaseUtils.executeStatement(connector, "DELETE FROM stats", new Object[0]); - DatabaseUtils.executeStatement(connector, "DELETE FROM pillar", new Object[0]); - DatabaseUtils.executeStatement(connector, "DELETE FROM collections", new Object[0]); + DatabaseUtils.executeStatement(connector, "DELETE FROM fileinfo"); + DatabaseUtils.executeStatement(connector, "DELETE FROM collection_progress"); + DatabaseUtils.executeStatement(connector, "DELETE FROM pillarstats"); + DatabaseUtils.executeStatement(connector, "DELETE FROM collectionstats"); + DatabaseUtils.executeStatement(connector, "DELETE FROM stats"); + DatabaseUtils.executeStatement(connector, "DELETE FROM pillar"); + DatabaseUtils.executeStatement(connector, "DELETE FROM collections"); } /** diff --git a/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/IntegrityWorkflowSchedulerTest.java b/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/IntegrityWorkflowSchedulerTest.java index 743a48350..bb8a2f59e 100644 --- a/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/IntegrityWorkflowSchedulerTest.java +++ b/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/IntegrityWorkflowSchedulerTest.java @@ -27,9 +27,9 @@ //import org.bitrepository.integrityservice.scheduler.TimerBasedScheduler; //import org.bitrepository.integrityservice.scheduler.workflow.Workflow; //import org.jaccept.structure.ExtendedTestCase; -//import org.testng.Assert; -//import org.testng.annotations.BeforeClass; -//import org.testng.annotations.Test; +// +// +// // ///** // * Test that scheduler calls triggers. @@ -44,33 +44,35 @@ // settings = TestSettingsProvider.reloadSettings("IntegrityWorkflowSchedulerUnderTest"); // } // -// @Test(groups = {"regressiontest", "integritytest"}) +// @Test +// @Tag("regressiontest", "integritytest"}) // public void testSchedulerContainingWorkflows() { // addDescription("Test that schedulers call all workflow at the given intervals."); // addStep("Setup a scheduler and validate initial state", "No errors and no workflows"); // TimerBasedScheduler scheduler = new TimerBasedScheduler(settings); -// Assert.assertEquals(scheduler.getJobs().size(), 0, "Should not be any workflows in the scheduler."); +// Assertions.assertEquals(scheduler.getJobs().size(), 0, "Should not be any workflows in the scheduler."); // // addStep("Make a new workflow, add it to the scheduler and extract it afterwards.", // "Should extract the same workflow"); // Workflow testWorkflow = new MockWorkflow(3600000L, "testWorkflow"); // scheduler.putWorkflow(testWorkflow); -// Assert.assertEquals(scheduler.getJobs().size(), 1, "Should only be one workflow in the scheduler."); -// Assert.assertEquals(scheduler.getJobs().get(0), testWorkflow, "Should be the same workflow."); +// Assertions.assertEquals(scheduler.getJobs().size(), 1, "Should only be one workflow in the scheduler."); +// Assertions.assertEquals(scheduler.getJobs().get(0), testWorkflow, "Should be the same workflow."); // // addStep("Add the workflow again to the scheduler", "Should still be only the one and same workflow in the scheduler"); // scheduler.putWorkflow(testWorkflow); -// Assert.assertEquals(scheduler.getJobs().size(), 1, "Should only be one workflow in the scheduler."); -// Assert.assertEquals(scheduler.getJobs().get(0), testWorkflow, "Should be the same workflow."); +// Assertions.assertEquals(scheduler.getJobs().size(), 1, "Should only be one workflow in the scheduler."); +// Assertions.assertEquals(scheduler.getJobs().get(0), testWorkflow, "Should be the same workflow."); // // addStep("Remove the workflow from the scheduler two times", // "Should not be any workflows in the scheduler, and only successfully remove workflow once."); -// Assert.assertTrue(scheduler.removeWorkflow(testWorkflow.getPrimitiveName())); -// Assert.assertEquals(scheduler.getJobs().size(), 0, "Should not be any workflows in the scheduler."); -// Assert.assertFalse(scheduler.removeWorkflow(testWorkflow.getPrimitiveName())); +// Assertions.assertTrue(scheduler.removeWorkflow(testWorkflow.getPrimitiveName())); +// Assertions.assertEquals(scheduler.getJobs().size(), 0, "Should not be any workflows in the scheduler."); +// Assertions.assertFalse(scheduler.removeWorkflow(testWorkflow.getPrimitiveName())); // } // -// @Test(groups = {"regressiontest", "integrationtest"}) +// @Test +// @Tag("regressiontest", "integrationtest"}) // public void schedulerTester() throws Exception { // addDescription("Tests that the scheduler is able make calls to the collector at given intervals."); // addStep("Setup the variables and such.", "Should not be able to fail here."); @@ -80,16 +82,16 @@ // // addStep("Create a workflow", "Should not have been called yet been called."); // MockWorkflow workflow = new MockWorkflow(INTERVAL + INTERVAL_DELAY, taskName); -// Assert.assertEquals(workflow.getCallsForNextRun(), 0); -// Assert.assertEquals(workflow.getCallsForRunWorkflow(), 0); +// Assertions.assertEquals(workflow.getCallsForNextRun(), 0); +// Assertions.assertEquals(workflow.getCallsForRunWorkflow(), 0); // // addStep("Add the workflow", "Validate that it initially calls the "); // scheduler.putWorkflow(workflow); // synchronized(this) { // wait(INTERVAL_DELAY); // } -// Assert.assertEquals(workflow.getCallsForNextRun(), 1); -// Assert.assertEquals(workflow.getCallsForRunWorkflow(), 1); +// Assertions.assertEquals(workflow.getCallsForNextRun(), 1); +// Assertions.assertEquals(workflow.getCallsForRunWorkflow(), 1); // // addStep("Wait 4 * the interval (plus delay for instantiation), stop the trigger and validate the results.", // "Should have checked the date 5 times, but only run the workflow 3 times."); @@ -97,8 +99,8 @@ // wait(4*INTERVAL); // } // scheduler.removeWorkflow(taskName); -// Assert.assertEquals(workflow.getCallsForNextRun(), 5); -// Assert.assertEquals(workflow.getCallsForRunWorkflow(), 3); +// Assertions.assertEquals(workflow.getCallsForNextRun(), 5); +// Assertions.assertEquals(workflow.getCallsForRunWorkflow(), 3); // // addStep("Wait another 2 seconds and validate that the trigger has been cancled.", // "Should have made no more calls to the workflow."); @@ -106,7 +108,7 @@ // wait(2*INTERVAL + INTERVAL_DELAY); // } // scheduler.removeWorkflow(taskName); -// Assert.assertEquals(workflow.getCallsForNextRun(), 5); -// Assert.assertEquals(workflow.getCallsForRunWorkflow(), 3); +// Assertions.assertEquals(workflow.getCallsForNextRun(), 5); +// Assertions.assertEquals(workflow.getCallsForRunWorkflow(), 3); // } //} diff --git a/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/cache/FileInfoTest.java b/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/cache/FileInfoTest.java index 0d9530b3e..e4f405cb2 100644 --- a/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/cache/FileInfoTest.java +++ b/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/cache/FileInfoTest.java @@ -5,16 +5,16 @@ * Copyright (C) 2010 - 2012 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% @@ -23,15 +23,16 @@ import org.bitrepository.common.utils.CalendarUtils; import org.jaccept.structure.ExtendedTestCase; -import org.testng.Assert; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; import javax.xml.datatype.DatatypeConstants; import javax.xml.datatype.XMLGregorianCalendar; public class FileInfoTest extends ExtendedTestCase { - - private static final String FILE_ID = "TEST-FILE"; + + private static final String FILE_ID = "TEST-FILE"; private static final long LAST_FILE_CHECK_MILLIS = 1000000; private static final XMLGregorianCalendar LAST_FILE_CHECK = CalendarUtils.getFromMillis(LAST_FILE_CHECK_MILLIS); private static final String CHECKSUM = "CHECKSUM"; @@ -39,38 +40,40 @@ public class FileInfoTest extends ExtendedTestCase { private static final XMLGregorianCalendar LAST_CHECKSUM_CHECK = CalendarUtils.getFromMillis(LAST_CHECKSUM_CHECK_MILLIS); private static final String PILLAR_ID = "test-pillar"; private static final Long FILE_SIZE = 12345L; - - @Test(groups = {"regressiontest", "integritytest"}) + + @Test + @Tag("regressiontest") + @Tag("integritytest") public void testFileInfo() { addDescription("Tests the FileInfo element. Adds all data and extracts it again."); addStep("Setup the file info.", "Should be possible to extract all the data again."); FileInfo fi = new FileInfo(FILE_ID, LAST_FILE_CHECK, CHECKSUM, FILE_SIZE, LAST_CHECKSUM_CHECK, PILLAR_ID); - - Assert.assertEquals(fi.getFileId(), FILE_ID); - Assert.assertEquals(fi.getDateForLastFileIDCheck().toGregorianCalendar().getTimeInMillis(), LAST_FILE_CHECK_MILLIS); - Assert.assertEquals(fi.getChecksum(), CHECKSUM); - Assert.assertEquals(fi.getDateForLastChecksumCheck().toGregorianCalendar().getTimeInMillis(), LAST_CHECKSUM_CHECK_MILLIS); - Assert.assertEquals(fi.getPillarId(), PILLAR_ID); - Assert.assertEquals(fi.getFileSize(), FILE_SIZE); - + + Assertions.assertEquals(FILE_ID, fi.getFileId()); + Assertions.assertEquals(LAST_FILE_CHECK_MILLIS, fi.getDateForLastFileIDCheck().toGregorianCalendar().getTimeInMillis()); + Assertions.assertEquals(CHECKSUM, fi.getChecksum()); + Assertions.assertEquals(LAST_CHECKSUM_CHECK_MILLIS, fi.getDateForLastChecksumCheck().toGregorianCalendar().getTimeInMillis()); + Assertions.assertEquals(PILLAR_ID, fi.getPillarId()); + Assertions.assertEquals(FILE_SIZE, fi.getFileSize()); + addStep("Change the checksum", "Should be possible to extract it again."); String newChecksum = "NEW-CHECKSUM"; fi.setChecksum(newChecksum); - Assert.assertNotEquals(newChecksum, CHECKSUM); - Assert.assertEquals(fi.getChecksum(), newChecksum); + Assertions.assertNotEquals(CHECKSUM, newChecksum); + Assertions.assertEquals(newChecksum, fi.getChecksum()); addStep("Change the date for last file id check", "Should be possible to extract it again."); long newLastFileMillis = 1234567; XMLGregorianCalendar newLastFileCheck = CalendarUtils.getFromMillis(newLastFileMillis); fi.setDateForLastFileIDCheck(newLastFileCheck); - Assert.assertNotEquals(DatatypeConstants.EQUAL, LAST_FILE_CHECK.compare(newLastFileCheck)); - Assert.assertEquals(fi.getDateForLastFileIDCheck().toGregorianCalendar().getTimeInMillis(), newLastFileMillis); - + Assertions.assertNotEquals(DatatypeConstants.EQUAL, LAST_FILE_CHECK.compare(newLastFileCheck)); + Assertions.assertEquals(newLastFileMillis, fi.getDateForLastFileIDCheck().toGregorianCalendar().getTimeInMillis()); + addStep("Change the date for last checksum check", "Should be possible to extract it again."); long newLastChecksumMillis = 7654321; XMLGregorianCalendar newLastChecksumCheck = CalendarUtils.getFromMillis(newLastChecksumMillis); fi.setDateForLastChecksumCheck(newLastChecksumCheck); - Assert.assertNotEquals(DatatypeConstants.EQUAL, LAST_CHECKSUM_CHECK.compare(newLastChecksumCheck)); - Assert.assertEquals(fi.getDateForLastChecksumCheck().toGregorianCalendar().getTimeInMillis(), newLastChecksumMillis); + Assertions.assertNotEquals(DatatypeConstants.EQUAL, LAST_CHECKSUM_CHECK.compare(newLastChecksumCheck)); + Assertions.assertEquals(newLastChecksumMillis, fi.getDateForLastChecksumCheck().toGregorianCalendar().getTimeInMillis()); } } diff --git a/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/cache/IntegrityDAOTest.java b/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/cache/IntegrityDAOTest.java index 6b66e35fa..0844249d7 100644 --- a/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/cache/IntegrityDAOTest.java +++ b/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/cache/IntegrityDAOTest.java @@ -1,23 +1,23 @@ /* * #%L * Bitrepository Integrity Client - * + * * $Id$ * $HeadURL$ * %% * Copyright (C) 2010 - 2012 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% @@ -36,9 +36,10 @@ import org.bitrepository.integrityservice.cache.database.IntegrityDAO; import org.bitrepository.integrityservice.cache.database.IntegrityIssueIterator; import org.bitrepository.service.database.DatabaseManager; -import org.testng.Assert; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; import java.math.BigInteger; import java.text.ParseException; @@ -56,264 +57,291 @@ public class IntegrityDAOTest extends IntegrityDatabaseTestCase { String TEST_PILLAR_1 = "MY-TEST-PILLAR-1"; String TEST_PILLAR_2 = "MY-TEST-PILLAR-2"; String EXTRA_PILLAR = "MY-EXTRA-PILLAR"; - + String TEST_FILE_ID = "TEST-FILE-ID"; String TEST_CHECKSUM = "1234cccc4321"; - + String TEST_COLLECTIONID; public static final String EXTRA_COLLECTION = "extra-collection"; - @BeforeMethod (alwaysRun = true) + @BeforeEach @Override public void setup() throws Exception { super.setup(); TEST_COLLECTIONID = settings.getRepositorySettings().getCollections().getCollection().get(0).getID(); } - - @Override + + @Override protected void customizeSettings() { - org.bitrepository.settings.repositorysettings.Collection c0 = + org.bitrepository.settings.repositorysettings.Collection c0 = settings.getRepositorySettings().getCollections().getCollection().get(0); c0.getPillarIDs().getPillarID().clear(); c0.getPillarIDs().getPillarID().add(TEST_PILLAR_1); c0.getPillarIDs().getPillarID().add(TEST_PILLAR_2); settings.getRepositorySettings().getCollections().getCollection().clear(); settings.getRepositorySettings().getCollections().getCollection().add(c0); - - org.bitrepository.settings.repositorysettings.Collection extraCollection = + + org.bitrepository.settings.repositorysettings.Collection extraCollection = new org.bitrepository.settings.repositorysettings.Collection(); extraCollection.setID(EXTRA_COLLECTION); - org.bitrepository.settings.repositorysettings.PillarIDs pids - = new org.bitrepository.settings.repositorysettings.PillarIDs(); + org.bitrepository.settings.repositorysettings.PillarIDs pids + = new org.bitrepository.settings.repositorysettings.PillarIDs(); pids.getPillarID().add(TEST_PILLAR_1); pids.getPillarID().add(EXTRA_PILLAR); extraCollection.setPillarIDs(pids); settings.getRepositorySettings().getCollections().getCollection().add(extraCollection); } - @Test(groups = {"regressiontest", "databasetest", "integritytest"}) + @Test + @Tag("regressiontest") + @Tag("databasetest") + @Tag("integritytest") public void instantiationTest() throws Exception { addDescription("Testing the connection to the integrity database."); IntegrityDAO cache = createDAO(); - Assert.assertNotNull(cache); + Assertions.assertNotNull(cache); } - @Test(groups = {"regressiontest", "databasetest", "integritytest"}) + @Test + @Tag("regressiontest") + @Tag("databasetest") + @Tag("integritytest") public void reinitialiseDatabaseTest() throws Exception { addDescription("Testing the connection to the integrity database."); addStep("Setup manually.", "Should be created."); DatabaseManager dm = new IntegrityDatabaseManager( settings.getReferenceSettings().getIntegrityServiceSettings().getIntegrityDatabase()); - + IntegrityDAO cache = new DerbyIntegrityDAO(dm.getConnector()); - Assert.assertNotNull(cache); + Assertions.assertNotNull(cache); addStep("Close the connection and create another one.", "Should not fail"); dm.getConnector().getConnection().close(); dm.getConnector().destroy(); - synchronized(this) { + synchronized (this) { wait(100); } - + DatabaseManager newdm = new IntegrityDatabaseManager( settings.getReferenceSettings().getIntegrityServiceSettings().getIntegrityDatabase()); - + cache = new DerbyIntegrityDAO(newdm.getConnector()); } - - @Test(groups = {"regressiontest", "databasetest", "integritytest"}) + + @Test + @Tag("regressiontest") + @Tag("databasetest") + @Tag("integritytest") public void initialStateExtractionTest() throws Exception { addDescription("Tests the initial state of the IntegrityModel. Should not contain any data."); IntegrityDAO cache = createDAO(); - + List pillersInDB = cache.getAllPillars(); - Assert.assertTrue(pillersInDB.containsAll(Arrays.asList(TEST_PILLAR_1, TEST_PILLAR_2, EXTRA_PILLAR))); - Assert.assertEquals(pillersInDB.size(), 3); + Assertions.assertTrue(pillersInDB.containsAll(Arrays.asList(TEST_PILLAR_1, TEST_PILLAR_2, EXTRA_PILLAR))); + Assertions.assertEquals(3, pillersInDB.size()); List collectionsInDB = cache.getCollections(); - Assert.assertTrue(collectionsInDB.containsAll(Arrays.asList(TEST_COLLECTIONID, EXTRA_COLLECTION))); - Assert.assertEquals(collectionsInDB.size(), 2); - - Assert.assertEquals(cache.getNumberOfFilesInCollection(TEST_COLLECTIONID), Long.valueOf(0)); - Assert.assertEquals(cache.getNumberOfFilesInCollection(EXTRA_COLLECTION), Long.valueOf(0)); + Assertions.assertTrue(collectionsInDB.containsAll(Arrays.asList(TEST_COLLECTIONID, EXTRA_COLLECTION))); + Assertions.assertEquals(2, collectionsInDB.size()); + + Assertions.assertEquals(cache.getNumberOfFilesInCollection(TEST_COLLECTIONID), Long.valueOf(0)); + Assertions.assertEquals(cache.getNumberOfFilesInCollection(EXTRA_COLLECTION), Long.valueOf(0)); } - - @Test(groups = {"regressiontest", "databasetest", "integritytest"}) - public void testCorrectDateHandling() throws ParseException { + + @Test + @Tag("regressiontest") + @Tag("databasetest") + @Tag("integritytest") + public void testCorrectDateHandling() throws ParseException { addDescription("Testing the correct ingest and extraction of file and checksum dates"); IntegrityDAO cache = createDAO(); - + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX", Locale.ROOT); Date summertimeTS = sdf.parse("2015-10-25T02:59:54.000+02:00"); Date summertimeUnix = new Date(1445734794000L); - Assert.assertEquals(summertimeTS, summertimeUnix); - + Assertions.assertEquals(summertimeTS, summertimeUnix); + Date wintertimeTS = sdf.parse("2015-10-25T02:59:54.000+01:00"); Date wintertimeUnix = new Date(1445738394000L); - Assert.assertEquals(wintertimeTS, wintertimeUnix); - + Assertions.assertEquals(wintertimeTS, wintertimeUnix); + FileIDsData summertimeData = getFileIDsData("summertime"); summertimeData.getFileIDsDataItems().getFileIDsDataItem().get(0) - .setLastModificationTime(CalendarUtils.getXmlGregorianCalendar(summertimeTS)); + .setLastModificationTime(CalendarUtils.getXmlGregorianCalendar(summertimeTS)); FileIDsData wintertimeData = getFileIDsData("wintertime"); wintertimeData.getFileIDsDataItems().getFileIDsDataItem().get(0) - .setLastModificationTime(CalendarUtils.getXmlGregorianCalendar(wintertimeTS)); + .setLastModificationTime(CalendarUtils.getXmlGregorianCalendar(wintertimeTS)); cache.updateFileIDs(summertimeData, TEST_PILLAR_1, TEST_COLLECTIONID); cache.updateFileIDs(wintertimeData, TEST_PILLAR_1, TEST_COLLECTIONID); - + List summertimeCsData = getChecksumResults("summertime", TEST_CHECKSUM); summertimeCsData.get(0).setCalculationTimestamp(CalendarUtils.getXmlGregorianCalendar(summertimeTS)); List wintertimeCsData = getChecksumResults("wintertime", TEST_CHECKSUM); wintertimeCsData.get(0).setCalculationTimestamp(CalendarUtils.getXmlGregorianCalendar(wintertimeTS)); cache.updateChecksums(summertimeCsData, TEST_PILLAR_1, TEST_COLLECTIONID); cache.updateChecksums(wintertimeCsData, TEST_PILLAR_1, TEST_COLLECTIONID); - + List fis = cache.getFileInfosForFile("summertime", TEST_COLLECTIONID); - Assert.assertEquals(fis.size(), 1, fis.toString()); - Assert.assertEquals( + Assertions.assertEquals(1, fis.size(), fis.toString()); + Assertions.assertEquals( CalendarUtils.convertFromXMLGregorianCalendar(fis.get(0).getDateForLastChecksumCheck()), summertimeUnix); - + fis = cache.getFileInfosForFile("wintertime", TEST_COLLECTIONID); - Assert.assertEquals(fis.size(), 1, fis.toString()); - Assert.assertEquals( + Assertions.assertEquals(1, fis.size(), fis.toString()); + Assertions.assertEquals( CalendarUtils.convertFromXMLGregorianCalendar(fis.get(0).getDateForLastChecksumCheck()), wintertimeUnix); } - - @Test(groups = {"regressiontest", "databasetest", "integritytest"}) + + @Test + @Tag("regressiontest") + @Tag("databasetest") + @Tag("integritytest") public void testIngestOfFileIDsData() throws Exception { addDescription("Tests the ingesting of file ids data"); IntegrityDAO cache = createDAO(); - - Assert.assertEquals(cache.getNumberOfFilesInCollection(TEST_COLLECTIONID), Long.valueOf(0)); - Assert.assertEquals(cache.getNumberOfFilesInCollection(EXTRA_COLLECTION), Long.valueOf(0)); - + + Assertions.assertEquals(cache.getNumberOfFilesInCollection(TEST_COLLECTIONID), Long.valueOf(0)); + Assertions.assertEquals(cache.getNumberOfFilesInCollection(EXTRA_COLLECTION), Long.valueOf(0)); + addStep("Create data", "Should be ingested into the database"); FileIDsData data1 = getFileIDsData(TEST_FILE_ID); cache.updateFileIDs(data1, TEST_PILLAR_1, TEST_COLLECTIONID); cache.updateFileIDs(data1, TEST_PILLAR_2, TEST_COLLECTIONID); - + addStep("Extract the data", "Should be identical to the ingested data"); Collection fileinfos = cache.getFileInfosForFile(TEST_FILE_ID, TEST_COLLECTIONID); - Assert.assertNotNull(fileinfos); - for(FileInfo fi : fileinfos) { - Assert.assertEquals(fi.getFileId(), TEST_FILE_ID); - Assert.assertNull(fi.getChecksum()); - Assert.assertEquals(fi.getDateForLastChecksumCheck(), CalendarUtils.getEpoch()); - Assert.assertEquals(fi.getDateForLastFileIDCheck(), data1.getFileIDsDataItems().getFileIDsDataItem().get(0).getLastModificationTime()); - Assert.assertEquals(fi.getFileSize(), Long.valueOf(data1.getFileIDsDataItems().getFileIDsDataItem().get(0).getFileSize().longValue())); + Assertions.assertNotNull(fileinfos); + for (FileInfo fi : fileinfos) { + Assertions.assertEquals(fi.getFileId(), TEST_FILE_ID); + Assertions.assertNull(fi.getChecksum()); + Assertions.assertEquals(fi.getDateForLastChecksumCheck(), CalendarUtils.getEpoch()); + Assertions.assertEquals(fi.getDateForLastFileIDCheck(), data1.getFileIDsDataItems().getFileIDsDataItem().get(0).getLastModificationTime()); + Assertions.assertEquals(fi.getFileSize(), Long.valueOf(data1.getFileIDsDataItems().getFileIDsDataItem().get(0).getFileSize().longValue())); } - + addStep("Check that the extra collection is untouched by the ingest", "should deliver an empty collection and no errors"); - Assert.assertEquals(cache.getNumberOfFilesInCollection(TEST_COLLECTIONID), Long.valueOf(1)); - Assert.assertEquals(cache.getNumberOfFilesInCollection(EXTRA_COLLECTION), Long.valueOf(0)); + Assertions.assertEquals(cache.getNumberOfFilesInCollection(TEST_COLLECTIONID), Long.valueOf(1)); + Assertions.assertEquals(cache.getNumberOfFilesInCollection(EXTRA_COLLECTION), Long.valueOf(0)); } - @Test(groups = {"regressiontest", "databasetest", "integritytest"}) + @Test + @Tag("regressiontest") + @Tag("databasetest") + @Tag("integritytest") public void testIngestOfChecksumsData() throws Exception { addDescription("Tests the ingesting of checksums data"); IntegrityDAO cache = createDAO(); - - Assert.assertEquals(cache.getNumberOfFilesInCollection(TEST_COLLECTIONID), Long.valueOf(0)); - Assert.assertEquals(cache.getNumberOfFilesInCollection(EXTRA_COLLECTION), Long.valueOf(0)); - + + Assertions.assertEquals(cache.getNumberOfFilesInCollection(TEST_COLLECTIONID), Long.valueOf(0)); + Assertions.assertEquals(cache.getNumberOfFilesInCollection(EXTRA_COLLECTION), Long.valueOf(0)); + addStep("Create data", "Should be ingested into the database"); List csData = getChecksumResults(TEST_FILE_ID, TEST_CHECKSUM); cache.updateChecksums(csData, TEST_PILLAR_1, TEST_COLLECTIONID); cache.updateChecksums(csData, TEST_PILLAR_2, TEST_COLLECTIONID); - + addStep("Extract the data", "Should be identical to the ingested data"); Collection fileinfos = cache.getFileInfosForFile(TEST_FILE_ID, TEST_COLLECTIONID); - Assert.assertNotNull(fileinfos); - for(FileInfo fi : fileinfos) { - Assert.assertEquals(fi.getFileId(), TEST_FILE_ID); - Assert.assertEquals(fi.getChecksum(), TEST_CHECKSUM); - Assert.assertEquals(fi.getDateForLastChecksumCheck(), csData.get(0).getCalculationTimestamp()); + Assertions.assertNotNull(fileinfos); + for (FileInfo fi : fileinfos) { + Assertions.assertEquals(fi.getFileId(), TEST_FILE_ID); + Assertions.assertEquals(fi.getChecksum(), TEST_CHECKSUM); + Assertions.assertEquals(fi.getDateForLastChecksumCheck(), csData.get(0).getCalculationTimestamp()); } - + addStep("Check that the extra collection is untouched by the ingest", "should deliver an empty collection and no errors"); - Assert.assertEquals(cache.getNumberOfFilesInCollection(TEST_COLLECTIONID), Long.valueOf(1)); - Assert.assertEquals(cache.getNumberOfFilesInCollection(EXTRA_COLLECTION), Long.valueOf(0)); - + Assertions.assertEquals(cache.getNumberOfFilesInCollection(TEST_COLLECTIONID), Long.valueOf(1)); + Assertions.assertEquals(cache.getNumberOfFilesInCollection(EXTRA_COLLECTION), Long.valueOf(0)); + } - - - @Test(groups = {"regressiontest", "databasetest", "integritytest"}) + + + @Test + @Tag("regressiontest") + @Tag("databasetest") + @Tag("integritytest") public void testDeletingEntry() throws Exception { addDescription("Tests the deletion of an FileID entry from a collection. " + - "Checks that it does not effect another collection with a fileID equal to the deleted"); + "Checks that it does not effect another collection with a fileID equal to the deleted"); IntegrityDAO cache = createDAO(); Collection fileinfos = cache.getFileInfosForFile(TEST_FILE_ID, TEST_COLLECTIONID); - Assert.assertNotNull(fileinfos); - Assert.assertEquals(fileinfos.size(), 0); + Assertions.assertNotNull(fileinfos); + Assertions.assertEquals(0, fileinfos.size()); addStep("Create data", "Should be ingested into the database"); FileIDsData data1 = getFileIDsData(TEST_FILE_ID); - cache.updateFileIDs(data1, TEST_PILLAR_1, TEST_COLLECTIONID); + cache.updateFileIDs(data1, TEST_PILLAR_1, TEST_COLLECTIONID); cache.updateFileIDs(data1, TEST_PILLAR_2, TEST_COLLECTIONID); - + cache.updateFileIDs(data1, TEST_PILLAR_1, EXTRA_COLLECTION); cache.updateFileIDs(data1, EXTRA_PILLAR, EXTRA_COLLECTION); - + addStep("Ensure that the data is present", "the data is present"); fileinfos = cache.getFileInfosForFile(TEST_FILE_ID, TEST_COLLECTIONID); - Assert.assertNotNull(fileinfos); - Assert.assertEquals(fileinfos.size(), 2); + Assertions.assertNotNull(fileinfos); + Assertions.assertEquals(2, fileinfos.size()); fileinfos = cache.getFileInfosForFile(TEST_FILE_ID, EXTRA_COLLECTION); - Assert.assertNotNull(fileinfos); - Assert.assertEquals(fileinfos.size(), 2); - + Assertions.assertNotNull(fileinfos); + Assertions.assertEquals(2, fileinfos.size()); + addStep("Delete the entry for the first pillar", "No fileinfos should be extracted from the pillar in the collection."); cache.removeFile(TEST_COLLECTIONID, TEST_PILLAR_1, TEST_FILE_ID); List fis = cache.getFileInfosForFile(TEST_FILE_ID, TEST_COLLECTIONID); - Assert.assertNotNull(fis); - Assert.assertEquals(fis.size(), 1); - Assert.assertEquals(fis.get(0).getPillarId(), TEST_PILLAR_2); - + Assertions.assertNotNull(fis); + Assertions.assertEquals(1, fis.size()); + Assertions.assertEquals(fis.get(0).getPillarId(), TEST_PILLAR_2); + addStep("Delete the entry for the second pillar", "No fileinfos should be extracted from the collection."); cache.removeFile(TEST_COLLECTIONID, TEST_PILLAR_2, TEST_FILE_ID); fis = cache.getFileInfosForFile(TEST_FILE_ID, TEST_COLLECTIONID); - Assert.assertNotNull(fis); - Assert.assertEquals(fis.size(), 0); - + Assertions.assertNotNull(fis); + Assertions.assertEquals(0, fis.size()); + addStep("Check that the data in the extra collection is still present", "the data is present"); fileinfos = cache.getFileInfosForFile(TEST_FILE_ID, EXTRA_COLLECTION); - Assert.assertNotNull(fileinfos); - Assert.assertEquals(fileinfos.size(), 2); + Assertions.assertNotNull(fileinfos); + Assertions.assertEquals(2, fileinfos.size()); } - @Test(groups = {"regressiontest", "databasetest", "integritytest"}) + @Test + @Tag("regressiontest") + @Tag("databasetest") + @Tag("integritytest") public void testDeletingNonExistingEntry() throws Exception { addDescription("Tests the deletion of an nonexisting FileID entry."); IntegrityDAO cache = createDAO(); - + String nonexistingFileEntry = "NON-EXISTING-FILE-ENTRY" + new Date().getTime(); addStep("Create data", "Should be ingested into the database"); FileIDsData data1 = getFileIDsData(TEST_FILE_ID); cache.updateFileIDs(data1, TEST_PILLAR_1, TEST_COLLECTIONID); cache.updateFileIDs(data1, TEST_PILLAR_2, TEST_COLLECTIONID); - + Collection fileinfos = cache.getFileInfosForFile(nonexistingFileEntry, TEST_COLLECTIONID); - Assert.assertNotNull(fileinfos); - Assert.assertEquals(fileinfos.size(), 0); - + Assertions.assertNotNull(fileinfos); + Assertions.assertEquals(0, fileinfos.size()); + fileinfos = cache.getFileInfosForFile(TEST_FILE_ID, TEST_COLLECTIONID); - Assert.assertNotNull(fileinfos); - Assert.assertEquals(fileinfos.size(), 2); - + Assertions.assertNotNull(fileinfos); + Assertions.assertEquals(2, fileinfos.size()); + addStep("Delete a nonexisting entry", "Should not change the state of the database."); cache.removeFile(TEST_COLLECTIONID, TEST_PILLAR_1, nonexistingFileEntry); cache.removeFile(TEST_COLLECTIONID, TEST_PILLAR_2, nonexistingFileEntry); fileinfos = cache.getFileInfosForFile(TEST_FILE_ID, TEST_COLLECTIONID); - Assert.assertNotNull(fileinfos); - Assert.assertEquals(fileinfos.size(), 2); + Assertions.assertNotNull(fileinfos); + Assertions.assertEquals(2, fileinfos.size()); } - - @Test(groups = {"regressiontest", "databasetest", "integritytest"}) + + @Test + @Tag("regressiontest") + @Tag("databasetest") + @Tag("integritytest") public void testFindOrphanFiles() throws Exception { addDescription("Tests the ability to find orphan files."); IntegrityDAO cache = createDAO(); - + addStep("Create data", "Should be ingested into the database"); String orphanFile = "orphan"; String existingFile = "existing"; @@ -323,38 +351,41 @@ public void testFindOrphanFiles() throws Exception { cache.updateFileIDs(data1, TEST_PILLAR_2, TEST_COLLECTIONID); cache.updateFileIDs(data3, TEST_PILLAR_1, TEST_COLLECTIONID); cache.updateFileIDs(data3, TEST_PILLAR_2, TEST_COLLECTIONID); - Assert.assertEquals(cache.getNumberOfFilesInCollection(TEST_COLLECTIONID), Long.valueOf(2)); - Assert.assertEquals(cache.getNumberOfFilesInCollection(EXTRA_COLLECTION), Long.valueOf(0)); + Assertions.assertEquals(cache.getNumberOfFilesInCollection(TEST_COLLECTIONID), Long.valueOf(2)); + Assertions.assertEquals(cache.getNumberOfFilesInCollection(EXTRA_COLLECTION), Long.valueOf(0)); Thread.sleep(100); Date updateTime = new Date(); cache.updateFileIDs(data1, TEST_PILLAR_1, TEST_COLLECTIONID); cache.updateFileIDs(data1, TEST_PILLAR_2, TEST_COLLECTIONID); cache.updateFileIDs(data3, TEST_PILLAR_1, TEST_COLLECTIONID); - - List orphanFilesPillar1 = getIssuesFromIterator(cache.getOrphanFilesOnPillar(TEST_COLLECTIONID, + + List orphanFilesPillar1 = getIssuesFromIterator(cache.getOrphanFilesOnPillar(TEST_COLLECTIONID, TEST_PILLAR_1, updateTime)); - Assert.assertEquals(orphanFilesPillar1.size(), 0); - List orphanFilesPillar2 = getIssuesFromIterator(cache.getOrphanFilesOnPillar(TEST_COLLECTIONID, + Assertions.assertEquals(0, orphanFilesPillar1.size()); + List orphanFilesPillar2 = getIssuesFromIterator(cache.getOrphanFilesOnPillar(TEST_COLLECTIONID, TEST_PILLAR_2, updateTime)); - Assert.assertEquals(orphanFilesPillar2.size(), 1); + Assertions.assertEquals(1, orphanFilesPillar2.size()); } - - @Test(groups = {"regressiontest", "databasetest", "integritytest"}) + + @Test + @Tag("regressiontest") + @Tag("databasetest") + @Tag("integritytest") public void testFindInconsistentChecksum() throws Exception { addDescription("Testing the localization of inconsistent checksums"); IntegrityDAO cache = createDAO(); - + String checksum1_1 = "11"; String checksum1_2 = "12"; String checksum3 = "33"; String checksum2_1 = "21"; String checksum2_2 = "22"; - + String BAD_FILE_ID_1 = "BAD-FILE-1"; String BAD_FILE_ID_2 = "BAD-FILE-2"; String GOOD_FILE_ID = "GOOD-FILE"; - addStep("Update the database with 2 inconsistent files and one consistent file.", + addStep("Update the database with 2 inconsistent files and one consistent file.", "Ingesting the data into the database"); List csData1_1 = getChecksumResults(BAD_FILE_ID_1, checksum1_1); List csData1_2 = getChecksumResults(BAD_FILE_ID_2, checksum1_2); @@ -371,16 +402,19 @@ public void testFindInconsistentChecksum() throws Exception { addStep("Find the files with inconsistent checksums", "Bad file 1 and 2"); List filesWithChecksumError - = getIssuesFromIterator(cache.findFilesWithChecksumInconsistencies(TEST_COLLECTIONID)); - Assert.assertEquals(filesWithChecksumError, Arrays.asList(BAD_FILE_ID_1, BAD_FILE_ID_2)); + = getIssuesFromIterator(cache.findFilesWithChecksumInconsistencies(TEST_COLLECTIONID)); + Assertions.assertEquals(filesWithChecksumError, Arrays.asList(BAD_FILE_ID_1, BAD_FILE_ID_2)); } - @Test(groups = {"regressiontest", "databasetest", "integritytest"}) + @Test + @Tag("regressiontest") + @Tag("databasetest") + @Tag("integritytest") public void testNoChecksums() throws Exception { addDescription("Testing the checksum validation, when no checksums exists."); IntegrityDAO cache = createDAO(); - - addStep("Update the database with 2 inconsistent files and one consistent file.", + + addStep("Update the database with 2 inconsistent files and one consistent file.", "Ingesting the data into the database"); FileIDsData data1 = getFileIDsData(TEST_FILE_ID); cache.updateFileIDs(data1, TEST_PILLAR_1, TEST_COLLECTIONID); @@ -388,60 +422,66 @@ public void testNoChecksums() throws Exception { addStep("Finding the files with inconsistent checksums", "No checksum thus no errors"); List filesWithChecksumError - = getIssuesFromIterator(cache.findFilesWithChecksumInconsistencies(TEST_COLLECTIONID)); - Assert.assertEquals(filesWithChecksumError, Collections.emptyList()); + = getIssuesFromIterator(cache.findFilesWithChecksumInconsistencies(TEST_COLLECTIONID)); + Assertions.assertEquals(filesWithChecksumError, Collections.emptyList()); } - @Test(groups = {"regressiontest", "databasetest", "integritytest"}) + @Test + @Tag("regressiontest") + @Tag("databasetest") + @Tag("integritytest") public void testMissingChecksums() throws Exception { addDescription("Testing the checksum validation, when only one pillar has a checksum for a file."); IntegrityDAO cache = createDAO(); Date testStart = new Date(); - addStep("Update the database with 1 file, missing its checksum on one pillar.", + addStep("Update the database with 1 file, missing its checksum on one pillar.", "Ingesting the data into the database"); cache.updateFileIDs(getFileIDsData(TEST_FILE_ID), TEST_PILLAR_1, TEST_COLLECTIONID); cache.updateFileIDs(getFileIDsData(TEST_FILE_ID), TEST_PILLAR_2, TEST_COLLECTIONID); - cache.updateChecksums(getChecksumResults(TEST_FILE_ID, TEST_CHECKSUM),TEST_PILLAR_1, TEST_COLLECTIONID); - + cache.updateChecksums(getChecksumResults(TEST_FILE_ID, TEST_CHECKSUM), TEST_PILLAR_1, TEST_COLLECTIONID); + addStep("Finding the files with inconsistent checksums", "No checksum thus no errors"); - List filesWithChecksumError - = getIssuesFromIterator(cache.findFilesWithChecksumInconsistencies(TEST_COLLECTIONID)); - Assert.assertEquals(filesWithChecksumError, Collections.emptyList()); - - List fileWithMissingChecksumPillar1 - = getIssuesFromIterator(cache.getFilesWithMissingChecksums(TEST_COLLECTIONID, TEST_PILLAR_1, testStart)); - Assert.assertEquals(fileWithMissingChecksumPillar1, Collections.emptyList()); - List fileWithMissingChecksumPillar2 - = getIssuesFromIterator(cache.getFilesWithMissingChecksums(TEST_COLLECTIONID, TEST_PILLAR_2, testStart)); - Assert.assertEquals(fileWithMissingChecksumPillar2, Collections.singletonList(TEST_FILE_ID)); + List filesWithChecksumError + = getIssuesFromIterator(cache.findFilesWithChecksumInconsistencies(TEST_COLLECTIONID)); + Assertions.assertEquals(filesWithChecksumError, Collections.emptyList()); + + List fileWithMissingChecksumPillar1 + = getIssuesFromIterator(cache.getFilesWithMissingChecksums(TEST_COLLECTIONID, TEST_PILLAR_1, testStart)); + Assertions.assertEquals(fileWithMissingChecksumPillar1, Collections.emptyList()); + List fileWithMissingChecksumPillar2 + = getIssuesFromIterator(cache.getFilesWithMissingChecksums(TEST_COLLECTIONID, TEST_PILLAR_2, testStart)); + Assertions.assertEquals(fileWithMissingChecksumPillar2, Collections.singletonList(TEST_FILE_ID)); } - - @Test(groups = {"regressiontest", "databasetest", "integritytest"}) + + @Test + @Tag("regressiontest") + @Tag("databasetest") + @Tag("integritytest") public void testMissingChecksumsChecksumNotUpdated() throws Exception { addDescription("Testing the checksum validation, when only one pillar has a checksum for a file."); IntegrityDAO cache = createDAO(); Date testStart = new Date(); - addStep("Update the database with 1 file, no missing checksums.", + addStep("Update the database with 1 file, no missing checksums.", "Ingesting the data into the database"); cache.updateFileIDs(getFileIDsData(TEST_FILE_ID), TEST_PILLAR_1, TEST_COLLECTIONID); cache.updateFileIDs(getFileIDsData(TEST_FILE_ID), TEST_PILLAR_2, TEST_COLLECTIONID); cache.updateChecksums(getChecksumResults(TEST_FILE_ID, TEST_CHECKSUM), TEST_PILLAR_1, TEST_COLLECTIONID); cache.updateChecksums(getChecksumResults(TEST_FILE_ID, TEST_CHECKSUM), TEST_PILLAR_2, TEST_COLLECTIONID); - + addStep("Finding the files with inconsistent checksums", "No checksum thus no errors"); - List filesWithChecksumError - = getIssuesFromIterator(cache.findFilesWithChecksumInconsistencies(TEST_COLLECTIONID)); - Assert.assertEquals(filesWithChecksumError, Collections.emptyList()); - - List fileWithMissingChecksumPillar1 - = getIssuesFromIterator(cache.getFilesWithMissingChecksums(TEST_COLLECTIONID, TEST_PILLAR_1, testStart)); - Assert.assertEquals(fileWithMissingChecksumPillar1, Collections.emptyList()); - List fileWithMissingChecksumPillar2 - = getIssuesFromIterator(cache.getFilesWithMissingChecksums(TEST_COLLECTIONID, TEST_PILLAR_2, testStart)); - Assert.assertEquals(fileWithMissingChecksumPillar2, Collections.emptyList()); - + List filesWithChecksumError + = getIssuesFromIterator(cache.findFilesWithChecksumInconsistencies(TEST_COLLECTIONID)); + Assertions.assertEquals(filesWithChecksumError, Collections.emptyList()); + + List fileWithMissingChecksumPillar1 + = getIssuesFromIterator(cache.getFilesWithMissingChecksums(TEST_COLLECTIONID, TEST_PILLAR_1, testStart)); + Assertions.assertEquals(fileWithMissingChecksumPillar1, Collections.emptyList()); + List fileWithMissingChecksumPillar2 + = getIssuesFromIterator(cache.getFilesWithMissingChecksums(TEST_COLLECTIONID, TEST_PILLAR_2, testStart)); + Assertions.assertEquals(fileWithMissingChecksumPillar2, Collections.emptyList()); + addStep("Updating the checksum for one pillar, and checking that the other pillars checksum is now missing", "The second pillar is reported to be missing the checksum for the file"); Date secondUpdate = new Date(); @@ -449,137 +489,152 @@ public void testMissingChecksumsChecksumNotUpdated() throws Exception { cache.updateChecksums(getChecksumResults(TEST_FILE_ID, TEST_CHECKSUM), TEST_PILLAR_1, TEST_COLLECTIONID); addStep("Finding the files with inconsistent checksums", "No checksum thus no errors"); filesWithChecksumError = getIssuesFromIterator(cache.findFilesWithChecksumInconsistencies(TEST_COLLECTIONID)); - Assert.assertEquals(filesWithChecksumError, Collections.emptyList()); - - fileWithMissingChecksumPillar1 - = getIssuesFromIterator(cache.getFilesWithMissingChecksums(TEST_COLLECTIONID, TEST_PILLAR_1, secondUpdate)); - Assert.assertEquals(fileWithMissingChecksumPillar1, Collections.emptyList()); - fileWithMissingChecksumPillar2 - = getIssuesFromIterator(cache.getFilesWithMissingChecksums(TEST_COLLECTIONID, TEST_PILLAR_2, secondUpdate)); - Assert.assertEquals(fileWithMissingChecksumPillar2, Collections.singletonList(TEST_FILE_ID)); + Assertions.assertEquals(filesWithChecksumError, Collections.emptyList()); + + fileWithMissingChecksumPillar1 + = getIssuesFromIterator(cache.getFilesWithMissingChecksums(TEST_COLLECTIONID, TEST_PILLAR_1, secondUpdate)); + Assertions.assertEquals(fileWithMissingChecksumPillar1, Collections.emptyList()); + fileWithMissingChecksumPillar2 + = getIssuesFromIterator(cache.getFilesWithMissingChecksums(TEST_COLLECTIONID, TEST_PILLAR_2, secondUpdate)); + Assertions.assertEquals(fileWithMissingChecksumPillar2, Collections.singletonList(TEST_FILE_ID)); } - - - @Test(groups = {"regressiontest", "databasetest", "integritytest"}) + + + @Test + @Tag("regressiontest") + @Tag("databasetest") + @Tag("integritytest") public void testOutdatedChecksums() throws Exception { addDescription("Testing the checksum validation, when only one pillar has a checksum for a file."); IntegrityDAO cache = createDAO(); - + Date maxDate = new Date(System.currentTimeMillis() - 10000); - - addStep("Update the database with one file, one pillar having an outdated checksum.", + + addStep("Update the database with one file, one pillar having an outdated checksum.", "Ingesting the data into the database"); cache.updateFileIDs(getFileIDsData(TEST_FILE_ID), TEST_PILLAR_1, TEST_COLLECTIONID); cache.updateFileIDs(getFileIDsData(TEST_FILE_ID), TEST_PILLAR_2, TEST_COLLECTIONID); - cache.updateChecksums(getChecksumResults(TEST_FILE_ID, TEST_CHECKSUM),TEST_PILLAR_1, TEST_COLLECTIONID); - + cache.updateChecksums(getChecksumResults(TEST_FILE_ID, TEST_CHECKSUM), TEST_PILLAR_1, TEST_COLLECTIONID); + List checksumData = getChecksumResults(TEST_FILE_ID, TEST_CHECKSUM); checksumData.get(0).setCalculationTimestamp(CalendarUtils.getEpoch()); - cache.updateChecksums(checksumData,TEST_PILLAR_2, TEST_COLLECTIONID); - + cache.updateChecksums(checksumData, TEST_PILLAR_2, TEST_COLLECTIONID); + addStep("Finding the files with inconsistent checksums", "No checksum thus no errors"); - List filesWithChecksumError - = getIssuesFromIterator(cache.findFilesWithChecksumInconsistencies(TEST_COLLECTIONID)); - Assert.assertEquals(filesWithChecksumError, Collections.emptyList()); - - List fileWithOutdatedChecksumsPillar1 - = getIssuesFromIterator(cache.getFilesWithOutdatedChecksums(TEST_COLLECTIONID, TEST_PILLAR_1, maxDate)); - Assert.assertEquals(fileWithOutdatedChecksumsPillar1, Collections.emptyList()); - - List fileWithOutdatedChecksumPillar2 - = getIssuesFromIterator(cache.getFilesWithOutdatedChecksums(TEST_COLLECTIONID, TEST_PILLAR_2, maxDate)); - Assert.assertEquals(fileWithOutdatedChecksumPillar2, Collections.singletonList(TEST_FILE_ID)); - } - - @Test(groups = {"regressiontest", "databasetest", "integritytest"}) + List filesWithChecksumError + = getIssuesFromIterator(cache.findFilesWithChecksumInconsistencies(TEST_COLLECTIONID)); + Assertions.assertEquals(filesWithChecksumError, Collections.emptyList()); + + List fileWithOutdatedChecksumsPillar1 + = getIssuesFromIterator(cache.getFilesWithOutdatedChecksums(TEST_COLLECTIONID, TEST_PILLAR_1, maxDate)); + Assertions.assertEquals(fileWithOutdatedChecksumsPillar1, Collections.emptyList()); + + List fileWithOutdatedChecksumPillar2 + = getIssuesFromIterator(cache.getFilesWithOutdatedChecksums(TEST_COLLECTIONID, TEST_PILLAR_2, maxDate)); + Assertions.assertEquals(fileWithOutdatedChecksumPillar2, Collections.singletonList(TEST_FILE_ID)); + } + + @Test + @Tag("regressiontest") + @Tag("databasetest") + @Tag("integritytest") public void testExtractingAllKnownFilesForPillars() throws Exception { addDescription("Tests that known files can be extracted for specific pillars."); IntegrityDAO cache = createDAO(); String file2 = TEST_FILE_ID + "-2"; String file3 = TEST_FILE_ID + "-3"; - + addStep("Insert two files into database for a pillar", "Ingesting the data into the database"); cache.updateFileIDs(getFileIDsData(TEST_FILE_ID, file2), TEST_PILLAR_1, TEST_COLLECTIONID); addStep("Insert a file to the extra collection for the common pillar", "Data is ingested into the database"); cache.updateFileIDs(getFileIDsData(file3), TEST_PILLAR_1, EXTRA_COLLECTION); - + addStep("Extract all the existing file ids for the pillar for collection '" + TEST_COLLECTIONID + "'", "Both file ids is found."); IntegrityIssueIterator it = cache.getAllFileIDsOnPillar(TEST_COLLECTIONID, TEST_PILLAR_1, 0L, Long.MAX_VALUE); Collection fileIDs = getIssuesFromIterator(it); - Assert.assertEquals(fileIDs.size(), 2, "Number of files: " + fileIDs.size()); - Assert.assertTrue(fileIDs.contains(TEST_FILE_ID)); - Assert.assertTrue(fileIDs.contains(file2)); - Assert.assertFalse(fileIDs.contains(file3)); + Assertions.assertEquals(2, fileIDs.size(), "Number of files: " + fileIDs.size()); + Assertions.assertTrue(fileIDs.contains(TEST_FILE_ID)); + Assertions.assertTrue(fileIDs.contains(file2)); + Assertions.assertFalse(fileIDs.contains(file3)); addStep("Extract the single fileID for the extra collection", "Only the one file id exists"); it = cache.getAllFileIDsOnPillar(EXTRA_COLLECTION, TEST_PILLAR_1, 0L, Long.MAX_VALUE); fileIDs = getIssuesFromIterator(it); - Assert.assertEquals(fileIDs.size(), 1, "Number of files: " + fileIDs.size()); - Assert.assertTrue(fileIDs.contains(file3)); - Assert.assertFalse(fileIDs.contains(file2)); - Assert.assertFalse(fileIDs.contains(TEST_FILE_ID)); - + Assertions.assertEquals(1, fileIDs.size(), "Number of files: " + fileIDs.size()); + Assertions.assertTrue(fileIDs.contains(file3)); + Assertions.assertFalse(fileIDs.contains(file2)); + Assertions.assertFalse(fileIDs.contains(TEST_FILE_ID)); + addStep("Extract all the existing file ids for another pillar", "No files are found."); it = cache.getAllFileIDsOnPillar(TEST_COLLECTIONID, TEST_PILLAR_2, 0L, Long.MAX_VALUE); fileIDs = getIssuesFromIterator(it); - Assert.assertTrue(fileIDs.isEmpty()); + Assertions.assertTrue(fileIDs.isEmpty()); } - - @Test(groups = {"regressiontest", "databasetest", "integritytest"}) + + @Test + @Tag("regressiontest") + @Tag("databasetest") + @Tag("integritytest") public void testExtractingAllKnownFilesForPillarsLimits() throws Exception { addDescription("Tests the limits for extracting files for specific pillars."); IntegrityDAO cache = createDAO(); String file2 = TEST_FILE_ID + "-2"; - + addStep("Insert two files into database for a pillar", "Ingesting the data into the database"); cache.updateFileIDs(getFileIDsData(TEST_FILE_ID, file2), TEST_PILLAR_1, TEST_COLLECTIONID); addStep("Extract with a maximum of 1", "The first file."); IntegrityIssueIterator it = cache.getAllFileIDsOnPillar(TEST_COLLECTIONID, TEST_PILLAR_1, 0L, 1L); Collection fileIDs = getIssuesFromIterator(it); - Assert.assertEquals(fileIDs.size(), 1); - Assert.assertTrue(fileIDs.contains(TEST_FILE_ID)); - + Assertions.assertEquals(1, fileIDs.size()); + Assertions.assertTrue(fileIDs.contains(TEST_FILE_ID)); + addStep("Extract with a minimum of 1 and maximum of infinite", "The last file."); it = cache.getAllFileIDsOnPillar(TEST_COLLECTIONID, TEST_PILLAR_1, 1L, Long.MAX_VALUE); fileIDs = getIssuesFromIterator(it); - Assert.assertEquals(fileIDs.size(), 1); - Assert.assertTrue(fileIDs.contains(file2)); + Assertions.assertEquals(1, fileIDs.size()); + Assertions.assertTrue(fileIDs.contains(file2)); } - @Test(groups = {"regressiontest", "databasetest", "integritytest"}) + @Test + @Tag("regressiontest") + @Tag("databasetest") + @Tag("integritytest") public void testExtractingAllMissingFiles() throws Exception { addDescription("Tests that missing files can be extracted."); IntegrityDAO cache = createDAO(); String file2 = TEST_FILE_ID + "-2"; - - addStep("Insert two files into database for a pillar and mark them as missing", + + addStep("Insert two files into database for a pillar and mark them as missing", "Ingesting the data into the database"); - + cache.updateFileIDs(getFileIDsData(TEST_FILE_ID, file2), TEST_PILLAR_1, TEST_COLLECTIONID); cache.updateFileIDs(getFileIDsData(TEST_FILE_ID), TEST_PILLAR_2, TEST_COLLECTIONID); - - addStep("Check the number of files in collection and on pillars", + + addStep("Check the number of files in collection and on pillars", "The collection should have two files, the first pillar two, the second one"); - Assert.assertEquals((long) cache.getNumberOfFilesInCollection(TEST_COLLECTIONID), 2); + Assertions.assertEquals(2, (long) cache.getNumberOfFilesInCollection(TEST_COLLECTIONID)); Map metrics = cache.getPillarCollectionMetrics(TEST_COLLECTIONID); - Assert.assertEquals(metrics.get(TEST_PILLAR_1).getPillarFileCount(), 2); - Assert.assertEquals(metrics.get(TEST_PILLAR_2).getPillarFileCount(), 1); - + Assertions.assertEquals(2, metrics.get(TEST_PILLAR_1).getPillarFileCount()); + Assertions.assertEquals(1, metrics.get(TEST_PILLAR_2).getPillarFileCount()); + addStep("Extract missing files", "one file should be missing"); - List missingFiles - = getIssuesFromIterator(cache.findFilesWithMissingCopies(TEST_COLLECTIONID, 2, 0L, 10L)); - Assert.assertEquals(missingFiles, Collections.singletonList(file2)); + List missingFiles + = getIssuesFromIterator(cache.findFilesWithMissingCopies(TEST_COLLECTIONID, 2, 0L, 10L)); + Assertions.assertEquals(missingFiles, Collections.singletonList(file2)); } - - @Test(groups = {"regressiontest", "databasetest", "integritytest"}) + + @Test + @Tag("regressiontest") + @Tag("databasetest") + @Tag("integritytest") public void testExtractingAllMissingFilesForPillarsLimits() throws Exception { addDescription("Tests the limits for extracting missing files for specific pillars."); IntegrityDAO cache = createDAO(); String file2 = TEST_FILE_ID + "-2"; String file3 = TEST_FILE_ID + "-3"; - - addStep("Insert two files into database for a pillar and set them to missing", + + addStep("Insert two files into database for a pillar and set them to missing", "Ingesting the data into the database"); cache.updateFileIDs(getFileIDsData(TEST_FILE_ID, file2, file3), TEST_PILLAR_1, TEST_COLLECTIONID); cache.updateFileIDs(getFileIDsData(TEST_FILE_ID), TEST_PILLAR_2, TEST_COLLECTIONID); @@ -587,75 +642,84 @@ public void testExtractingAllMissingFilesForPillarsLimits() throws Exception { addStep("Extract with a maximum of 1", "The first file."); IntegrityIssueIterator it = cache.findFilesWithMissingCopies(TEST_COLLECTIONID, 2, 0L, 1L); Collection fileIDs = getIssuesFromIterator(it); - Assert.assertEquals(fileIDs.size(), 1); - Assert.assertTrue(fileIDs.contains(file2)); - + Assertions.assertEquals(1, fileIDs.size()); + Assertions.assertTrue(fileIDs.contains(file2)); + addStep("Extract with a minimum of 1 and maximum of infinite", "The last file."); it = cache.findFilesWithMissingCopies(TEST_COLLECTIONID, 2, 1L, Long.MAX_VALUE); fileIDs = getIssuesFromIterator(it); - Assert.assertEquals(fileIDs.size(), 1); - Assert.assertTrue(fileIDs.contains(file3)); + Assertions.assertEquals(1, fileIDs.size()); + Assertions.assertTrue(fileIDs.contains(file3)); } - @Test(groups = {"regressiontest", "databasetest", "integritytest"}) + @Test + @Tag("regressiontest") + @Tag("databasetest") + @Tag("integritytest") public void testGetLatestFileDateEntryForCollection() throws Exception { addDescription("Tests that checksum date entries can be retrieved and manipulated."); IntegrityDAO cache = createDAO(); addStep("Create data", "Should be ingested into the database"); - - Assert.assertNull(cache.getLatestFileDate(TEST_COLLECTIONID, TEST_PILLAR_1)); - Assert.assertNull(cache.getLatestFileDate(TEST_COLLECTIONID, TEST_PILLAR_2)); - + + Assertions.assertNull(cache.getLatestFileDate(TEST_COLLECTIONID, TEST_PILLAR_1)); + Assertions.assertNull(cache.getLatestFileDate(TEST_COLLECTIONID, TEST_PILLAR_2)); + FileIDsData fidsPillar1 = getFileIDsData(TEST_FILE_ID); Date expectedLatestFileDatePillar1 = CalendarUtils.convertFromXMLGregorianCalendar( fidsPillar1.getFileIDsDataItems().getFileIDsDataItem().get(0).getLastModificationTime()); cache.updateFileIDs(fidsPillar1, TEST_PILLAR_1, TEST_COLLECTIONID); - + FileIDsData fidsPillar2 = getFileIDsData(TEST_FILE_ID); Date expectedLatestFileDatePillar2 = new Date(expectedLatestFileDatePillar1.getTime() + 100); fidsPillar2.getFileIDsDataItems().getFileIDsDataItem().get(0) - .setLastModificationTime(CalendarUtils.getXmlGregorianCalendar(expectedLatestFileDatePillar2)); + .setLastModificationTime(CalendarUtils.getXmlGregorianCalendar(expectedLatestFileDatePillar2)); cache.updateFileIDs(fidsPillar2, TEST_PILLAR_2, TEST_COLLECTIONID); - - Assert.assertEquals(cache.getLatestFileDate(TEST_COLLECTIONID, TEST_PILLAR_1), expectedLatestFileDatePillar1); - Assert.assertEquals(cache.getLatestFileDate(TEST_COLLECTIONID, TEST_PILLAR_2), expectedLatestFileDatePillar2); - - Assert.assertEquals(cache.getLatestFileDate(TEST_COLLECTIONID, TEST_PILLAR_2), + + Assertions.assertEquals(cache.getLatestFileDate(TEST_COLLECTIONID, TEST_PILLAR_1), expectedLatestFileDatePillar1); + Assertions.assertEquals(cache.getLatestFileDate(TEST_COLLECTIONID, TEST_PILLAR_2), expectedLatestFileDatePillar2); + + Assertions.assertEquals(cache.getLatestFileDate(TEST_COLLECTIONID, TEST_PILLAR_2), cache.getLatestFileDateInCollection(TEST_COLLECTIONID)); - + cache.resetFileCollectionProgress(TEST_COLLECTIONID); - Assert.assertNull(cache.getLatestFileDate(TEST_COLLECTIONID, TEST_PILLAR_1)); - Assert.assertNull(cache.getLatestFileDate(TEST_COLLECTIONID, TEST_PILLAR_2)); + Assertions.assertNull(cache.getLatestFileDate(TEST_COLLECTIONID, TEST_PILLAR_1)); + Assertions.assertNull(cache.getLatestFileDate(TEST_COLLECTIONID, TEST_PILLAR_2)); } - - @Test(groups = {"regressiontest", "databasetest", "integritytest"}) + + @Test + @Tag("regressiontest") + @Tag("databasetest") + @Tag("integritytest") public void testGetLatestChecksumDateEntryForCollection() throws Exception { addDescription("Tests that checksum date entries can be retrieved and manipulated."); IntegrityDAO cache = createDAO(); addStep("Create data", "Should be ingested into the database"); - - Assert.assertNull(cache.getLatestChecksumDate(TEST_COLLECTIONID, TEST_PILLAR_1)); - Assert.assertNull(cache.getLatestChecksumDate(TEST_COLLECTIONID, TEST_PILLAR_2)); - - List csData = getChecksumResults(TEST_FILE_ID, TEST_CHECKSUM); + + Assertions.assertNull(cache.getLatestChecksumDate(TEST_COLLECTIONID, TEST_PILLAR_1)); + Assertions.assertNull(cache.getLatestChecksumDate(TEST_COLLECTIONID, TEST_PILLAR_2)); + + List csData = getChecksumResults(TEST_FILE_ID, TEST_CHECKSUM); cache.updateChecksums(csData, TEST_PILLAR_1, TEST_COLLECTIONID); cache.updateChecksums(csData, TEST_PILLAR_2, TEST_COLLECTIONID); Date expectedLatestChecksum = CalendarUtils.convertFromXMLGregorianCalendar(csData.get(0).getCalculationTimestamp()); - Assert.assertEquals(cache.getLatestChecksumDate(TEST_COLLECTIONID, TEST_PILLAR_1), expectedLatestChecksum); - Assert.assertEquals(cache.getLatestChecksumDate(TEST_COLLECTIONID, TEST_PILLAR_2), expectedLatestChecksum); - + Assertions.assertEquals(cache.getLatestChecksumDate(TEST_COLLECTIONID, TEST_PILLAR_1), expectedLatestChecksum); + Assertions.assertEquals(cache.getLatestChecksumDate(TEST_COLLECTIONID, TEST_PILLAR_2), expectedLatestChecksum); + cache.resetChecksumCollectionProgress(TEST_COLLECTIONID); - Assert.assertNull(cache.getLatestChecksumDate(TEST_COLLECTIONID, TEST_PILLAR_1)); - Assert.assertNull(cache.getLatestChecksumDate(TEST_COLLECTIONID, TEST_PILLAR_2)); + Assertions.assertNull(cache.getLatestChecksumDate(TEST_COLLECTIONID, TEST_PILLAR_1)); + Assertions.assertNull(cache.getLatestChecksumDate(TEST_COLLECTIONID, TEST_PILLAR_2)); } - - @Test(groups = {"regressiontest", "databasetest", "integritytest"}) + + @Test + @Tag("regressiontest") + @Tag("databasetest") + @Tag("integritytest") public void testExtractCollectionFileSize() throws Exception { addDescription("Tests that the accumulated size of the collection can be extracted"); IntegrityDAO cache = createDAO(); - + addStep("Insert test data into database", "Data is ingested"); String file2 = TEST_FILE_ID + "-2"; String file3 = TEST_FILE_ID + "-3"; @@ -666,43 +730,46 @@ public void testExtractCollectionFileSize() throws Exception { FileIDsData data2 = makeFileIDsDataWithGivenFileSize(file2, size2); FileIDsData data3 = makeFileIDsDataWithGivenFileSize(file3, size3); cache.updateFileIDs(data1, TEST_PILLAR_1, TEST_COLLECTIONID); - cache.updateFileIDs(data2, TEST_PILLAR_1, TEST_COLLECTIONID); + cache.updateFileIDs(data2, TEST_PILLAR_1, TEST_COLLECTIONID); cache.updateFileIDs(data2, TEST_PILLAR_2, TEST_COLLECTIONID); cache.updateFileIDs(data3, TEST_PILLAR_2, TEST_COLLECTIONID); - + long pillar1Size = size1 + size2; long pillar2Size = size2 + size3; long collectionSize = size1 + size2 + size3; - + Map metrics = cache.getPillarCollectionMetrics(TEST_COLLECTIONID); addStep("Check the reported size of the first pillar in the collection", "The reported size matches the precalculated"); - Assert.assertEquals(metrics.get(TEST_PILLAR_1).getPillarCollectionSize(), pillar1Size); + Assertions.assertEquals(metrics.get(TEST_PILLAR_1).getPillarCollectionSize(), pillar1Size); addStep("Check the reported size of the second pillar in the collection", "The reported size matches the precalculated"); - Assert.assertEquals(metrics.get(TEST_PILLAR_2).getPillarCollectionSize(), pillar2Size); + Assertions.assertEquals(metrics.get(TEST_PILLAR_2).getPillarCollectionSize(), pillar2Size); addStep("Check the reported size of the whole collection", "The reported size matches the precalculated"); - Assert.assertEquals(cache.getCollectionSize(TEST_COLLECTIONID), collectionSize); + Assertions.assertEquals(cache.getCollectionSize(TEST_COLLECTIONID), collectionSize); } - - @Test(groups = {"regressiontest", "databasetest", "integritytest"}) + + @Test + @Tag("regressiontest") + @Tag("databasetest") + @Tag("integritytest") public void testGetFileIDAtIndex() throws Exception { addDescription("Tests that a fileID at a given index can be extracted."); IntegrityDAO cache = createDAO(); - + addStep("Extract a fileID from the empty database", "Returns a null"); - Assert.assertNull(cache.getFileIdAtIndex(TEST_COLLECTIONID, 0L)); - + Assertions.assertNull(cache.getFileIdAtIndex(TEST_COLLECTIONID, 0L)); + addStep("Insert test data into database", "Data is ingested"); FileIDsData data = makeFileIDsDataWithGivenFileSize(TEST_FILE_ID, 100L); cache.updateFileIDs(data, TEST_PILLAR_1, TEST_COLLECTIONID); cache.updateFileIDs(data, TEST_PILLAR_2, TEST_COLLECTIONID); addStep("Extract the first fileID", "The inserted fileID"); - Assert.assertEquals(cache.getFileIdAtIndex(TEST_COLLECTIONID, 0L), TEST_FILE_ID); - + Assertions.assertEquals(cache.getFileIdAtIndex(TEST_COLLECTIONID, 0L), TEST_FILE_ID); + addStep("Extract a fileID at an incomprehendable index from the database", "Returns a null"); - Assert.assertNull(cache.getFileIdAtIndex(TEST_COLLECTIONID, Long.MAX_VALUE)); + Assertions.assertNull(cache.getFileIdAtIndex(TEST_COLLECTIONID, Long.MAX_VALUE)); } - + private FileIDsData makeFileIDsDataWithGivenFileSize(String fileID, Long size) { FileIDsData res = new FileIDsData(); FileIDsDataItems items = new FileIDsDataItems(); @@ -714,10 +781,10 @@ private FileIDsData makeFileIDsDataWithGivenFileSize(String fileID, Long size) { res.setFileIDsDataItems(items); return res; } - + private List getChecksumResults(String fileID, String checksum) { List res = new ArrayList<>(); - + ChecksumDataForChecksumSpecTYPE csData = new ChecksumDataForChecksumSpecTYPE(); try { csData.setChecksumValue(Base16Utils.encodeBase16(checksum)); @@ -729,40 +796,40 @@ private List getChecksumResults(String fileID, res.add(csData); return res; } - + private FileIDsData getFileIDsData(String... fileIDs) { FileIDsData res = new FileIDsData(); FileIDsDataItems items = new FileIDsDataItems(); - - for(String fileID : fileIDs) { + + for (String fileID : fileIDs) { FileIDsDataItem dataItem = new FileIDsDataItem(); dataItem.setFileID(fileID); dataItem.setFileSize(BigInteger.valueOf(items.getFileIDsDataItem().size() + 1)); dataItem.setLastModificationTime(CalendarUtils.getNow()); items.getFileIDsDataItem().add(dataItem); - } - + } + res.setFileIDsDataItems(items); return res; } - + private IntegrityDAO createDAO() { DatabaseManager dm = new IntegrityDatabaseManager( settings.getReferenceSettings().getIntegrityServiceSettings().getIntegrityDatabase()); return new DerbyIntegrityDAO(dm.getConnector()); } - + /** - * This is not the way to handle the iterators, as the lists might grow really long. - * It's here to make the tests simple, and can be done as there's only small amounts of test data in the tests. + * This is not the way to handle the iterators, as the lists might grow really long. + * It's here to make the tests simple, and can be done as there's only small amounts of test data in the tests. */ private List getIssuesFromIterator(IntegrityIssueIterator it) { List issues = new ArrayList<>(); String issue = null; - while((issue = it.getNextIntegrityIssue()) != null) { + while ((issue = it.getNextIntegrityIssue()) != null) { issues.add(issue); } - + return issues; } } diff --git a/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/cache/IntegrityDBToolsTest.java b/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/cache/IntegrityDBToolsTest.java index b834bbd73..f302e2c13 100644 --- a/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/cache/IntegrityDBToolsTest.java +++ b/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/cache/IntegrityDBToolsTest.java @@ -5,16 +5,16 @@ * Copyright (C) 2010 - 2012 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% @@ -35,55 +35,58 @@ import org.bitrepository.integrityservice.cache.database.IntegrityDBTools; import org.bitrepository.service.database.DBConnector; import org.bitrepository.service.database.DatabaseManager; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; import java.math.BigInteger; import java.util.ArrayList; import java.util.List; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; public class IntegrityDBToolsTest extends IntegrityDatabaseTestCase { - String TEST_PILLAR_1 = "MY-TEST-PILLAR-1"; - String TEST_PILLAR_2 = "MY-TEST-PILLAR-2"; - String EXTRA_PILLAR = "MY-EXTRA-PILLAR"; - String EXTRA_COLLECTION = "extra-collection"; - String TEST_FILE_ID = "TEST-FILE-ID"; - String TEST_COLLECTIONID; - - @BeforeMethod (alwaysRun = true) + String testPillar1 = "MY-TEST-PILLAR-1"; + String testPillar2 = "MY-TEST-PILLAR-2"; + String extraCollectionId = "extra-collection"; + String testFileId = "TEST-FILE-ID"; + String testCollectionid; + + @BeforeEach @Override public void setup() throws Exception { super.setup(); - TEST_COLLECTIONID = settings.getRepositorySettings().getCollections().getCollection().get(0).getID(); + testCollectionid = settings.getRepositorySettings().getCollections().getCollection().get(0).getID(); } - - @Override + + @Override protected void customizeSettings() { - org.bitrepository.settings.repositorysettings.Collection c0 = + org.bitrepository.settings.repositorysettings.Collection c0 = settings.getRepositorySettings().getCollections().getCollection().get(0); c0.getPillarIDs().getPillarID().clear(); - c0.getPillarIDs().getPillarID().add(TEST_PILLAR_1); - c0.getPillarIDs().getPillarID().add(TEST_PILLAR_2); + c0.getPillarIDs().getPillarID().add(testPillar1); + c0.getPillarIDs().getPillarID().add(testPillar2); settings.getRepositorySettings().getCollections().getCollection().clear(); settings.getRepositorySettings().getCollections().getCollection().add(c0); - - org.bitrepository.settings.repositorysettings.Collection extraCollection = + + org.bitrepository.settings.repositorysettings.Collection extraCollection = new org.bitrepository.settings.repositorysettings.Collection(); - extraCollection.setID(EXTRA_COLLECTION); - org.bitrepository.settings.repositorysettings.PillarIDs pids - = new org.bitrepository.settings.repositorysettings.PillarIDs(); - pids.getPillarID().add(TEST_PILLAR_1); - pids.getPillarID().add(TEST_PILLAR_2); + extraCollection.setID(extraCollectionId); + org.bitrepository.settings.repositorysettings.PillarIDs pids + = new org.bitrepository.settings.repositorysettings.PillarIDs(); + pids.getPillarID().add(testPillar1); + pids.getPillarID().add(testPillar2); extraCollection.setPillarIDs(pids); settings.getRepositorySettings().getCollections().getCollection().add(extraCollection); } - - @Test(groups = {"regressiontest", "databasetest", "integritytest"}) + + @Test + @Tag("regressiontest") + @Tag("databasetest") + @Tag("integritytest") public void testAddCollectionSuccess() { addDescription("Tests that a new collection can be added to the integrity database"); String newCollectionID = "new-collectionid"; @@ -94,19 +97,22 @@ public void testAddCollectionSuccess() { IntegrityDBTools tool = new IntegrityDBTools(dbCon); List collections = integrityDAO.getCollections(); addStep("Extract initial list of collections", "The list contains the expected collections"); - assertTrue(collections.contains(TEST_COLLECTIONID)); - assertTrue(collections.contains(EXTRA_COLLECTION)); + assertTrue(collections.contains(testCollectionid)); + assertTrue(collections.contains(extraCollectionId)); assertFalse(collections.contains(newCollectionID)); - + addStep("Add the new collection", "The new collection is found in the list of collections"); tool.addCollection(newCollectionID); collections = integrityDAO.getCollections(); - assertTrue(collections.contains(TEST_COLLECTIONID)); - assertTrue(collections.contains(EXTRA_COLLECTION)); + assertTrue(collections.contains(testCollectionid)); + assertTrue(collections.contains(extraCollectionId)); assertTrue(collections.contains(newCollectionID)); } - - @Test(groups = {"regressiontest", "databasetest", "integritytest"}) + + @Test + @Tag("regressiontest") + @Tag("databasetest") + @Tag("integritytest") public void testAddExistingCollection() { addDescription("Tests that an existing collectionID cannot be added to the integrity database."); DatabaseManager dm = new IntegrityDatabaseManager( @@ -116,22 +122,25 @@ public void testAddExistingCollection() { IntegrityDBTools tool = new IntegrityDBTools(dbCon); List collections = integrityDAO.getCollections(); addStep("Extract initial list of collections.", "The list contains the expected collections."); - assertTrue(collections.contains(TEST_COLLECTIONID)); - assertTrue(collections.contains(EXTRA_COLLECTION)); - + assertTrue(collections.contains(testCollectionid)); + assertTrue(collections.contains(extraCollectionId)); + addStep("Attempt to add the new collection.", "An exception is thrown, and the collection list is uneffected."); try { - tool.addCollection(TEST_COLLECTIONID); + tool.addCollection(testCollectionid); fail("addCollection did not fail as expected"); - } catch(IntegrityDBStateException e) { - + } catch (IntegrityDBStateException e) { + } collections = integrityDAO.getCollections(); - assertTrue(collections.contains(TEST_COLLECTIONID)); - assertTrue(collections.contains(EXTRA_COLLECTION)); + assertTrue(collections.contains(testCollectionid)); + assertTrue(collections.contains(extraCollectionId)); } - - @Test(groups = {"regressiontest", "databasetest", "integritytest"}) + + @Test + @Tag("regressiontest") + @Tag("databasetest") + @Tag("integritytest") public void testRemoveNonExistingCollection() { addDescription("Tests that a non existing collection can't be removed from the integrity database."); String nonExistingCollectionID = "non-existing-collectionid"; @@ -142,8 +151,8 @@ public void testRemoveNonExistingCollection() { IntegrityDBTools tool = new IntegrityDBTools(dbCon); List collections = integrityDAO.getCollections(); addStep("Extract initial list of collections.", "The list contains the expected collections."); - assertTrue(collections.contains(TEST_COLLECTIONID)); - assertTrue(collections.contains(EXTRA_COLLECTION)); + assertTrue(collections.contains(testCollectionid)); + assertTrue(collections.contains(extraCollectionId)); assertFalse(collections.contains(nonExistingCollectionID)); addStep("Attempt to remove the non-existing collection.", "An exception is thrown, the collection list is uneffected."); @@ -151,14 +160,17 @@ public void testRemoveNonExistingCollection() { tool.removeCollection(nonExistingCollectionID); fail("removeCollection did not fail as expected"); } catch (IntegrityDBStateException e) { - + } collections = integrityDAO.getCollections(); - assertTrue(collections.contains(TEST_COLLECTIONID)); - assertTrue(collections.contains(EXTRA_COLLECTION)); + assertTrue(collections.contains(testCollectionid)); + assertTrue(collections.contains(extraCollectionId)); } - /*@Test(groups = {"regressiontest", "databasetest", "integritytest"}) + /*@Test + @Tag("regressiontest") + @Tag("databasetest") + @Tag("integritytest") public void testRemoveExistingCollection() { addDescription("Tests the removal of an existing collection and references to it in the integrity database"); DatabaseManager dm = new IntegrityDatabaseManager( @@ -216,12 +228,12 @@ public void testRemoveExistingCollection() { assertNotNull(integrityDAO.getLatestCollectionStats(EXTRA_COLLECTION, 1L)); assertFalse(integrityDAO.getLatestCollectionStats(EXTRA_COLLECTION, 1L).isEmpty()); }*/ - + private void populateCollection(IntegrityDAO dao, String collectionID) { - String file2 = TEST_FILE_ID + "-2"; - String file3 = TEST_FILE_ID + "-3"; - String file4 = TEST_FILE_ID + "-4"; - String file5 = TEST_FILE_ID + "-5"; + String file2 = testFileId + "-2"; + String file3 = testFileId + "-3"; + String file4 = testFileId + "-4"; + String file5 = testFileId + "-5"; Long size1 = 100L; Long size2 = 200L; Long size3 = 300L; @@ -233,12 +245,12 @@ private void populateCollection(IntegrityDAO dao, String collectionID) { String checksum3bad = "baad"; String checksum4 = "ccaa"; String checksum5 = "ddaa"; - FileIDsData data1 = makeFileIDsDataWithGivenFileSize(TEST_FILE_ID, size1); + FileIDsData data1 = makeFileIDsDataWithGivenFileSize(testFileId, size1); FileIDsData data2 = makeFileIDsDataWithGivenFileSize(file2, size2); FileIDsData data3 = makeFileIDsDataWithGivenFileSize(file3, size3); FileIDsData data4 = makeFileIDsDataWithGivenFileSize(file4, size4); FileIDsData data5 = makeFileIDsDataWithGivenFileSize(file5, size5); - List csData1 = getChecksumResults(TEST_FILE_ID, checksum1); + List csData1 = getChecksumResults(testFileId, checksum1); List csData2 = getChecksumResults(file2, checksum2); List csData3 = getChecksumResults(file3, checksum3); List csData3bad = getChecksumResults(file3, checksum3bad); @@ -255,20 +267,20 @@ private void populateCollection(IntegrityDAO dao, String collectionID) { csDataPillar2.addAll(csData2); csDataPillar2.addAll(csData3); csDataPillar2.addAll(csData4); - dao.updateFileIDs(data1, TEST_PILLAR_1, collectionID); - dao.updateFileIDs(data3, TEST_PILLAR_1, collectionID); - dao.updateFileIDs(data4, TEST_PILLAR_1, collectionID); - dao.updateFileIDs(data5, TEST_PILLAR_1, collectionID); - dao.updateFileIDs(data1, TEST_PILLAR_2, collectionID); - dao.updateFileIDs(data2, TEST_PILLAR_2, collectionID); - dao.updateFileIDs(data3, TEST_PILLAR_2, collectionID); - dao.updateFileIDs(data4, TEST_PILLAR_2, collectionID); + dao.updateFileIDs(data1, testPillar1, collectionID); + dao.updateFileIDs(data3, testPillar1, collectionID); + dao.updateFileIDs(data4, testPillar1, collectionID); + dao.updateFileIDs(data5, testPillar1, collectionID); + dao.updateFileIDs(data1, testPillar2, collectionID); + dao.updateFileIDs(data2, testPillar2, collectionID); + dao.updateFileIDs(data3, testPillar2, collectionID); + dao.updateFileIDs(data4, testPillar2, collectionID); + + dao.updateChecksums(csDataPillar1, testPillar1, collectionID); + dao.updateChecksums(csDataPillar2, testPillar2, collectionID); - dao.updateChecksums(csDataPillar1, TEST_PILLAR_1, collectionID); - dao.updateChecksums(csDataPillar2, TEST_PILLAR_2, collectionID); - } - + private FileIDsData makeFileIDsDataWithGivenFileSize(String fileID, Long size) { FileIDsData res = new FileIDsData(); FileIDsDataItems items = new FileIDsDataItems(); @@ -280,10 +292,10 @@ private FileIDsData makeFileIDsDataWithGivenFileSize(String fileID, Long size) { res.setFileIDsDataItems(items); return res; } - + private List getChecksumResults(String fileID, String checksum) { List res = new ArrayList<>(); - + ChecksumDataForChecksumSpecTYPE csData = new ChecksumDataForChecksumSpecTYPE(); try { csData.setChecksumValue(Base16Utils.encodeBase16(checksum)); diff --git a/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/cache/IntegrityDatabaseTest.java b/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/cache/IntegrityDatabaseTest.java index 593b6258c..5209574b7 100644 --- a/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/cache/IntegrityDatabaseTest.java +++ b/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/cache/IntegrityDatabaseTest.java @@ -1,23 +1,23 @@ /* * #%L * Bitrepository Integrity Client - * + * * $Id$ * $HeadURL$ * %% * Copyright (C) 2010 - 2012 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% @@ -35,9 +35,10 @@ import org.bitrepository.integrityservice.IntegrityDatabaseTestCase; import org.bitrepository.integrityservice.cache.database.IntegrityIssueIterator; import org.bitrepository.service.audit.AuditTrailManager; -import org.testng.Assert; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; import java.math.BigInteger; import java.util.ArrayList; @@ -52,23 +53,23 @@ public class IntegrityDatabaseTest extends IntegrityDatabaseTestCase { AuditTrailManager auditManager; String TEST_PILLAR_1 = "MY-TEST-PILLAR-1"; String TEST_PILLAR_2 = "MY-TEST-PILLAR-2"; - + String TEST_FILE_ID = "TEST-FILE-ID"; String TEST_CHECKSUM = "1234cccc4321"; - + String TEST_COLLECTIONID; - - @BeforeMethod (alwaysRun = true) + + @BeforeEach @Override public void setup() throws Exception { super.setup(); TEST_COLLECTIONID = settings.getRepositorySettings().getCollections().getCollection().get(0).getID(); auditManager = mock(AuditTrailManager.class); } - - @Override + + @Override protected void customizeSettings() { - org.bitrepository.settings.repositorysettings.Collection c0 = + org.bitrepository.settings.repositorysettings.Collection c0 = settings.getRepositorySettings().getCollections().getCollection().get(0); c0.getPillarIDs().getPillarID().clear(); c0.getPillarIDs().getPillarID().add(TEST_PILLAR_1); @@ -77,93 +78,108 @@ protected void customizeSettings() { settings.getRepositorySettings().getCollections().getCollection().add(c0); } - @Test(groups = {"regressiontest", "databasetest", "integritytest"}) + @Test + @Tag("regressiontest") + @Tag("databasetest") + @Tag("integritytest") public void instantiationTest() { addDescription("Tests that the connection can be instantaited."); IntegrityDatabase integrityCache = new IntegrityDatabase(settings); - Assert.assertNotNull(integrityCache); + Assertions.assertNotNull(integrityCache); } - @Test(groups = {"regressiontest", "databasetest", "integritytest"}) + @Test + @Tag("regressiontest") + @Tag("databasetest") + @Tag("integritytest") public void initialStateExtractionTest() { addDescription("Tests the initial state of the IntegrityModel. Should not contain any data."); IntegrityModel model = new IntegrityDatabase(settings); - + addStep("Test the 'findChecksumsOlderThan'", "Should deliver an empty collection"); Collection oldChecksums = getIssuesFromIterator(model.findChecksumsOlderThan( - new Date(0), TEST_PILLAR_1, TEST_COLLECTIONID)); - Assert.assertNotNull(oldChecksums); - Assert.assertEquals(oldChecksums.size(), 0); - + new Date(0), TEST_PILLAR_1, TEST_COLLECTIONID)); + Assertions.assertNotNull(oldChecksums); + Assertions.assertEquals(0, oldChecksums.size()); + addStep("Test the 'findMissingChecksums'", "Should deliver an empty collection"); - for(String pillar : SettingsUtils.getPillarIDsForCollection(TEST_COLLECTIONID)) { - Collection missingChecksums - = getIssuesFromIterator(model.findFilesWithMissingChecksum(TEST_COLLECTIONID, pillar, new Date(0))); - Assert.assertNotNull(missingChecksums); - Assert.assertEquals(missingChecksums.size(), 0); + for (String pillar : SettingsUtils.getPillarIDsForCollection(TEST_COLLECTIONID)) { + Collection missingChecksums + = getIssuesFromIterator(model.findFilesWithMissingChecksum(TEST_COLLECTIONID, pillar, new Date(0))); + Assertions.assertNotNull(missingChecksums); + Assertions.assertEquals(0, missingChecksums.size()); } - + addStep("Test the 'findMissingFiles'", "Should deliver an empty collection"); - Collection missingFiles = getIssuesFromIterator(model.findFilesWithMissingCopies(TEST_COLLECTIONID, + Collection missingFiles = getIssuesFromIterator(model.findFilesWithMissingCopies(TEST_COLLECTIONID, SettingsUtils.getPillarIDsForCollection(TEST_COLLECTIONID).size(), 0L, Long.MAX_VALUE)); - Assert.assertNotNull(missingFiles); - Assert.assertEquals(missingFiles.size(), 0); + Assertions.assertNotNull(missingFiles); + Assertions.assertEquals(0, missingFiles.size()); addStep("Test the 'getAllFileIDs'", "Should deliver an empty collection"); - Assert.assertEquals(model.getNumberOfFilesInCollection(TEST_COLLECTIONID), 0); - + Assertions.assertEquals(0, model.getNumberOfFilesInCollection(TEST_COLLECTIONID)); + addStep("Test the 'getFileInfos'", "Should deliver an empty collection"); Collection fileInfos = model.getFileInfos(TEST_FILE_ID, TEST_COLLECTIONID); - Assert.assertNotNull(fileInfos); - Assert.assertEquals(fileInfos.size(), 0); - + Assertions.assertNotNull(fileInfos); + Assertions.assertEquals(0, fileInfos.size()); + addStep("Test the 'getPillarCollectionMetrics'", "The set of metrics should be empty."); Map metrics = model.getPillarCollectionMetrics(TEST_COLLECTIONID); - Assert.assertTrue(metrics.isEmpty()); + Assertions.assertTrue(metrics.isEmpty()); } - - @Test(groups = {"regressiontest", "databasetest", "integritytest"}) + + @Test + @Tag("regressiontest") + @Tag("databasetest") + @Tag("integritytest") public void testIngestOfFileIDsData() { addDescription("Tests the ingesting of file ids data"); IntegrityModel model = new IntegrityDatabase(settings); - + addStep("Create data", "Should be ingested into the database"); FileIDsData data1 = getFileIDsData(TEST_FILE_ID); model.addFileIDs(data1, TEST_PILLAR_1, TEST_COLLECTIONID); model.addFileIDs(data1, TEST_PILLAR_2, TEST_COLLECTIONID); - + addStep("Extract the data", "Should be identical to the ingested data"); Collection fileinfos = model.getFileInfos(TEST_FILE_ID, TEST_COLLECTIONID); - Assert.assertNotNull(fileinfos); - for(FileInfo fi : fileinfos) { - Assert.assertEquals(fi.getFileId(), TEST_FILE_ID); - Assert.assertNull(fi.getChecksum()); - Assert.assertEquals(fi.getDateForLastChecksumCheck(), CalendarUtils.getEpoch()); - Assert.assertEquals(fi.getDateForLastFileIDCheck(), data1.getFileIDsDataItems().getFileIDsDataItem().get(0).getLastModificationTime()); + Assertions.assertNotNull(fileinfos); + for (FileInfo fi : fileinfos) { + Assertions.assertEquals(fi.getFileId(), TEST_FILE_ID); + Assertions.assertNull(fi.getChecksum()); + Assertions.assertEquals(fi.getDateForLastChecksumCheck(), CalendarUtils.getEpoch()); + Assertions.assertEquals(fi.getDateForLastFileIDCheck(), data1.getFileIDsDataItems().getFileIDsDataItem().get(0).getLastModificationTime()); } } - @Test(groups = {"regressiontest", "databasetest", "integritytest"}) + @Test + @Tag("regressiontest") + @Tag("databasetest") + @Tag("integritytest") public void testIngestOfChecksumsData() { addDescription("Tests the ingesting of checksums data"); IntegrityModel model = new IntegrityDatabase(settings); - + addStep("Create data", "Should be ingested into the database"); List csData = getChecksumResults(TEST_FILE_ID, TEST_CHECKSUM); insertChecksumDataForModel(model, csData, TEST_PILLAR_1, TEST_COLLECTIONID); insertChecksumDataForModel(model, csData, TEST_PILLAR_2, TEST_COLLECTIONID); - + addStep("Extract the data", "Should be identical to the ingested data"); Collection fileinfos = model.getFileInfos(TEST_FILE_ID, TEST_COLLECTIONID); - Assert.assertNotNull(fileinfos); - for(FileInfo fi : fileinfos) { - Assert.assertEquals(fi.getFileId(), TEST_FILE_ID); - Assert.assertEquals(fi.getChecksum(), TEST_CHECKSUM); - Assert.assertEquals(fi.getDateForLastChecksumCheck(), csData.get(0).getCalculationTimestamp()); + Assertions.assertNotNull(fileinfos); + for (FileInfo fi : fileinfos) { + Assertions.assertEquals(fi.getFileId(), TEST_FILE_ID); + Assertions.assertEquals(fi.getChecksum(), TEST_CHECKSUM); + Assertions.assertEquals(fi.getDateForLastChecksumCheck(), csData.get(0).getCalculationTimestamp()); } } - - @Test(groups = {"regressiontest", "databasetest", "integritytest"}) + + @Test + @Tag("regressiontest") + @Tag("databasetest") + @Tag("integritytest") public void testDeletingEntry() { addDescription("Tests the deletion of an FileID entry."); IntegrityModel model = new IntegrityDatabase(settings); @@ -172,25 +188,25 @@ public void testDeletingEntry() { FileIDsData data1 = getFileIDsData(TEST_FILE_ID); model.addFileIDs(data1, TEST_PILLAR_1, TEST_COLLECTIONID); model.addFileIDs(data1, TEST_PILLAR_2, TEST_COLLECTIONID); - + Collection fileinfos = model.getFileInfos(TEST_FILE_ID, TEST_COLLECTIONID); - Assert.assertNotNull(fileinfos); - Assert.assertEquals(fileinfos.size(), 2); - + Assertions.assertNotNull(fileinfos); + Assertions.assertEquals(2, fileinfos.size()); + addStep("Delete the entry", "No fileinfos should be extracted."); model.deleteFileIdEntry(TEST_COLLECTIONID, TEST_PILLAR_1, TEST_FILE_ID); fileinfos = model.getFileInfos(TEST_FILE_ID, TEST_COLLECTIONID); - Assert.assertNotNull(fileinfos); - Assert.assertEquals(fileinfos.size(), 1); + Assertions.assertNotNull(fileinfos); + Assertions.assertEquals(1, fileinfos.size()); model.deleteFileIdEntry(TEST_COLLECTIONID, TEST_PILLAR_2, TEST_FILE_ID); fileinfos = model.getFileInfos(TEST_FILE_ID, TEST_COLLECTIONID); - Assert.assertNotNull(fileinfos); - Assert.assertEquals(fileinfos.size(), 0); + Assertions.assertNotNull(fileinfos); + Assertions.assertEquals(0, fileinfos.size()); } - + private List getChecksumResults(String fileID, String checksum) { List res = new ArrayList<>(); - + ChecksumDataForChecksumSpecTYPE csData = new ChecksumDataForChecksumSpecTYPE(); try { csData.setChecksumValue(Base16Utils.encodeBase16(checksum)); @@ -202,34 +218,34 @@ private List getChecksumResults(String fileID, res.add(csData); return res; } - + private FileIDsData getFileIDsData(String... fileIDs) { FileIDsData res = new FileIDsData(); FileIDsDataItems items = new FileIDsDataItems(); - - for(String fileID : fileIDs) { + + for (String fileID : fileIDs) { FileIDsDataItem dataItem = new FileIDsDataItem(); dataItem.setFileID(fileID); dataItem.setFileSize(BigInteger.valueOf(items.getFileIDsDataItem().size() + 1)); dataItem.setLastModificationTime(CalendarUtils.getNow()); items.getFileIDsDataItem().add(dataItem); - } - + } + res.setFileIDsDataItems(items); return res; } - + /** - * This is not the way to handle the iterators, as the lists might grow really long. - * It's here to make the tests simple, and can be done as there's only small amounts of test data in the tests. + * This is not the way to handle the iterators, as the lists might grow really long. + * It's here to make the tests simple, and can be done as there's only small amounts of test data in the tests. */ private List getIssuesFromIterator(IntegrityIssueIterator it) { List issues = new ArrayList<>(); String issue; - while((issue = it.getNextIntegrityIssue()) != null) { + while ((issue = it.getNextIntegrityIssue()) != null) { issues.add(issue); } - + return issues; } } diff --git a/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/checking/MaxChecksumAgeProviderTest.java b/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/checking/MaxChecksumAgeProviderTest.java index 93fd86f83..9de994dd0 100644 --- a/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/checking/MaxChecksumAgeProviderTest.java +++ b/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/checking/MaxChecksumAgeProviderTest.java @@ -23,25 +23,27 @@ import org.bitrepository.settings.referencesettings.ObsoleteChecksumSettings; import org.jaccept.structure.ExtendedTestCase; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; import javax.xml.datatype.DatatypeConfigurationException; import javax.xml.datatype.DatatypeFactory; import java.time.Duration; -import static org.testng.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; public class MaxChecksumAgeProviderTest extends ExtendedTestCase{ DatatypeFactory factory; - @BeforeMethod(alwaysRun = true) + @BeforeEach public void setUpFactory() throws DatatypeConfigurationException { factory = DatatypeFactory.newInstance(); } - @Test(groups = {"regressiontest", "integritytest"}) + @Test + @Tag("regressiontest") @Tag("integritytest") public void testNoSettings() { addDescription("Test the MaxChecksumAge when no settings are defined"); addStep("Create a MaxChecksumAgeProvider with null settings and a default MaxAge of 100", @@ -52,7 +54,9 @@ public void testNoSettings() { assertEquals(maxChecksumAgeProvider.getMaxChecksumAge(""), defaultMaxAge); } - @Test(groups = {"regressiontest", "integritytest"}) + @Test + @Tag("regressiontest") + @Tag("integritytest") public void testNoPillarSpecificSetting() { addDescription("Test the MaxChecksumAge when no settings are defined for the specific pillar"); @@ -66,7 +70,9 @@ public void testNoPillarSpecificSetting() { assertEquals(maxChecksumAgeProvider.getMaxChecksumAge(""), Duration.ofMillis(10)); } - @Test(groups = {"regressiontest", "integritytest"}) + @Test + @Tag("regressiontest") + @Tag("integritytest") public void testPillarSpecificSetting() { addDescription("Test the MaxChecksumAge when a value has been defined for specific pillars"); diff --git a/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/collector/IntegrityInformationCollectorTest.java b/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/collector/IntegrityInformationCollectorTest.java index 8a379491d..b6f824628 100644 --- a/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/collector/IntegrityInformationCollectorTest.java +++ b/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/collector/IntegrityInformationCollectorTest.java @@ -33,10 +33,11 @@ import org.bitrepository.client.eventhandler.EventHandler; import org.bitrepository.modify.putfile.PutFileClient; import org.jaccept.structure.ExtendedTestCase; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; import java.net.URL; -import java.util.Arrays; +import java.util.List; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyLong; @@ -56,12 +57,13 @@ public class IntegrityInformationCollectorTest extends ExtendedTestCase { public final static String collectionID = "dummy-collection"; public final static String fileId = "FILE_ID"; - @Test(groups = {"regressiontest", "integritytest"}) + @Test + @Tag("regressiontest") @Tag("integritytest") public void testCollectorGetFileIDs() throws Exception { addDescription("Tests that the collector calls the GetFileClient"); addStep("Define variables", "No errors"); String pillarID = "TEST-PILLAR"; - ContributorQuery[] contributorQueries = ContributorQueryUtils.createFullContributorQuery(Arrays.asList(pillarID)); + ContributorQuery[] contributorQueries = ContributorQueryUtils.createFullContributorQuery(List.of(pillarID)); String auditTrailInformation = "audit trail for this test"; addStep("Setup a GetFileIDsClient for test purpose.", "Should be OK."); @@ -70,29 +72,30 @@ public void testCollectorGetFileIDs() throws Exception { EventHandler eventHandler = mock(EventHandler.class); addStep("Call the getFileIDs on the collector.", "Should go directly to the GetFileIDsClient"); - collector.getFileIDs(collectionID, Arrays.asList(pillarID), auditTrailInformation, contributorQueries, eventHandler); + collector.getFileIDs(collectionID, List.of(pillarID), auditTrailInformation, contributorQueries, eventHandler); verify(getFileIDsClient).getFileIDs(eq(collectionID), any(), any(), any(), any(EventHandler.class)); addStep("Call the getFileIDs on the collector four times more.", "The GetFileIDsClient should have been called 5 times."); - collector.getFileIDs(collectionID, Arrays.asList(pillarID), auditTrailInformation, contributorQueries, null); - collector.getFileIDs(collectionID, Arrays.asList(pillarID), auditTrailInformation, contributorQueries, null); - collector.getFileIDs(collectionID, Arrays.asList(pillarID), auditTrailInformation, contributorQueries, null); - collector.getFileIDs(collectionID, Arrays.asList(pillarID), auditTrailInformation, contributorQueries, null); + collector.getFileIDs(collectionID, List.of(pillarID), auditTrailInformation, contributorQueries, null); + collector.getFileIDs(collectionID, List.of(pillarID), auditTrailInformation, contributorQueries, null); + collector.getFileIDs(collectionID, List.of(pillarID), auditTrailInformation, contributorQueries, null); + collector.getFileIDs(collectionID, List.of(pillarID), auditTrailInformation, contributorQueries, null); verify(getFileIDsClient, times(5)).getFileIDs(eq(collectionID), any(), any(), any(), any()); verifyNoMoreInteractions(getFileIDsClient); verifyNoMoreInteractions(eventHandler); } - @Test(groups = {"regressiontest", "integritytest"}) + @Test + @Tag("regressiontest") @Tag("integritytest") public void testCollectorGetChecksums() throws Exception { addDescription("Tests that the collector calls the GetChecksumsClient"); addStep("Define variables", "No errors"); String pillarID = "TEST-PILLAR"; ContributorQuery[] contributorQueries = ContributorQueryUtils.createFullContributorQuery( - Arrays.asList(pillarID)); + List.of(pillarID)); ChecksumSpecTYPE csType = new ChecksumSpecTYPE(); csType.setChecksumType(ChecksumType.MD5); String auditTrailInformation = "audit trail for this test"; @@ -104,15 +107,15 @@ public void testCollectorGetChecksums() throws Exception { EventHandler eventHandler = mock(EventHandler.class); addStep("Call the getChecksumsClient on the collector.", "Should go directly to the GetChecksumsClient"); - collector.getChecksums(collectionID, Arrays.asList(pillarID), csType, null, auditTrailInformation, contributorQueries, eventHandler); + collector.getChecksums(collectionID, List.of(pillarID), csType, null, auditTrailInformation, contributorQueries, eventHandler); verify(getChecksumsClient).getChecksums(eq(collectionID), any(), any(), any(ChecksumSpecTYPE.class), any(), any(EventHandler.class), anyString()); addStep("Call the getChecksumsClient on the collector four times more.", "The GetChecksumsClient should have been called 5 times."); - collector.getChecksums(collectionID, Arrays.asList(pillarID), csType, null, auditTrailInformation, contributorQueries, null); - collector.getChecksums(collectionID, Arrays.asList(pillarID), csType, null, auditTrailInformation, contributorQueries, null); - collector.getChecksums(collectionID, Arrays.asList(pillarID), csType, null, auditTrailInformation, contributorQueries, null); - collector.getChecksums(collectionID, Arrays.asList(pillarID), csType, null, auditTrailInformation, contributorQueries, null); + collector.getChecksums(collectionID, List.of(pillarID), csType, null, auditTrailInformation, contributorQueries, null); + collector.getChecksums(collectionID, List.of(pillarID), csType, null, auditTrailInformation, contributorQueries, null); + collector.getChecksums(collectionID, List.of(pillarID), csType, null, auditTrailInformation, contributorQueries, null); + collector.getChecksums(collectionID, List.of(pillarID), csType, null, auditTrailInformation, contributorQueries, null); verify(getChecksumsClient, times(5)).getChecksums(eq(collectionID), any(), any(), any(ChecksumSpecTYPE.class), any(), any(), anyString()); @@ -121,7 +124,8 @@ public void testCollectorGetChecksums() throws Exception { } - @Test(groups = {"regressiontest", "integritytest"}) + @Test + @Tag("regressiontest") @Tag("integritytest") public void testCollectorGetFile() throws Exception { addDescription("Tests that the collector calls the GetFileClient"); addStep("Define variables", "No errors"); @@ -149,7 +153,8 @@ public void testCollectorGetFile() throws Exception { verifyNoMoreInteractions(eventHandler); } - @Test(groups = {"regressiontest", "integritytest"}) + @Test + @Tag("regressiontest") @Tag("integritytest") public void testCollectorPutFile() throws Exception { addDescription("Tests that the collector calls the PutFileClient"); addStep("Define variables", "No errors"); @@ -180,13 +185,14 @@ public void testCollectorPutFile() throws Exception { verifyNoMoreInteractions(eventHandler); } - @Test(groups = {"regressiontest", "integritytest"}) + @Test + @Tag("regressiontest") @Tag("integritytest") public void testCollectorHandleChecksumClientFailures() throws Exception { addDescription("Test that the IntegrityInformationCollector works as a fault-barrier."); addStep("Setup variables for the test", "Should be OK"); String pillarID = "TEST-PILLAR"; ContributorQuery[] contributorQueries = ContributorQueryUtils.createFullContributorQuery( - Arrays.asList(pillarID)); + List.of(pillarID)); ChecksumSpecTYPE csType = new ChecksumSpecTYPE(); csType.setChecksumType(ChecksumType.MD5); String auditTrailInformation = "audit trail for this test"; @@ -199,16 +205,17 @@ public void testCollectorHandleChecksumClientFailures() throws Exception { addStep("Verify that the collector does not fail, just because the GetChecksumClient does so", "Should not throw an unexpected exception"); - collector.getChecksums(collectionID, Arrays.asList(pillarID), csType, null, auditTrailInformation, contributorQueries, null); + collector.getChecksums(collectionID, List.of(pillarID), csType, null, auditTrailInformation, contributorQueries, null); } - @Test(groups = {"regressiontest", "integritytest"}) + @Test + @Tag("regressiontest") @Tag("integritytest") public void testCollectorHandleGetFileIDsClientFailures() throws Exception { addDescription("Test that the IntegrityInformationCollector works as a fault-barrier."); addStep("Setup variables for the test", "Should be OK"); String pillarID = "TEST-PILLAR"; ContributorQuery[] contributorQueries = ContributorQueryUtils.createFullContributorQuery( - Arrays.asList(pillarID)); + List.of(pillarID)); String auditTrailInformation = "audit trail for this test"; addStep("Setup a DyingGetFileIDsClient for test purpose.", "Should be OK."); @@ -218,10 +225,11 @@ public void testCollectorHandleGetFileIDsClientFailures() throws Exception { addStep("Verify that the collector does not fail, just because the GetChecksumClient does so", "Should not throw an unexpected exception"); - collector.getFileIDs(collectionID, Arrays.asList(pillarID), auditTrailInformation, contributorQueries, null); + collector.getFileIDs(collectionID, List.of(pillarID), auditTrailInformation, contributorQueries, null); } - @Test(groups = {"regressiontest", "integritytest"}) + @Test + @Tag("regressiontest") @Tag("integritytest") public void testCollectorHandleGetFileClientFailures() throws Exception { addDescription("Test that the IntegrityInformationCollector works as a fault-barrier."); addStep("Define variables", "No errors"); @@ -241,7 +249,8 @@ public void testCollectorHandleGetFileClientFailures() throws Exception { collector.getFile(collectionID, fileId, uploadUrl, eventHandler, auditTrailInformation); } - @Test(groups = {"regressiontest", "integritytest"}) + @Test + @Tag("regressiontest") @Tag("integritytest") public void testCollectorHandlePutFileClientFailures() throws Exception { addDescription("Test that the IntegrityInformationCollector works as a fault-barrier."); addStep("Define variables", "No errors"); diff --git a/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/integrationtest/MissingChecksumTests.java b/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/integrationtest/MissingChecksumTests.java index ac9f83e44..574fd2be0 100644 --- a/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/integrationtest/MissingChecksumTests.java +++ b/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/integrationtest/MissingChecksumTests.java @@ -5,16 +5,16 @@ * Copyright (C) 2010 - 2013 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% @@ -55,8 +55,9 @@ import org.bitrepository.service.database.DerbyDatabaseDestroyer; import org.bitrepository.service.exception.WorkflowAbortedException; import org.jaccept.structure.ExtendedTestCase; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; import javax.xml.datatype.DatatypeFactory; import javax.xml.datatype.Duration; @@ -69,6 +70,7 @@ import java.util.List; import java.util.Map; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; @@ -77,12 +79,12 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; -import static org.testng.Assert.assertEquals; + public class MissingChecksumTests extends ExtendedTestCase { private static final String PILLAR_1 = "pillar1"; private static final String PILLAR_2 = "pillar2"; - + private static final String DEFAULT_CHECKSUM = "0123456789"; private static final String TEST_FILE_1 = "test-file-1"; private String TEST_COLLECTION; @@ -92,10 +94,10 @@ public class MissingChecksumTests extends ExtendedTestCase { protected IntegrityAlerter alerter; protected IntegrityModel model; protected IntegrityContributors integrityContributors; - + IntegrityReporter reporter; - - @BeforeMethod (alwaysRun = true) + + @BeforeEach public void setup() throws Exception { settings = TestSettingsProvider.reloadSettings("IntegrityCheckingUnderTest"); @@ -104,7 +106,7 @@ public void setup() throws Exception { IntegrityDatabaseCreator integrityDatabaseCreator = new IntegrityDatabaseCreator(); integrityDatabaseCreator.createIntegrityDatabase(settings, null); - + settings.getRepositorySettings().getCollections().getCollection().get(0).getPillarIDs().getPillarID().clear(); settings.getRepositorySettings().getCollections().getCollection().get(0).getPillarIDs().getPillarID().add(PILLAR_1); settings.getRepositorySettings().getCollections().getCollection().get(0).getPillarIDs().getPillarID().add(PILLAR_2); @@ -113,18 +115,20 @@ public void setup() throws Exception { settings.getReferenceSettings().getIntegrityServiceSettings().setTimeBeforeMissingFileCheck(time); TEST_COLLECTION = settings.getRepositorySettings().getCollections().getCollection().get(0).getID(); SettingsUtils.initialize(settings); - + collector = mock(IntegrityInformationCollector.class); alerter = mock(IntegrityAlerter.class); model = new IntegrityDatabase(settings); - + reporter = mock(IntegrityReporter.class); integrityContributors = mock(IntegrityContributors.class); - + SettingsUtils.initialize(settings); } - @Test(groups = {"regressiontest", "integritytest"}) + @Test + @Tag("regressiontest") + @Tag("integritytest") public void testMissingChecksumAndStep() throws Exception { addDescription("Test that files initially are set to checksum-state unknown, and to missing in the " + "missing checksum step."); @@ -133,22 +137,24 @@ public void testMissingChecksumAndStep() throws Exception { addStep("Run missing checksum step.", "The file should be marked as missing at all pillars."); doAnswer(invocation -> TEST_COLLECTION).when(reporter).getCollectionID(); - + StatisticsCollector cs = new StatisticsCollector(TEST_COLLECTION); - HandleMissingChecksumsStep missingChecksumStep = new HandleMissingChecksumsStep(model, reporter, cs, new Date(0)); + HandleMissingChecksumsStep missingChecksumStep = new HandleMissingChecksumsStep(model, reporter, cs, new Date(0)); missingChecksumStep.performStep(); - for(String pillar : SettingsUtils.getPillarIDsForCollection(TEST_COLLECTION)) { - assertEquals((long) cs.getPillarCollectionStat(pillar).getMissingChecksums(), 1); + for (String pillar : SettingsUtils.getPillarIDsForCollection(TEST_COLLECTION)) { + assertEquals(1, (long) cs.getPillarCollectionStat(pillar).getMissingChecksums()); } } - @Test(groups = {"regressiontest", "integritytest"}) + @Test + @Tag("regressiontest") + @Tag("integritytest") public void testMissingChecksumForFirstGetChecksums() throws WorkflowAbortedException { addDescription("Test that checksums are set to missing, when not found during GetChecksum."); addStep("Ingest file to database", ""); Date testStart = new Date(); populateDatabase(model, TEST_FILE_1); - + addStep("Add checksum results for only one pillar.", ""); final ResultingChecksums resultingChecksums = createResultingChecksums(TEST_FILE_1); doAnswer(invocation -> { @@ -163,38 +169,40 @@ public void testMissingChecksumForFirstGetChecksums() throws WorkflowAbortedExce any(ContributorQuery[].class), any(EventHandler.class)); when(integrityContributors.getActiveContributors()) - .thenReturn(new HashSet<>(Arrays.asList(PILLAR_1, PILLAR_2))).thenReturn(new HashSet<>()); - - UpdateChecksumsStep step = new FullUpdateChecksumsStep(collector, model, alerter, createChecksumSpecTYPE(), + .thenReturn(new HashSet<>(Arrays.asList(PILLAR_1, PILLAR_2))).thenReturn(new HashSet<>()); + + UpdateChecksumsStep step = new FullUpdateChecksumsStep(collector, model, alerter, createChecksumSpecTYPE(), settings, TEST_COLLECTION, integrityContributors); step.performStep(); verify(collector).getChecksums(eq(TEST_COLLECTION), any(), any(ChecksumSpecTYPE.class), any(), anyString(), any(ContributorQuery[].class), any(EventHandler.class)); verifyNoMoreInteractions(alerter); - + addStep("Check whether checksum is missing", "Should be missing at pillar two only."); Map metrics = model.getPillarCollectionMetrics(TEST_COLLECTION); - assertEquals(metrics.get(PILLAR_1).getPillarFileCount(), 1); - assertEquals(metrics.get(PILLAR_2).getPillarFileCount(), 1); - + assertEquals(1, metrics.get(PILLAR_1).getPillarFileCount()); + assertEquals(1, metrics.get(PILLAR_2).getPillarFileCount()); + List missingChecksumsPillar1 - = getIssuesFromIterator(model.findFilesWithMissingChecksum(TEST_COLLECTION, PILLAR_1, testStart)); - assertEquals(missingChecksumsPillar1.size(), 0); - - List missingChecksumsPillar2 - = getIssuesFromIterator(model.findFilesWithMissingChecksum(TEST_COLLECTION, PILLAR_2, testStart)); - assertEquals(missingChecksumsPillar2.size(), 1); - assertEquals(missingChecksumsPillar2.get(0), TEST_FILE_1); + = getIssuesFromIterator(model.findFilesWithMissingChecksum(TEST_COLLECTION, PILLAR_1, testStart)); + assertEquals(0, missingChecksumsPillar1.size()); + + List missingChecksumsPillar2 + = getIssuesFromIterator(model.findFilesWithMissingChecksum(TEST_COLLECTION, PILLAR_2, testStart)); + assertEquals(1, missingChecksumsPillar2.size()); + assertEquals(TEST_FILE_1, missingChecksumsPillar2.get(0)); } - @Test(groups = {"regressiontest", "integritytest"}) + @Test + @Tag("regressiontest") + @Tag("integritytest") public void testMissingChecksumDuringSecondIngest() throws WorkflowAbortedException { addDescription("Test that checksums are set to missing, when not found during GetChecksum, " + "even though they have been found before."); addStep("Ingest file to database", ""); Date testStart = new Date(); populateDatabase(model, TEST_FILE_1); - + addStep("Add checksum results for both pillar.", ""); final ResultingChecksums resultingChecksums = createResultingChecksums(TEST_FILE_1); doAnswer(invocation -> { @@ -209,28 +217,28 @@ public void testMissingChecksumDuringSecondIngest() throws WorkflowAbortedExcept }).when(collector).getChecksums( eq(TEST_COLLECTION), any(), any(ChecksumSpecTYPE.class), any(), anyString(), any(ContributorQuery[].class), any(EventHandler.class)); - + when(integrityContributors.getActiveContributors()) - .thenReturn(new HashSet<>(Arrays.asList(PILLAR_1, PILLAR_2))).thenReturn(new HashSet<>()); - - UpdateChecksumsStep step1 = new FullUpdateChecksumsStep(collector, model, alerter, createChecksumSpecTYPE(), + .thenReturn(new HashSet<>(Arrays.asList(PILLAR_1, PILLAR_2))).thenReturn(new HashSet<>()); + + UpdateChecksumsStep step1 = new FullUpdateChecksumsStep(collector, model, alerter, createChecksumSpecTYPE(), settings, TEST_COLLECTION, integrityContributors); step1.performStep(); verify(collector).getChecksums(eq(TEST_COLLECTION), any(), any(ChecksumSpecTYPE.class), any(), anyString(), any(ContributorQuery[].class), any(EventHandler.class)); verifyNoMoreInteractions(alerter); - + addStep("Check whether checksum is missing", "Should be missing at pillar two only."); Map metrics = model.getPillarCollectionMetrics(TEST_COLLECTION); - assertEquals(metrics.get(PILLAR_1).getPillarFileCount(), 1); - assertEquals(metrics.get(PILLAR_2).getPillarFileCount(), 1); - - for(String pillar : Arrays.asList(PILLAR_1, PILLAR_2)) { - List missingChecksums - = getIssuesFromIterator(model.findFilesWithMissingChecksum(TEST_COLLECTION, pillar, testStart)); - assertEquals(missingChecksums.size(), 0); + assertEquals(1, metrics.get(PILLAR_1).getPillarFileCount()); + assertEquals(1, metrics.get(PILLAR_2).getPillarFileCount()); + + for (String pillar : Arrays.asList(PILLAR_1, PILLAR_2)) { + List missingChecksums + = getIssuesFromIterator(model.findFilesWithMissingChecksum(TEST_COLLECTION, pillar, testStart)); + assertEquals(0, missingChecksums.size()); } - + addStep("Add checksum results for only the second pillar.", ""); doAnswer(invocation -> { EventHandler eventHandler = (EventHandler) invocation.getArguments()[6]; @@ -244,32 +252,32 @@ public void testMissingChecksumDuringSecondIngest() throws WorkflowAbortedExcept anyString(), any(ContributorQuery[].class), any(EventHandler.class)); when(integrityContributors.getActiveContributors()) - .thenReturn(new HashSet<>(Arrays.asList(PILLAR_1, PILLAR_2))).thenReturn(new HashSet<>()); - + .thenReturn(new HashSet<>(Arrays.asList(PILLAR_1, PILLAR_2))).thenReturn(new HashSet<>()); + Date secondUpdate = new Date(); - UpdateChecksumsStep step2 = new FullUpdateChecksumsStep(collector, model, alerter, createChecksumSpecTYPE(), + UpdateChecksumsStep step2 = new FullUpdateChecksumsStep(collector, model, alerter, createChecksumSpecTYPE(), settings, TEST_COLLECTION, integrityContributors); step2.performStep(); verifyNoMoreInteractions(alerter); - + addStep("Check whether checksum is missing", "Should be missing at pillar one, and not on pillar two."); metrics = model.getPillarCollectionMetrics(TEST_COLLECTION); - assertEquals(metrics.get(PILLAR_1).getPillarFileCount(), 1); - assertEquals(metrics.get(PILLAR_2).getPillarFileCount(), 1); - - List missingChecksumsPillar1 - = getIssuesFromIterator(model.findFilesWithMissingChecksum(TEST_COLLECTION, PILLAR_1, secondUpdate)); - assertEquals(missingChecksumsPillar1.size(), 1); - List missingChecksumsPillar2 - = getIssuesFromIterator(model.findFilesWithMissingChecksum(TEST_COLLECTION, PILLAR_2, secondUpdate)); - assertEquals(missingChecksumsPillar2.size(), 0); + assertEquals(1, metrics.get(PILLAR_1).getPillarFileCount()); + assertEquals(1, metrics.get(PILLAR_2).getPillarFileCount()); + + List missingChecksumsPillar1 + = getIssuesFromIterator(model.findFilesWithMissingChecksum(TEST_COLLECTION, PILLAR_1, secondUpdate)); + assertEquals(1, missingChecksumsPillar1.size()); + List missingChecksumsPillar2 + = getIssuesFromIterator(model.findFilesWithMissingChecksum(TEST_COLLECTION, PILLAR_2, secondUpdate)); + assertEquals(0, missingChecksumsPillar2.size()); } - - protected void populateDatabase(IntegrityModel model, String ... files) { + + protected void populateDatabase(IntegrityModel model, String... files) { FileIDsData data = new FileIDsData(); FileIDsDataItems items = new FileIDsDataItems(); XMLGregorianCalendar lastModificationTime = CalendarUtils.getNow(); - for(String f : files) { + for (String f : files) { FileIDsDataItem item = new FileIDsDataItem(); item.setFileID(f); item.setFileSize(BigInteger.ONE); @@ -281,16 +289,16 @@ protected void populateDatabase(IntegrityModel model, String ... files) { model.addFileIDs(data, PILLAR_1, collectionID); model.addFileIDs(data, PILLAR_2, collectionID); } - + private ResultingChecksums createResultingChecksums(String... fileIDs) { ResultingChecksums res = new ResultingChecksums(); res.getChecksumDataItems().addAll(createChecksumData(fileIDs)); return res; } - + private List createChecksumData(String... fileIDs) { List res = new ArrayList<>(); - for(String fileID : fileIDs) { + for (String fileID : fileIDs) { ChecksumDataForChecksumSpecTYPE csData = new ChecksumDataForChecksumSpecTYPE(); csData.setCalculationTimestamp(CalendarUtils.getNow()); try { @@ -311,16 +319,16 @@ private ChecksumSpecTYPE createChecksumSpecTYPE() { } /** - * This is not the way to handle the iterators, as the lists might grow really long. - * It's here to make the tests simple, and can be done as there's only small amounts of test data in the tests. + * This is not the way to handle the iterators, as the lists might grow really long. + * It's here to make the tests simple, and can be done as there's only small amounts of test data in the tests. */ private List getIssuesFromIterator(IntegrityIssueIterator it) { List issues = new ArrayList<>(); String issue; - while((issue = it.getNextIntegrityIssue()) != null) { + while ((issue = it.getNextIntegrityIssue()) != null) { issues.add(issue); } - + return issues; } } diff --git a/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/reports/BasicIntegrityReporterTest.java b/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/reports/BasicIntegrityReporterTest.java index c39fb3183..1b6bdc128 100644 --- a/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/reports/BasicIntegrityReporterTest.java +++ b/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/reports/BasicIntegrityReporterTest.java @@ -5,16 +5,16 @@ * Copyright (C) 2010 - 2012 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% @@ -23,67 +23,75 @@ package org.bitrepository.integrityservice.reports; import org.jaccept.structure.ExtendedTestCase; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; import java.io.File; -import static org.testng.AssertJUnit.assertEquals; -import static org.testng.AssertJUnit.assertFalse; -import static org.testng.AssertJUnit.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; public class BasicIntegrityReporterTest extends ExtendedTestCase { private static final String REPORT_SUMMARY_START = "The following integrity issues were found:\n"; - @Test(groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public void deletedFilesTest() throws Exception { addDescription("Verifies that the hasIntegrityIssues() reports deleted files correctly"); - addStep("Report a delete file for a new Reporter", "hasIntegrityIssues() should return false and the summary " + - "report should inform that no issues where found."); - BasicIntegrityReporter reporter = new BasicIntegrityReporter("CollectionWithIssues", "test", new File("target/")); + addStep("Report a delete file for a new Reporter", + "hasIntegrityIssues() should return false and the summary " + + "report should inform that no issues where found."); + BasicIntegrityReporter reporter = new BasicIntegrityReporter( + "CollectionWithIssues", "test", new File("target/")); reporter.reportDeletedFile("TestFile", "Pillar1"); - assertFalse("Reporter interpreted delete file as a integrity issue", reporter.hasIntegrityIssues()); + assertFalse(reporter.hasIntegrityIssues(), "Reporter interpreted delete file as a integrity issue"); String expectedReport = "No integrity issues found"; - assertEquals("Reporter didn't create clean report", expectedReport, reporter.generateSummaryOfReport()); + assertEquals(expectedReport, reporter.generateSummaryOfReport(), + "Reporter didn't create clean report"); reporter.generateReport(); } - @Test(groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public void noIntegrityIssuesTest() { addDescription("Verifies that missing files are reported correctly"); addStep("Create a clean reporter", "hasIntegrityIssues() should return false and the summary report should " + "state that no inform of the missing file."); BasicIntegrityReporter reporter = new BasicIntegrityReporter("CollectionWithoutIssues", "test", new File("target/")); - assertFalse("Reporter interpreted delete file as a integrity issue", reporter.hasIntegrityIssues()); + assertFalse(reporter.hasIntegrityIssues(), "Reporter interpreted delete file as a integrity issue"); String expectedReport = "No integrity issues found"; - assertEquals("Reporter didn't create clean report", expectedReport, reporter.generateSummaryOfReport()); + assertEquals(expectedReport, reporter.generateSummaryOfReport()); } - @Test(groups = {"regressiontest"}) - public void missingFilesTest() throws Exception { + @Test + @Tag("regressiontest") + public void missingFilesTest() throws Exception { addDescription("Verifies that missing files are reported correctly"); addStep("Report a missing file", "hasIntegrityIssues() should return true and the summary report should " + "correctly inform of the missing file."); BasicIntegrityReporter reporter = new BasicIntegrityReporter("CollectionWithIssues", "test", new File("target/")); reporter.reportMissingFile("TestFile", "Pillar1"); - assertTrue("Reporter didn't interpreted missing file as a integrity issue", reporter.hasIntegrityIssues()); + assertTrue(reporter.hasIntegrityIssues(), "Reporter didn't interpreted missing file as a integrity issue"); String expectedReport = REPORT_SUMMARY_START + "Pillar1 is missing 1 file."; - assertEquals("Wrong report returned on missing file", expectedReport, reporter.generateSummaryOfReport()); + assertEquals(expectedReport, reporter.generateSummaryOfReport()); addStep("Report another missing file on the same pillar", "The summary report should be update with the additional missing file."); reporter.reportMissingFile("TestFile2", "Pillar1"); expectedReport = REPORT_SUMMARY_START + "Pillar1 is missing 2 files."; - assertEquals("Wrong report returned on missing file", expectedReport, reporter.generateSummaryOfReport()); + assertEquals(expectedReport, reporter.generateSummaryOfReport()); addStep("Report a missing file on another pillar", "The summary report should be update with the new pillar problem."); reporter.reportMissingFile("TestFile3", "Pillar2"); expectedReport = REPORT_SUMMARY_START + "Pillar1 is missing 2 files." + "\nPillar2 is missing 1 file."; - assertEquals("Wrong report returned on missing file", expectedReport, reporter.generateSummaryOfReport()); + assertEquals(expectedReport, reporter.generateSummaryOfReport()); } - @Test(groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public void checksumIssuesTest() throws Exception { addDescription("Verifies that missing files are reported correctly"); @@ -91,25 +99,26 @@ public void checksumIssuesTest() throws Exception { "correctly inform of the checksum issue."); BasicIntegrityReporter reporter = new BasicIntegrityReporter("CollectionWithIssues", "test", new File("target/")); reporter.reportChecksumIssue("TestFile", "Pillar1"); - assertTrue("Reporter didn't interpreted checksum issue as a integrity issue", reporter.hasIntegrityIssues()); + assertTrue(reporter.hasIntegrityIssues(), "Reporter didn't interpreted checksum issue as a integrity issue"); String expectedReport = REPORT_SUMMARY_START + "Pillar1 has 1 potentially corrupt file."; - assertEquals("Wrong report returned on checksum issue", expectedReport, reporter.generateSummaryOfReport()); + assertEquals(expectedReport, reporter.generateSummaryOfReport()); addStep("Report another checksum issue on the same pillar", "The summary report should be update with the " + "additional checksum issue."); reporter.reportChecksumIssue("TestFile2", "Pillar1"); expectedReport = REPORT_SUMMARY_START + "Pillar1 has 2 potentially corrupt files."; - assertEquals("Wrong report returned on checksum issue", expectedReport, reporter.generateSummaryOfReport()); + assertEquals(expectedReport, reporter.generateSummaryOfReport()); addStep("Report a checksum issue on another pillar", "The summary report should be update with the new pillar problem."); reporter.reportChecksumIssue("TestFile3", "Pillar2"); expectedReport = REPORT_SUMMARY_START + "Pillar1 has 2 potentially corrupt files." + "\nPillar2 has 1 " + "potentially corrupt file."; - assertEquals("Wrong report returned on checksum issue", expectedReport, reporter.generateSummaryOfReport()); + assertEquals(expectedReport, reporter.generateSummaryOfReport()); } - @Test(groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public void missingChecksumTest() throws Exception { addDescription("Verifies that missing checksums are reported correctly"); @@ -117,25 +126,26 @@ public void missingChecksumTest() throws Exception { "correctly inform of the missing checksum."); BasicIntegrityReporter reporter = new BasicIntegrityReporter("CollectionWithIssues", "test", new File("target/")); reporter.reportMissingChecksum("TestChecksum", "Pillar1"); - assertTrue("Reporter didn't interpreted missing checksum as a integrity issue", reporter.hasIntegrityIssues()); + assertTrue(reporter.hasIntegrityIssues(), "Reporter didn't interpreted missing checksum as a integrity issue"); String expectedReport = REPORT_SUMMARY_START + "Pillar1 is missing 1 checksum."; - assertEquals("Wrong report returned on missing checksum", expectedReport, reporter.generateSummaryOfReport()); + assertEquals(expectedReport, reporter.generateSummaryOfReport()); addStep("Report another missing checksum on the same pillar", "The summary report should be update with the " + "additional missing checksum."); reporter.reportMissingChecksum("TestChecksum2", "Pillar1"); expectedReport = REPORT_SUMMARY_START + "Pillar1 is missing 2 checksums."; - assertEquals("Wrong report returned on missing checksum", expectedReport, reporter.generateSummaryOfReport()); + assertEquals(expectedReport, reporter.generateSummaryOfReport()); addStep("Report a missing checksum on another pillar", "The summary report should be update with the new pillar problem."); reporter.reportMissingChecksum("TestChecksum3", "Pillar2"); expectedReport = REPORT_SUMMARY_START + "Pillar1 is missing 2 checksums." + "\nPillar2 is missing 1 checksum."; - assertEquals("Wrong report returned on missing checksum", expectedReport, reporter.generateSummaryOfReport()); + assertEquals(expectedReport, reporter.generateSummaryOfReport()); } - @Test(groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public void obsoleteChecksumTest() throws Exception { addDescription("Verifies that obsolete checksums are reported correctly"); @@ -143,20 +153,20 @@ public void obsoleteChecksumTest() throws Exception { "correctly inform of the obsolete checksum."); BasicIntegrityReporter reporter = new BasicIntegrityReporter("CollectionWithIssues", "test", new File("target/")); reporter.reportObsoleteChecksum("TestChecksum", "Pillar1"); - assertTrue("Reporter didn't interpreted obsolete checksum as a integrity issue", reporter.hasIntegrityIssues()); + assertTrue(reporter.hasIntegrityIssues(), "Reporter didn't interpreted obsolete checksum as a integrity issue"); String expectedReport = REPORT_SUMMARY_START + "Pillar1 has 1 obsolete checksum."; - assertEquals("Wrong report returned on obsolete checksum", expectedReport, reporter.generateSummaryOfReport()); + assertEquals(expectedReport, reporter.generateSummaryOfReport()); addStep("Report another obsolete checksum on the same pillar", "The summary report should be update with the " + "additional obsolete checksum."); reporter.reportObsoleteChecksum("TestChecksum2", "Pillar1"); expectedReport = REPORT_SUMMARY_START + "Pillar1 has 2 obsolete checksums."; - assertEquals("Wrong report returned on obsolete checksum", expectedReport, reporter.generateSummaryOfReport()); + assertEquals(expectedReport, reporter.generateSummaryOfReport()); addStep("Report a obsolete checksum on another pillar", "The summary report should be update with the new pillar problem."); reporter.reportObsoleteChecksum("TestChecksum3", "Pillar2"); expectedReport = REPORT_SUMMARY_START + "Pillar1 has 2 obsolete checksums." + "\nPillar2 has 1 obsolete checksum."; - assertEquals("Wrong report returned on obsolete checksum", expectedReport, reporter.generateSummaryOfReport()); + assertEquals(expectedReport, reporter.generateSummaryOfReport()); } } diff --git a/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/reports/ExampleReportGenerationTest.java b/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/reports/ExampleReportGenerationTest.java index 4d69a810b..922e851c1 100644 --- a/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/reports/ExampleReportGenerationTest.java +++ b/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/reports/ExampleReportGenerationTest.java @@ -22,7 +22,7 @@ package org.bitrepository.integrityservice.reports; import org.jaccept.structure.ExtendedTestCase; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Test; import java.io.BufferedReader; import java.io.File; diff --git a/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/stresstest/DatabaseStressTests.java b/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/stresstest/DatabaseStressTests.java index 89f738fde..934238c97 100644 --- a/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/stresstest/DatabaseStressTests.java +++ b/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/stresstest/DatabaseStressTests.java @@ -37,10 +37,11 @@ import org.bitrepository.service.database.DatabaseUtils; import org.bitrepository.service.database.DerbyDatabaseDestroyer; import org.jaccept.structure.ExtendedTestCase; -import org.testng.AssertJUnit; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; import javax.xml.datatype.DatatypeFactory; import javax.xml.datatype.Duration; @@ -59,7 +60,7 @@ public class DatabaseStressTests extends ExtendedTestCase { protected Settings settings; - @BeforeMethod (alwaysRun = true) + @BeforeEach public void setup() throws Exception { settings = TestSettingsProvider.reloadSettings("IntegrityCheckingUnderTest"); @@ -98,18 +99,20 @@ protected void populateDatabase(IntegrityDAO cache) { cache.updateFileIDs(data, PILLAR_4, collectionID); } - @AfterMethod (alwaysRun = true) + @AfterEach public void clearDatabase() { DBConnector connector = new DBConnector(settings.getReferenceSettings().getIntegrityServiceSettings().getIntegrityDatabase()); DatabaseUtils.executeStatement(connector, "DELETE FROM fileinfo"); DatabaseUtils.executeStatement(connector, "DELETE FROM pillar"); } - @Test(groups = {"stresstest", "integritytest"}) + @Test + @Tag("stresstest") + @Tag("integritytest") public void testDatabasePerformance() { addDescription("Testing the performance of the SQL queries to the database."); IntegrityDAO cache = createDAO(); - AssertJUnit.assertNotNull(cache); + Assertions.assertNotNull(cache); long startTime = System.currentTimeMillis(); populateDatabase(cache); diff --git a/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/web/PillarDetailsDtoTest.java b/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/web/PillarDetailsDtoTest.java index b25ef9a33..e59acf740 100644 --- a/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/web/PillarDetailsDtoTest.java +++ b/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/web/PillarDetailsDtoTest.java @@ -1,11 +1,11 @@ package org.bitrepository.integrityservice.web; import com.fasterxml.jackson.databind.ObjectMapper; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Test; import java.io.IOException; -import static org.testng.Assert.*; +import static org.junit.jupiter.api.Assertions.assertTrue; public class PillarDetailsDtoTest { private final ObjectMapper objectMapper = new ObjectMapper(); // Use ObjectMapper for JSON diff --git a/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/workflow/IntegrityContributorsTest.java b/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/workflow/IntegrityContributorsTest.java index cd9853a7a..e43150587 100644 --- a/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/workflow/IntegrityContributorsTest.java +++ b/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/workflow/IntegrityContributorsTest.java @@ -5,103 +5,109 @@ * Copyright (C) 2010 - 2012 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% */ package org.bitrepository.integrityservice.workflow; -import org.testng.Assert; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; import java.util.Arrays; import java.util.Set; - public class IntegrityContributorsTest { private final static String PILLAR1 = "pillar1"; private final static String PILLAR2 = "pillar2"; - - @Test(groups = {"regressiontest"}) + + @Test + @Tag("regressiontest") public void testConstructor() { IntegrityContributors ic = new IntegrityContributors(Arrays.asList(PILLAR1, PILLAR2), 3); Set activeContributors = ic.getActiveContributors(); - Assert.assertTrue(activeContributors.contains(PILLAR1)); - Assert.assertTrue(activeContributors.contains(PILLAR2)); - Assert.assertTrue(ic.getFailedContributors().isEmpty()); - Assert.assertTrue(ic.getFinishedContributors().isEmpty()); + Assertions.assertTrue(activeContributors.contains(PILLAR1)); + Assertions.assertTrue(activeContributors.contains(PILLAR2)); + Assertions.assertTrue(ic.getFailedContributors().isEmpty()); + Assertions.assertTrue(ic.getFinishedContributors().isEmpty()); } - - @Test(groups = {"regressiontest"}) + + @Test + @Tag("regressiontest") public void testFailContributor() { IntegrityContributors ic = new IntegrityContributors(Arrays.asList(PILLAR1, PILLAR2), 1); ic.failContributor(PILLAR1); - Assert.assertTrue(ic.getFailedContributors().contains(PILLAR1)); - Assert.assertTrue(ic.getActiveContributors().contains(PILLAR2)); - Assert.assertTrue(ic.getFinishedContributors().isEmpty()); + Assertions.assertTrue(ic.getFailedContributors().contains(PILLAR1)); + Assertions.assertTrue(ic.getActiveContributors().contains(PILLAR2)); + Assertions.assertTrue(ic.getFinishedContributors().isEmpty()); } - - @Test(groups = {"regressiontest"}) + + @Test + @Tag("regressiontest") public void testRetry() { IntegrityContributors ic = new IntegrityContributors(Arrays.asList(PILLAR1, PILLAR2), 3); ic.failContributor(PILLAR1); - Assert.assertTrue(ic.getActiveContributors().contains(PILLAR1)); - Assert.assertTrue(ic.getFailedContributors().isEmpty()); + Assertions.assertTrue(ic.getActiveContributors().contains(PILLAR1)); + Assertions.assertTrue(ic.getFailedContributors().isEmpty()); ic.failContributor(PILLAR1); - Assert.assertTrue(ic.getActiveContributors().contains(PILLAR1)); - Assert.assertTrue(ic.getFailedContributors().isEmpty()); + Assertions.assertTrue(ic.getActiveContributors().contains(PILLAR1)); + Assertions.assertTrue(ic.getFailedContributors().isEmpty()); ic.failContributor(PILLAR1); - Assert.assertFalse(ic.getActiveContributors().contains(PILLAR1)); - Assert.assertTrue(ic.getFailedContributors().contains(PILLAR1)); + Assertions.assertFalse(ic.getActiveContributors().contains(PILLAR1)); + Assertions.assertTrue(ic.getFailedContributors().contains(PILLAR1)); } - - @Test(groups = {"regressiontest"}) + + @Test + @Tag("regressiontest") public void testSucceed() { IntegrityContributors ic = new IntegrityContributors(Arrays.asList(PILLAR1, PILLAR2), 2); ic.failContributor(PILLAR1); ic.failContributor(PILLAR2); - Assert.assertTrue(ic.getActiveContributors().containsAll(Arrays.asList(PILLAR1, PILLAR2))); + Assertions.assertTrue(ic.getActiveContributors().containsAll(Arrays.asList(PILLAR1, PILLAR2))); ic.succeedContributor(PILLAR1); ic.failContributor(PILLAR1); ic.failContributor(PILLAR2); - Assert.assertTrue(ic.getActiveContributors().contains(PILLAR1)); - Assert.assertTrue(ic.getFailedContributors().contains(PILLAR2)); - + Assertions.assertTrue(ic.getActiveContributors().contains(PILLAR1)); + Assertions.assertTrue(ic.getFailedContributors().contains(PILLAR2)); + } - - @Test(groups = {"regressiontest"}) + + @Test + @Tag("regressiontest") public void testFinishContributor() { IntegrityContributors ic = new IntegrityContributors(Arrays.asList(PILLAR1, PILLAR2), 3); ic.finishContributor(PILLAR1); - Assert.assertTrue(ic.getFinishedContributors().contains(PILLAR1)); - Assert.assertTrue(ic.getActiveContributors().contains(PILLAR2)); - Assert.assertTrue(ic.getFailedContributors().isEmpty()); + Assertions.assertTrue(ic.getFinishedContributors().contains(PILLAR1)); + Assertions.assertTrue(ic.getActiveContributors().contains(PILLAR2)); + Assertions.assertTrue(ic.getFailedContributors().isEmpty()); } - - @Test(groups = {"regressiontest"}) + + @Test + @Tag("regressiontest") public void testReloadContributors() { IntegrityContributors ic = new IntegrityContributors(Arrays.asList(PILLAR1, PILLAR2), 1); ic.finishContributor(PILLAR1); ic.failContributor(PILLAR2); - Assert.assertTrue(ic.getActiveContributors().isEmpty()); - Assert.assertTrue(ic.getFinishedContributors().contains(PILLAR1)); - Assert.assertTrue(ic.getFailedContributors().contains(PILLAR2)); - + Assertions.assertTrue(ic.getActiveContributors().isEmpty()); + Assertions.assertTrue(ic.getFinishedContributors().contains(PILLAR1)); + Assertions.assertTrue(ic.getFailedContributors().contains(PILLAR2)); + ic.reloadActiveContributors(); - Assert.assertTrue(ic.getFinishedContributors().isEmpty()); - Assert.assertTrue(ic.getActiveContributors().contains(PILLAR1)); - Assert.assertTrue(ic.getFailedContributors().contains(PILLAR2)); + Assertions.assertTrue(ic.getFinishedContributors().isEmpty()); + Assertions.assertTrue(ic.getActiveContributors().contains(PILLAR1)); + Assertions.assertTrue(ic.getFailedContributors().contains(PILLAR2)); } - + } diff --git a/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/workflow/IntegrityWorkflowManagerTest.java b/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/workflow/IntegrityWorkflowManagerTest.java index bddd5fb37..d0db93dfb 100644 --- a/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/workflow/IntegrityWorkflowManagerTest.java +++ b/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/workflow/IntegrityWorkflowManagerTest.java @@ -5,16 +5,16 @@ * Copyright (C) 2010 - 2012 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% @@ -33,20 +33,21 @@ import org.bitrepository.settings.referencesettings.WorkflowConfiguration; import org.bitrepository.settings.referencesettings.WorkflowSettings; import org.jaccept.structure.ExtendedTestCase; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; import javax.xml.datatype.DatatypeConfigurationException; import javax.xml.datatype.DatatypeFactory; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertNull; public class IntegrityWorkflowManagerTest extends ExtendedTestCase { private Settings settings; @@ -56,8 +57,7 @@ public class IntegrityWorkflowManagerTest extends ExtendedTestCase { private String collection1ID, collection2ID; private TestWorkflow workflow1, workflow2; - - @BeforeMethod(alwaysRun = true) + @BeforeEach public void setup() throws DatatypeConfigurationException { scheduler = mock(TimerBasedScheduler.class); factory = DatatypeFactory.newInstance(); @@ -80,12 +80,13 @@ public void setup() throws DatatypeConfigurationException { workflow2 = new TestWorkflow(collection2ID); } - @Test (groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public void normalWorkflowSettings() { addDescription("Verifies that the IntegrityWorkflowManager loads correctly for at normally defined workflow."); addStep("Create a IntegrityWorkflowManager based on a single Testworkflow with a daily schedule in a to " + - "collection system", + "collection system", "Two Test workflows should be scheduled daily, one for each collection"); createIntegrityWorkflowManager(); @@ -94,13 +95,14 @@ public void normalWorkflowSettings() { verifyNoMoreInteractions(scheduler); } - @Test (groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public void noWorkflowPackage() { addDescription("Verifies that the IntegrityWorkflowManager loads correctly for at workflow configuration with " + "a workflow class name without a package scope (located in the default workflow package)."); addStep("Create a IntegrityWorkflowManager based on a single Testworkflow with a daily schedule in a to " + - "collection system, where the className is just the simpleName", + "collection system, where the className is just the simpleName", "Two Test workflows should be scheduled daily, one for each collection"); workflowSettings.getWorkflow().get(0).setWorkflowClass("TestWorkflow"); @@ -110,7 +112,8 @@ public void noWorkflowPackage() { verifyNoMoreInteractions(scheduler); } - @Test (groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public void noWorkflowSettings() { addDescription("Verifies that the IntegrityWorkflowManager loads correctly for missing reference settings a " + "workflow settings element."); @@ -131,13 +134,14 @@ public void noWorkflowSettings() { verifyNoMoreInteractions(scheduler); } - @Test (groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public void collectionSpecificWorkflows() { addDescription("Verifies that the IntegrityWorkflowManager loads correctly for workflows configured for " + "specific collection."); addStep("Create a IntegrityWorkflowManager based on a workflow with different schedules for collection 1 and " + - "2 (daily and hourly)", + "2 (daily and hourly)", "Two workflows should be scheduled, one daily and one hourly"); WorkflowConfiguration workflowConfiguration = settings.getReferenceSettings().getIntegrityServiceSettings().getWorkflows().getWorkflow().get(0); @@ -159,7 +163,8 @@ public void collectionSpecificWorkflows() { verifyNoMoreInteractions(scheduler); } - @Test (groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public void unscheduledWorkflow() { addDescription("Verifies that the IntegrityWorkflowManager loads workflow correctly for workflows without a " + "defined schedule meaning they are never run automatically."); @@ -172,10 +177,11 @@ public void unscheduledWorkflow() { when(manager.getNextScheduledRun(workflow1.getJobID())).thenReturn(null); when(manager.getRunInterval(workflow1.getJobID())).thenReturn(-1L); assertNull(manager.getNextScheduledRun(workflow1.getJobID())); - assertEquals(manager.getRunInterval(workflow1.getJobID()), -1); + assertEquals(-1, manager.getRunInterval(workflow1.getJobID())); } - @Test (groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public void startWorkflow() { addDescription("Verifies that the that it is possible to manually start a workflow."); diff --git a/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/workflow/RepairMissingFilesWorkflowTest.java b/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/workflow/RepairMissingFilesWorkflowTest.java index acca352b1..cd0647339 100644 --- a/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/workflow/RepairMissingFilesWorkflowTest.java +++ b/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/workflow/RepairMissingFilesWorkflowTest.java @@ -37,10 +37,11 @@ import org.bitrepository.service.workflow.Workflow; import org.bitrepository.settings.referencesettings.ProtocolType; import org.jaccept.structure.ExtendedTestCase; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; import javax.xml.datatype.DatatypeFactory; import javax.xml.datatype.Duration; @@ -78,7 +79,7 @@ public class RepairMissingFilesWorkflowTest extends ExtendedTestCase { protected IntegrityModel model; protected AuditTrailManager auditManager; - @BeforeMethod (alwaysRun = true) + @BeforeEach public void setup() throws Exception { settings = TestSettingsProvider.reloadSettings("IntegrityWorkflowTest"); @@ -102,7 +103,8 @@ public void setup() throws Exception { auditManager = mock(AuditTrailManager.class); } - @Test(groups = {"regressiontest", "integritytest"}) + @Test + @Tag("regressiontest") @Tag("integritytest") public void testNoMissingFiles() { addDescription("Test that the workflow does nothing, when it has no missing files."); addStep("Prepare for calls to mocks", ""); @@ -125,7 +127,8 @@ public void testNoMissingFiles() { verifyNoMoreInteractions(model); } - @Test(groups = {"regressiontest", "integritytest"}) + @Test + @Tag("regressiontest") @Tag("integritytest") public void testSuccessRepair() { addDescription("Test that the workflow makes calls to the collector, when a file is missing"); addStep("Prepare for calls to mocks to handle a repair", ""); @@ -173,7 +176,8 @@ public Void answer(InvocationOnMock invocation) { verifyNoMoreInteractions(model); } - @Test(groups = {"regressiontest", "integritytest"}) + @Test + @Tag("regressiontest") @Tag("integritytest") public void testFailedGetFile() { addDescription("Test that the workflow does not try to put a file, if it fails to get it."); addStep("Prepare for calls to mocks to fail when performing get-file", ""); @@ -213,7 +217,8 @@ public Void answer(InvocationOnMock invocation) { verifyNoMoreInteractions(model); } - @Test(groups = {"regressiontest", "integritytest"}) + @Test + @Tag("regressiontest") @Tag("integritytest") public void testFailedPutFile() { addDescription("Test that the workflow makes calls to the collector for get and put file, even when put file fails."); addStep("Prepare for calls to mocks", ""); @@ -266,7 +271,7 @@ public Void answer(InvocationOnMock invocation) { private IntegrityIssueIterator createMockIterator(String ...strings) { return new IntegrityIssueIterator(null) { - Iterator results = Arrays.asList(strings).iterator(); + final Iterator results = Arrays.asList(strings).iterator(); @Override public void close() { // TODO Auto-generated method stub diff --git a/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/workflow/SaltedChecksumWorkflowTest.java b/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/workflow/SaltedChecksumWorkflowTest.java index c41453cbc..da3ce7605 100644 --- a/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/workflow/SaltedChecksumWorkflowTest.java +++ b/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/workflow/SaltedChecksumWorkflowTest.java @@ -43,9 +43,10 @@ import org.bitrepository.service.audit.AuditTrailManager; import org.bitrepository.service.workflow.Workflow; import org.jaccept.structure.ExtendedTestCase; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; import org.mockito.stubbing.Answer; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; import java.util.Arrays; @@ -75,7 +76,7 @@ public class SaltedChecksumWorkflowTest extends ExtendedTestCase { protected IntegrityModel model; protected AuditTrailManager auditManager; - @BeforeMethod(alwaysRun = true) + @BeforeEach public void setup() throws Exception { settings = TestSettingsProvider.reloadSettings("IntegrityWorkflowTest"); @@ -93,7 +94,9 @@ public void setup() throws Exception { auditManager = mock(AuditTrailManager.class); } - @Test(groups = {"regressiontest", "integritytest"}) + @Test + @Tag("regressiontest") + @Tag("integritytest") public void testNoFilesInCollection() { addDescription("Test that the workflow does nothing, when it has no files in the collection."); addStep("Prepare for calls to mocks", ""); @@ -116,7 +119,9 @@ public void testNoFilesInCollection() { verifyNoMoreInteractions(model); } - @Test(groups = {"regressiontest", "integritytest"}) + @Test + @Tag("regressiontest") + @Tag("integritytest") public void testSuccess() { addDescription("Test that the workflow works when both pillars deliver the same checksum."); addStep("Prepare for calls to mocks", ""); @@ -156,7 +161,8 @@ public void testSuccess() { verifyNoMoreInteractions(auditManager); } - @Test(groups = {"regressiontest", "integritytest"}) + @Test + @Tag("regressiontest") @Tag("integritytest") public void testOneComponentFailureAndTwoOtherAgreeOnChecksum() { addDescription("Test that the workflow works when both pillars deliver the same checksum."); addStep("Prepare for calls to mocks", ""); @@ -199,7 +205,9 @@ public void testOneComponentFailureAndTwoOtherAgreeOnChecksum() { verifyNoMoreInteractions(auditManager); } - @Test(groups = {"regressiontest", "integritytest"}) + @Test + @Tag("regressiontest") + @Tag("integritytest") public void testOneComponentFailureAndTwoOtherDisagreeOnChecksum() throws Exception { addDescription("Test that the workflow works when both pillars deliver the same checksum."); addStep("Prepare for calls to mocks", ""); @@ -243,7 +251,8 @@ public void testOneComponentFailureAndTwoOtherDisagreeOnChecksum() throws Except verifyNoMoreInteractions(auditManager); } - @Test(groups = {"regressiontest", "integritytest"}) + @Test + @Tag("regressiontest") @Tag("integritytest") public void testInconsistentChecksums() { addDescription("Test that the workflow discovers and handles inconsistent checksums"); addStep("Prepare for calls to mocks", ""); @@ -286,7 +295,9 @@ public void testInconsistentChecksums() { verifyNoMoreInteractions(alerter); } - @Test(groups = {"regressiontest", "integritytest"}) + @Test + @Tag("regressiontest") + @Tag("integritytest") public void testNoReceivedChecksums() { addDescription("Test that the workflow handles the case, when no checksums are received"); addStep("Prepare for calls to mocks", ""); diff --git a/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/workflow/TestWorkflow.java b/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/workflow/TestWorkflow.java index 34dc41dae..25920196b 100644 --- a/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/workflow/TestWorkflow.java +++ b/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/workflow/TestWorkflow.java @@ -64,9 +64,7 @@ public boolean equals(Object o) { TestWorkflow that = (TestWorkflow) o; - if (!jobID.equals(that.jobID)) return false; - - return true; + return jobID.equals(that.jobID); } @Override diff --git a/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/workflow/step/GetChecksumForFileStepTest.java b/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/workflow/step/GetChecksumForFileStepTest.java index b9f40d0ca..23eeb1b12 100644 --- a/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/workflow/step/GetChecksumForFileStepTest.java +++ b/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/workflow/step/GetChecksumForFileStepTest.java @@ -36,10 +36,11 @@ import org.bitrepository.common.utils.CalendarUtils; import org.bitrepository.common.utils.ChecksumUtils; import org.bitrepository.integrityservice.workflow.IntegrityContributors; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; import org.mockito.stubbing.Answer; -import org.testng.Assert; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; import javax.xml.datatype.DatatypeConfigurationException; import java.util.Arrays; @@ -66,7 +67,7 @@ public class GetChecksumForFileStepTest extends WorkflowstepTest { public static final String FILE_1 = "test-file-1"; String TEST_COLLECTION = "test-collection"; - @BeforeMethod(alwaysRun = true) + @BeforeEach public void setup() throws DatatypeConfigurationException { super.setup(); settings.getRepositorySettings().getCollections().getCollection().get(0).getPillarIDs().getPillarID().clear(); @@ -77,7 +78,9 @@ public void setup() throws DatatypeConfigurationException { } - @Test(groups = {"regressiontest", "integritytest"}) + @Test + @Tag("regressiontest") + @Tag("integritytest") public void testNoResults() throws Exception { addDescription("Test step for retrieving the checksum of a single file, when no results are delivered."); ChecksumSpecTYPE checksumType = ChecksumUtils.getDefault(settings); @@ -97,13 +100,15 @@ public void testNoResults() throws Exception { addStep("Validate the checksum results", "Should not have any results"); step.performStep(); - Assert.assertTrue(step.getResults().isEmpty()); + Assertions.assertTrue(step.getResults().isEmpty()); verifyNoInteractions(alerter); verify(collector).getChecksums(anyString(), any(), eq(checksumType), eq(FILE_1), anyString(), any(), any(EventHandler.class)); verifyNoMoreInteractions(collector); } - @Test(groups = {"regressiontest", "integritytest"}) + @Test + @Tag("regressiontest") + @Tag("integritytest") public void testFullData() throws Exception { addDescription("Test step for retrieving the checksum of a single file, when all three pillars deliver results."); ChecksumSpecTYPE checksumType = ChecksumUtils.getDefault(settings); @@ -134,18 +139,20 @@ public void testFullData() throws Exception { addStep("Validate the checksum results", "Should have checksum for each pillar."); step.performStep(); - Assert.assertFalse(step.getResults().isEmpty()); - Assert.assertEquals(step.getResults().size(), 3); - Assert.assertTrue(step.getResults().containsKey(TEST_PILLAR_1)); - Assert.assertTrue(step.getResults().containsKey(TEST_PILLAR_2)); - Assert.assertTrue(step.getResults().containsKey(TEST_PILLAR_3)); + Assertions.assertFalse(step.getResults().isEmpty()); + Assertions.assertEquals(3, step.getResults().size()); + Assertions.assertTrue(step.getResults().containsKey(TEST_PILLAR_1)); + Assertions.assertTrue(step.getResults().containsKey(TEST_PILLAR_2)); + Assertions.assertTrue(step.getResults().containsKey(TEST_PILLAR_3)); verifyNoInteractions(alerter); verify(collector).getChecksums(anyString(), any(), eq(checksumType), eq(FILE_1), anyString(), any(), any(EventHandler.class)); verifyNoMoreInteractions(collector); } - @Test(groups = {"regressiontest", "integritytest"}) + @Test + @Tag("regressiontest") + @Tag("integritytest") public void testComponentFailure() throws Exception { addDescription("Test step for retrieving the checksum of a single file, when one pillar fails."); ChecksumSpecTYPE checksumType = ChecksumUtils.getDefault(settings); @@ -175,11 +182,11 @@ public void testComponentFailure() throws Exception { addStep("Validate the file ids", "Should not have integrity issues."); step.performStep(); - Assert.assertFalse(step.getResults().isEmpty()); - Assert.assertEquals(step.getResults().size(), 2); - Assert.assertTrue(step.getResults().containsKey(TEST_PILLAR_1)); - Assert.assertTrue(step.getResults().containsKey(TEST_PILLAR_2)); - Assert.assertFalse(step.getResults().containsKey(TEST_PILLAR_3)); + Assertions.assertFalse(step.getResults().isEmpty()); + Assertions.assertEquals(2, step.getResults().size()); + Assertions.assertTrue(step.getResults().containsKey(TEST_PILLAR_1)); + Assertions.assertTrue(step.getResults().containsKey(TEST_PILLAR_2)); + Assertions.assertFalse(step.getResults().containsKey(TEST_PILLAR_3)); verify(alerter).integrityFailed(anyString(), eq(TEST_COLLECTION)); verifyNoMoreInteractions(alerter); diff --git a/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/workflow/step/GetFileStepTest.java b/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/workflow/step/GetFileStepTest.java index 2e0e234ab..b681ecb25 100644 --- a/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/workflow/step/GetFileStepTest.java +++ b/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/workflow/step/GetFileStepTest.java @@ -25,12 +25,14 @@ import org.bitrepository.client.eventhandler.EventHandler; import org.bitrepository.client.eventhandler.OperationFailedEvent; import org.bitrepository.integrityservice.workflow.IntegrityWorkflowContext; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; -import org.testng.annotations.Test; import java.net.URL; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; @@ -43,7 +45,8 @@ public class GetFileStepTest extends WorkflowstepTest { public static final String TEST_PILLAR_1 = "test-pillar-1"; public static final String TEST_FILE_1 = "test-file-1"; - @Test(groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public void testPositiveReply() throws Exception { addDescription("Test the step for getting the file can handle COMPLETE operation event."); doAnswer(new Answer() { @@ -67,23 +70,26 @@ public Void answer(InvocationOnMock invocation) { verifyNoMoreInteractions(model); } - @Test(groups = {"regressiontest"}, expectedExceptions = IllegalStateException.class) + @Test + @Tag("regressiontest") public void testNegativeReply() throws Exception { - addDescription("Test the step for getting the file can handle FAILURE operation event."); - doAnswer(new Answer() { - public Void answer(InvocationOnMock invocation) { - EventHandler eventHandler = (EventHandler) invocation.getArguments()[3]; - eventHandler.handleEvent(new OperationFailedEvent(TEST_COLLECTION, "Problem encountered", null)); - return null; - } - }).when(collector).getFile( - eq(TEST_COLLECTION), eq(TEST_FILE_1), any(URL.class), any(EventHandler.class), anyString()); + assertThrows(IllegalStateException.class, () -> { + addDescription("Test the step for getting the file can handle FAILURE operation event."); + doAnswer(new Answer() { + public Void answer(InvocationOnMock invocation) { + EventHandler eventHandler = (EventHandler) invocation.getArguments()[3]; + eventHandler.handleEvent(new OperationFailedEvent(TEST_COLLECTION, "Problem encountered", null)); + return null; + } + }).when(collector).getFile( + eq(TEST_COLLECTION), eq(TEST_FILE_1), any(URL.class), any(EventHandler.class), anyString()); - IntegrityWorkflowContext context = new IntegrityWorkflowContext(settings, collector, model, alerter, auditManager); - URL uploadUrl = new URL("http://localhost/dav/test.txt"); - GetFileStep step = new GetFileStep(context, TEST_COLLECTION, TEST_FILE_1, uploadUrl); + IntegrityWorkflowContext context = new IntegrityWorkflowContext(settings, collector, model, alerter, auditManager); + URL uploadUrl = new URL("http://localhost/dav/test.txt"); + GetFileStep step = new GetFileStep(context, TEST_COLLECTION, TEST_FILE_1, uploadUrl); - step.performStep(); + step.performStep(); + }); } } diff --git a/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/workflow/step/HandleChecksumValidationStepTest.java b/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/workflow/step/HandleChecksumValidationStepTest.java index d6ad4f327..898fc5820 100644 --- a/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/workflow/step/HandleChecksumValidationStepTest.java +++ b/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/workflow/step/HandleChecksumValidationStepTest.java @@ -5,16 +5,16 @@ * Copyright (C) 2010 - 2012 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% @@ -36,8 +36,9 @@ import org.bitrepository.integrityservice.statistics.StatisticsCollector; import org.bitrepository.service.audit.AuditTrailDatabaseResults; import org.bitrepository.service.audit.AuditTrailManager; -import org.testng.Assert; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; import javax.xml.datatype.DatatypeConfigurationException; import javax.xml.datatype.DatatypeFactory; @@ -53,17 +54,19 @@ * Performs the validation of the integrity for the checksums. */ public class HandleChecksumValidationStepTest extends IntegrityDatabaseTestCase { - /** The settings for the tests. Should be instantiated in the setup.*/ + /** + * The settings for the tests. Should be instantiated in the setup. + */ public static final String TEST_PILLAR_1 = "test-pillar-1"; public static final String TEST_PILLAR_2 = "test-pillar-2"; public static final String TEST_PILLAR_3 = "test-pillar-3"; - + public static final String FILE_1 = "test-file-1"; private AuditTrailManager auditManager; public static final String FILE_2 = "test-file-2"; - + String TEST_COLLECTION; - + @Override protected void customizeSettings() throws DatatypeConfigurationException { settings.getRepositorySettings().getCollections().getCollection().get(0).getPillarIDs().getPillarID().clear(); @@ -76,50 +79,56 @@ protected void customizeSettings() throws DatatypeConfigurationException { TEST_COLLECTION = settings.getRepositorySettings().getCollections().getCollection().get(0).getID(); auditManager = mock(AuditTrailManager.class); } - - @Test(groups = {"regressiontest", "integritytest"}) + + @Test + @Tag("regressiontest") + @Tag("integritytest") public void testNoData() throws Exception { addDescription("Test the checksum integrity validator without any data in the cache."); IntegrityModel cache = getIntegrityModel(); IntegrityReporter reporter = new BasicIntegrityReporter(TEST_COLLECTION, "test", new File("target/")); StatisticsCollector cs = new StatisticsCollector(TEST_COLLECTION); HandleChecksumValidationStep step = new HandleChecksumValidationStep(cache, auditManager, reporter, cs); - + addStep("Validate the file ids", "Should not have integrity issues."); step.performStep(); - - Assert.assertFalse(reporter.hasIntegrityIssues(), reporter.generateSummaryOfReport()); + + Assertions.assertFalse(reporter.hasIntegrityIssues(), reporter.generateSummaryOfReport()); } - - @Test(groups = {"regressiontest", "integritytest"}) + + @Test + @Tag("regressiontest") + @Tag("integritytest") public void testSimilarData() throws Exception { addDescription("Test the checksum integrity validator when all pillars have similar data."); IntegrityModel cache = getIntegrityModel(); IntegrityReporter reporter = new BasicIntegrityReporter(TEST_COLLECTION, "test", new File("target/")); StatisticsCollector cs = new StatisticsCollector(TEST_COLLECTION); HandleChecksumValidationStep step = new HandleChecksumValidationStep(cache, auditManager, reporter, cs); - + addStep("Add data to the cache", ""); List csData = createChecksumData("1234cccc4321", FILE_1); insertChecksumDataForModel(cache, csData, TEST_PILLAR_1, TEST_COLLECTION); insertChecksumDataForModel(cache, csData, TEST_PILLAR_2, TEST_COLLECTION); insertChecksumDataForModel(cache, csData, TEST_PILLAR_3, TEST_COLLECTION); - + addStep("Perform the step", ""); step.performStep(); addStep("Validate the file ids", "Should not have integrity issues."); - Assert.assertFalse(reporter.hasIntegrityIssues(), reporter.generateSummaryOfReport()); - Assert.assertEquals(cs.getCollectionStat().getChecksumErrors(), Long.valueOf(0)); - Assert.assertEquals(cs.getPillarCollectionStat(TEST_PILLAR_3).getChecksumErrors(), Long.valueOf(0)); - Assert.assertEquals(cs.getPillarCollectionStat(TEST_PILLAR_2).getChecksumErrors(), Long.valueOf(0)); - Assert.assertEquals(cs.getPillarCollectionStat(TEST_PILLAR_1).getChecksumErrors(), Long.valueOf(0)); - for(FileInfo fi : cache.getFileInfos(FILE_1, TEST_COLLECTION)) { - Assert.assertEquals(fi.getChecksum(), "1234cccc4321"); + Assertions.assertFalse(reporter.hasIntegrityIssues(), reporter.generateSummaryOfReport()); + Assertions.assertEquals(cs.getCollectionStat().getChecksumErrors(), Long.valueOf(0)); + Assertions.assertEquals(cs.getPillarCollectionStat(TEST_PILLAR_3).getChecksumErrors(), Long.valueOf(0)); + Assertions.assertEquals(cs.getPillarCollectionStat(TEST_PILLAR_2).getChecksumErrors(), Long.valueOf(0)); + Assertions.assertEquals(cs.getPillarCollectionStat(TEST_PILLAR_1).getChecksumErrors(), Long.valueOf(0)); + for (FileInfo fi : cache.getFileInfos(FILE_1, TEST_COLLECTION)) { + Assertions.assertEquals("1234cccc4321", fi.getChecksum()); } } - - @Test(groups = {"regressiontest", "integritytest"}) + + @Test + @Tag("regressiontest") + @Tag("integritytest") public void testMissingAtOnePillar() throws Exception { addDescription("Test the checksum integrity validator when one pillar is missing the data."); IntegrityModel cache = getIntegrityModel(); @@ -131,49 +140,53 @@ public void testMissingAtOnePillar() throws Exception { List csData = createChecksumData("1234cccc4321", FILE_1); insertChecksumDataForModel(cache, csData, TEST_PILLAR_1, TEST_COLLECTION); insertChecksumDataForModel(cache, csData, TEST_PILLAR_2, TEST_COLLECTION); - + addStep("Perform the step", ""); step.performStep(); addStep("Validate the file ids", "No integrity issues."); - Assert.assertFalse(reporter.hasIntegrityIssues(), reporter.generateSummaryOfReport()); + Assertions.assertFalse(reporter.hasIntegrityIssues(), reporter.generateSummaryOfReport()); } - @Test(groups = {"regressiontest", "integritytest"}) + @Test + @Tag("regressiontest") + @Tag("integritytest") public void testTwoDisagreeingChecksums() throws Exception { addDescription("Test the checksum integrity validator when only two pillar has data, but it it different."); IntegrityModel cache = getIntegrityModel(); IntegrityReporter reporter = new BasicIntegrityReporter(TEST_COLLECTION, "test", new File("target/")); StatisticsCollector cs = new StatisticsCollector(TEST_COLLECTION); HandleChecksumValidationStep step = new HandleChecksumValidationStep(cache, auditManager, reporter, cs); - + addStep("Add data to the cache", ""); List csData1 = createChecksumData("1234cccc4321", FILE_1); insertChecksumDataForModel(cache, csData1, TEST_PILLAR_1, TEST_COLLECTION); List csData2 = createChecksumData("1c2c3c44c3c2c1", FILE_1); insertChecksumDataForModel(cache, csData2, TEST_PILLAR_2, TEST_COLLECTION); - + addStep("Perform the step", ""); step.performStep(); addStep("Validate the file ids", "Should have integrity issues. No entry should be valid."); - Assert.assertTrue(reporter.hasIntegrityIssues(), reporter.generateSummaryOfReport()); - Assert.assertEquals(cs.getCollectionStat().getChecksumErrors(), Long.valueOf(1)); - Assert.assertEquals(cs.getPillarCollectionStat(TEST_PILLAR_1).getChecksumErrors(), Long.valueOf(1)); - Assert.assertEquals(cs.getPillarCollectionStat(TEST_PILLAR_2).getChecksumErrors(), Long.valueOf(1)); + Assertions.assertTrue(reporter.hasIntegrityIssues(), reporter.generateSummaryOfReport()); + Assertions.assertEquals(cs.getCollectionStat().getChecksumErrors(), Long.valueOf(1)); + Assertions.assertEquals(cs.getPillarCollectionStat(TEST_PILLAR_1).getChecksumErrors(), Long.valueOf(1)); + Assertions.assertEquals(cs.getPillarCollectionStat(TEST_PILLAR_2).getChecksumErrors(), Long.valueOf(1)); /*for(FileInfo fi : cache.getFileInfos(FILE_1, TEST_COLLECTION)) { - Assert.assertTrue(fi.getChecksumState() != ChecksumState.VALID); + Assertions.assertTrue(fi.getChecksumState() != ChecksumState.VALID); }*/ } - - @Test(groups = {"regressiontest", "integritytest"}) + + @Test + @Tag("regressiontest") + @Tag("integritytest") public void testThreeDisagreeingChecksums() throws Exception { addDescription("Test the checksum integrity validator when all pillars have different checksums."); IntegrityModel cache = getIntegrityModel(); IntegrityReporter reporter = new BasicIntegrityReporter(TEST_COLLECTION, "test", new File("target/")); StatisticsCollector cs = new StatisticsCollector(TEST_COLLECTION); HandleChecksumValidationStep step = new HandleChecksumValidationStep(cache, auditManager, reporter, cs); - + addStep("Add data to the cache", ""); List csData1 = createChecksumData("1234cccc4321", FILE_1); insertChecksumDataForModel(cache, csData1, TEST_PILLAR_1, TEST_COLLECTION); @@ -181,19 +194,21 @@ public void testThreeDisagreeingChecksums() throws Exception { insertChecksumDataForModel(cache, csData2, TEST_PILLAR_2, TEST_COLLECTION); List csData3 = createChecksumData("1c2c3c44c3c2c1", FILE_1); insertChecksumDataForModel(cache, csData3, TEST_PILLAR_3, TEST_COLLECTION); - + addStep("Perform the step", ""); step.performStep(); addStep("Validate the file ids", "Should have integrity issues."); - Assert.assertTrue(reporter.hasIntegrityIssues(), reporter.generateSummaryOfReport()); - Assert.assertEquals(cs.getCollectionStat().getChecksumErrors(), Long.valueOf(1)); - Assert.assertEquals(cs.getPillarCollectionStat(TEST_PILLAR_3).getChecksumErrors(), Long.valueOf(1)); - Assert.assertEquals(cs.getPillarCollectionStat(TEST_PILLAR_2).getChecksumErrors(), Long.valueOf(1)); - Assert.assertEquals(cs.getPillarCollectionStat(TEST_PILLAR_1).getChecksumErrors(), Long.valueOf(1)); + Assertions.assertTrue(reporter.hasIntegrityIssues(), reporter.generateSummaryOfReport()); + Assertions.assertEquals(cs.getCollectionStat().getChecksumErrors(), Long.valueOf(1)); + Assertions.assertEquals(cs.getPillarCollectionStat(TEST_PILLAR_3).getChecksumErrors(), Long.valueOf(1)); + Assertions.assertEquals(cs.getPillarCollectionStat(TEST_PILLAR_2).getChecksumErrors(), Long.valueOf(1)); + Assertions.assertEquals(cs.getPillarCollectionStat(TEST_PILLAR_1).getChecksumErrors(), Long.valueOf(1)); } - - @Test(groups = {"regressiontest", "integritytest"}) + + @Test + @Tag("regressiontest") + @Tag("integritytest") public void testChecksumMajority() throws Exception { addDescription("Test the checksum integrity validator when two pillars have one checksum and the last pillar " + "has another checksum."); @@ -201,7 +216,7 @@ public void testChecksumMajority() throws Exception { IntegrityReporter reporter = new BasicIntegrityReporter(TEST_COLLECTION, "test", new File("target/")); StatisticsCollector cs = new StatisticsCollector(TEST_COLLECTION); HandleChecksumValidationStep step = new HandleChecksumValidationStep(cache, auditManager, reporter, cs); - + addStep("Add data to the cache", ""); List csData1 = createChecksumData("1234cccc4321", FILE_1); insertChecksumDataForModel(cache, csData1, TEST_PILLAR_1, TEST_COLLECTION); @@ -209,19 +224,21 @@ public void testChecksumMajority() throws Exception { insertChecksumDataForModel(cache, csData2, TEST_PILLAR_2, TEST_COLLECTION); List csData3 = createChecksumData("1c2c3c44c3c2c1", FILE_1); insertChecksumDataForModel(cache, csData3, TEST_PILLAR_3, TEST_COLLECTION); - + addStep("Perform the checksum validation step", ""); step.performStep(); addStep("Validate the file ids", "Should only have integrity issues on pillar 3."); - Assert.assertTrue(reporter.hasIntegrityIssues(), reporter.generateSummaryOfReport()); - Assert.assertEquals(cs.getCollectionStat().getChecksumErrors(), Long.valueOf(1)); - Assert.assertEquals(cs.getPillarCollectionStat(TEST_PILLAR_3).getChecksumErrors(), Long.valueOf(1)); - Assert.assertEquals(cs.getPillarCollectionStat(TEST_PILLAR_2).getChecksumErrors(), Long.valueOf(0)); - Assert.assertEquals(cs.getPillarCollectionStat(TEST_PILLAR_1).getChecksumErrors(), Long.valueOf(0)); + Assertions.assertTrue(reporter.hasIntegrityIssues(), reporter.generateSummaryOfReport()); + Assertions.assertEquals(cs.getCollectionStat().getChecksumErrors(), Long.valueOf(1)); + Assertions.assertEquals(cs.getPillarCollectionStat(TEST_PILLAR_3).getChecksumErrors(), Long.valueOf(1)); + Assertions.assertEquals(cs.getPillarCollectionStat(TEST_PILLAR_2).getChecksumErrors(), Long.valueOf(0)); + Assertions.assertEquals(cs.getPillarCollectionStat(TEST_PILLAR_1).getChecksumErrors(), Long.valueOf(0)); } - @Test(groups = {"regressiontest", "integritytest"}) + @Test + @Tag("regressiontest") + @Tag("integritytest") public void testAuditTrailsForChecksumErrors() throws Exception { addDescription("Test audit trails for checksum errors. Verify that a pillar with a single checksum will" + " be pointed out as the possible cause."); @@ -230,53 +247,53 @@ public void testAuditTrailsForChecksumErrors() throws Exception { TestAuditTrailManager auditManager = new TestAuditTrailManager(); StatisticsCollector cs = new StatisticsCollector(TEST_COLLECTION); HandleChecksumValidationStep step = new HandleChecksumValidationStep(cache, auditManager, reporter, cs); - + addStep("Test step on data without checksum error", "No audit trails."); List csData = createChecksumData("1234cccc4321", FILE_1); insertChecksumDataForModel(cache, csData, TEST_PILLAR_1, TEST_COLLECTION); insertChecksumDataForModel(cache, csData, TEST_PILLAR_2, TEST_COLLECTION); insertChecksumDataForModel(cache, csData, TEST_PILLAR_3, TEST_COLLECTION); step.performStep(); - Assert.assertNull(auditManager.latestAuditInfo); - + Assertions.assertNull(auditManager.latestAuditInfo); + addStep("Test step on data where only two pillars have the file and they disagree about the checksum.", "An audit trail with fileID and collectionID, but no pillar pointed out as cause"); insertChecksumDataForModel(cache, createChecksumData("1234cccc4321", FILE_2), TEST_PILLAR_1, TEST_COLLECTION); insertChecksumDataForModel(cache, createChecksumData("cc12344321cc", FILE_2), TEST_PILLAR_2, TEST_COLLECTION); - + List fis = (List) cache.getFileInfos(FILE_1, TEST_COLLECTION); System.out.println("number of files in the collection" + cache.getNumberOfFilesInCollection(TEST_COLLECTION)); System.out.println("number of file infos: " + fis.size()); - Assert.assertNotNull(fis.get(0).getChecksum()); - + Assertions.assertNotNull(fis.get(0).getChecksum()); + step.performStep(); - Assert.assertNotNull(auditManager.latestAuditInfo); - Assert.assertFalse(auditManager.latestAuditInfo.contains(TEST_PILLAR_1), auditManager.latestAuditInfo); - Assert.assertFalse(auditManager.latestAuditInfo.contains(TEST_PILLAR_2), auditManager.latestAuditInfo); - Assert.assertFalse(auditManager.latestAuditInfo.contains(TEST_PILLAR_3), auditManager.latestAuditInfo); - Assert.assertTrue(auditManager.latestAuditInfo.contains(FILE_2), auditManager.latestAuditInfo); - Assert.assertTrue(auditManager.latestAuditInfo.contains(TEST_COLLECTION), auditManager.latestAuditInfo); - + Assertions.assertNotNull(auditManager.latestAuditInfo); + Assertions.assertFalse(auditManager.latestAuditInfo.contains(TEST_PILLAR_1), auditManager.latestAuditInfo); + Assertions.assertFalse(auditManager.latestAuditInfo.contains(TEST_PILLAR_2), auditManager.latestAuditInfo); + Assertions.assertFalse(auditManager.latestAuditInfo.contains(TEST_PILLAR_3), auditManager.latestAuditInfo); + Assertions.assertTrue(auditManager.latestAuditInfo.contains(FILE_2), auditManager.latestAuditInfo); + Assertions.assertTrue(auditManager.latestAuditInfo.contains(TEST_COLLECTION), auditManager.latestAuditInfo); + addStep("remove the last audit info", ""); auditManager.latestAuditInfo = null; - + addStep("Test step on data where two pillars have one checksum and the last pillar has a different one", "An audit trail with fileID and collectionID, and the lone pillar is pointed out as possible cause"); insertChecksumDataForModel(cache, createChecksumData("1234cccc4321", FILE_2), TEST_PILLAR_1, TEST_COLLECTION); insertChecksumDataForModel(cache, createChecksumData("cc12344321cc", FILE_2), TEST_PILLAR_2, TEST_COLLECTION); insertChecksumDataForModel(cache, createChecksumData("cc12344321cc", FILE_2), TEST_PILLAR_3, TEST_COLLECTION); step.performStep(); - Assert.assertNotNull(auditManager.latestAuditInfo); - Assert.assertTrue(auditManager.latestAuditInfo.contains(TEST_PILLAR_1), auditManager.latestAuditInfo); - Assert.assertFalse(auditManager.latestAuditInfo.contains(TEST_PILLAR_2), auditManager.latestAuditInfo); - Assert.assertFalse(auditManager.latestAuditInfo.contains(TEST_PILLAR_3), auditManager.latestAuditInfo); - Assert.assertTrue(auditManager.latestAuditInfo.contains(FILE_2), auditManager.latestAuditInfo); - Assert.assertTrue(auditManager.latestAuditInfo.contains(TEST_COLLECTION), auditManager.latestAuditInfo); + Assertions.assertNotNull(auditManager.latestAuditInfo); + Assertions.assertTrue(auditManager.latestAuditInfo.contains(TEST_PILLAR_1), auditManager.latestAuditInfo); + Assertions.assertFalse(auditManager.latestAuditInfo.contains(TEST_PILLAR_2), auditManager.latestAuditInfo); + Assertions.assertFalse(auditManager.latestAuditInfo.contains(TEST_PILLAR_3), auditManager.latestAuditInfo); + Assertions.assertTrue(auditManager.latestAuditInfo.contains(FILE_2), auditManager.latestAuditInfo); + Assertions.assertTrue(auditManager.latestAuditInfo.contains(TEST_COLLECTION), auditManager.latestAuditInfo); } - private List createChecksumData(String checksum, String ... fileids) { + private List createChecksumData(String checksum, String... fileids) { List res = new ArrayList<>(); - for(String fileID : fileids) { + for (String fileID : fileids) { ChecksumDataForChecksumSpecTYPE csData = new ChecksumDataForChecksumSpecTYPE(); csData.setCalculationTimestamp(CalendarUtils.getNow()); try { @@ -293,21 +310,21 @@ private List createChecksumData(String checksum private IntegrityModel getIntegrityModel() { return new IntegrityDatabase(settings); } - + private static class TestAuditTrailManager implements AuditTrailManager { String latestAuditInfo; @Override public void addAuditEvent(String collectionID, String fileID, - String actor, String info, String auditTrail, - FileAction operation, String operationID, String certificateID) { + String actor, String info, String auditTrail, + FileAction operation, String operationID, String certificateID) { latestAuditInfo = info; } @Override public AuditTrailDatabaseResults getAudits(String collectionID, - String fileID, Long minSeqNumber, Long maxSeqNumber, - Date minDate, Date maxDate, Long maxNumberOfResults) { + String fileID, Long minSeqNumber, Long maxSeqNumber, + Date minDate, Date maxDate, Long maxNumberOfResults) { return null; } } diff --git a/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/workflow/step/PutFileStepTest.java b/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/workflow/step/PutFileStepTest.java index 682846310..cf3b4a6c2 100644 --- a/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/workflow/step/PutFileStepTest.java +++ b/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/workflow/step/PutFileStepTest.java @@ -26,12 +26,14 @@ import org.bitrepository.client.eventhandler.EventHandler; import org.bitrepository.client.eventhandler.OperationFailedEvent; import org.bitrepository.integrityservice.workflow.IntegrityWorkflowContext; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; -import org.testng.annotations.Test; import java.net.URL; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; @@ -45,7 +47,8 @@ public class PutFileStepTest extends WorkflowstepTest { public static final String TEST_FILE_1 = "test-file-1"; public static final String TEST_CHECKSUM = "1234567890abba0987654321"; - @Test(groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public void testPositiveReply() throws Exception { addDescription("Test the step for getting the file can handle COMPLETE operation event."); doAnswer(new Answer() { @@ -69,23 +72,27 @@ public Void answer(InvocationOnMock invocation) { verifyNoMoreInteractions(model); } - @Test(groups = {"regressiontest"}, expectedExceptions = IllegalStateException.class) + @Test + @Tag("regressiontest") public void testNegativeReply() throws Exception { - addDescription("Test the step for getting the file can handle FAILURE operation event."); - doAnswer(new Answer() { - public Void answer(InvocationOnMock invocation) { - EventHandler eventHandler = (EventHandler) invocation.getArguments()[4]; - eventHandler.handleEvent(new OperationFailedEvent(TEST_COLLECTION, "Problem encountered", null)); - return null; - } - }).when(collector).putFile( - eq(TEST_COLLECTION), eq(TEST_FILE_1), any(URL.class), any(ChecksumDataForFileTYPE.class), any(EventHandler.class), anyString()); + assertThrows(IllegalStateException.class, () -> { - IntegrityWorkflowContext context = new IntegrityWorkflowContext(settings, collector, model, alerter, auditManager); - URL uploadUrl = new URL("http://localhost/dav/test.txt"); - PutFileStep step = new PutFileStep(context, TEST_COLLECTION, TEST_FILE_1, uploadUrl, TEST_CHECKSUM); + addDescription("Test the step for getting the file can handle FAILURE operation event."); + doAnswer(new Answer() { + public Void answer(InvocationOnMock invocation) { + EventHandler eventHandler = (EventHandler) invocation.getArguments()[4]; + eventHandler.handleEvent(new OperationFailedEvent(TEST_COLLECTION, "Problem encountered", null)); + return null; + } + }).when(collector).putFile( + eq(TEST_COLLECTION), eq(TEST_FILE_1), any(URL.class), any(ChecksumDataForFileTYPE.class), any(EventHandler.class), anyString()); - step.performStep(); + IntegrityWorkflowContext context = new IntegrityWorkflowContext(settings, collector, model, alerter, auditManager); + URL uploadUrl = new URL("http://localhost/dav/test.txt"); + PutFileStep step = new PutFileStep(context, TEST_COLLECTION, TEST_FILE_1, uploadUrl, TEST_CHECKSUM); + + step.performStep(); + }); } } diff --git a/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/workflow/step/UpdateChecksumsStepTest.java b/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/workflow/step/UpdateChecksumsStepTest.java index 8146ddf86..c9df25573 100644 --- a/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/workflow/step/UpdateChecksumsStepTest.java +++ b/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/workflow/step/UpdateChecksumsStepTest.java @@ -39,13 +39,13 @@ import org.bitrepository.common.utils.SettingsUtils; import org.bitrepository.integrityservice.cache.IntegrityModel; import org.bitrepository.service.exception.WorkflowAbortedException; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; -import org.testng.Assert; -import org.testng.annotations.Test; import java.util.ArrayList; -import java.util.Arrays; import java.util.Date; import java.util.HashSet; import java.util.List; @@ -65,7 +65,8 @@ public class UpdateChecksumsStepTest extends WorkflowstepTest { public static final String TEST_FILE_1 = "test-file-1"; public static final String DEFAULT_CHECKSUM = "0123456789"; - @Test(groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public void testPositiveReply() throws WorkflowAbortedException { addDescription("Test the step for updating the checksums can handle COMPLETE operation event."); doAnswer(new Answer() { @@ -79,7 +80,7 @@ public Void answer(InvocationOnMock invocation) { anyString(), any(ContributorQuery[].class), any(EventHandler.class)); when(integrityContributors.getActiveContributors()) - .thenReturn(new HashSet<>(Arrays.asList(TEST_PILLAR_1))).thenReturn(new HashSet<>()); + .thenReturn(new HashSet<>(List.of(TEST_PILLAR_1))).thenReturn(new HashSet<>()); UpdateChecksumsStep step = new IncrementalUpdateChecksumsStep(collector, model, alerter, createChecksumSpecTYPE(), settings, TEST_COLLECTION, integrityContributors); @@ -89,7 +90,8 @@ public Void answer(InvocationOnMock invocation) { verifyNoMoreInteractions(alerter); } - @Test(groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public void testAbortWorkflowWhenNegativeReply() { addDescription("Test the step for updating the checksums will abort the workflow in case " + "of FAILURE operation event and AbortOnFailedContributor = true ."); @@ -105,16 +107,16 @@ public Void answer(InvocationOnMock invocation) { anyString(), any(ContributorQuery[].class), any(EventHandler.class)); when(integrityContributors.getActiveContributors()) - .thenReturn(new HashSet<>(Arrays.asList(TEST_PILLAR_1))) + .thenReturn(new HashSet<>(List.of(TEST_PILLAR_1))) .thenReturn(new HashSet<>()); - when(integrityContributors.getFailedContributors()).thenReturn(new HashSet<>(Arrays.asList(TEST_PILLAR_1))); + when(integrityContributors.getFailedContributors()).thenReturn(new HashSet<>(List.of(TEST_PILLAR_1))); settings.getReferenceSettings().getIntegrityServiceSettings().setAbortOnFailedContributor(true); UpdateChecksumsStep step = new IncrementalUpdateChecksumsStep(collector, model, alerter, createChecksumSpecTYPE(), settings, TEST_COLLECTION, integrityContributors); try { step.performStep(); - Assert.fail("The step should have thrown an WorkflowAbortedException"); + Assertions.fail("The step should have thrown an WorkflowAbortedException"); } catch (WorkflowAbortedException e) { // nothing to do here } @@ -124,7 +126,8 @@ public Void answer(InvocationOnMock invocation) { verify(alerter).integrityFailed(anyString(), eq(TEST_COLLECTION)); } - @Test(groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public void testRetryCollectionWhenNegativeReply() throws WorkflowAbortedException { addDescription("Test the step for updating the file ids will retry on a FAILED event"); @@ -139,7 +142,7 @@ public Void answer(InvocationOnMock invocation) { eventHandler.handleEvent(new ContributorFailedEvent(TEST_PILLAR_1, TEST_COLLECTION, ResponseCode.FAILURE)); eventHandler.handleEvent(new OperationFailedEvent(TEST_COLLECTION, "Problem encountered", null)); } else { - eventHandler.handleEvent(new IdentificationCompleteEvent(TEST_COLLECTION, Arrays.asList(TEST_PILLAR_1))); + eventHandler.handleEvent(new IdentificationCompleteEvent(TEST_COLLECTION, List.of(TEST_PILLAR_1))); eventHandler.handleEvent(new ChecksumsCompletePillarEvent(TEST_PILLAR_1, TEST_COLLECTION, resultingChecksums, createChecksumSpecTYPE(), false)); eventHandler.handleEvent(new CompleteEvent(TEST_COLLECTION, null)); @@ -151,8 +154,8 @@ public Void answer(InvocationOnMock invocation) { anyString(), any(ContributorQuery[].class), any(EventHandler.class)); when(integrityContributors.getActiveContributors()) - .thenReturn(new HashSet<>(Arrays.asList(TEST_PILLAR_1))) - .thenReturn(new HashSet<>(Arrays.asList(TEST_PILLAR_1))) + .thenReturn(new HashSet<>(List.of(TEST_PILLAR_1))) + .thenReturn(new HashSet<>(List.of(TEST_PILLAR_1))) .thenReturn(new HashSet<>()); when(integrityContributors.getFailedContributors()).thenReturn(new HashSet<>()); @@ -168,7 +171,8 @@ public Void answer(InvocationOnMock invocation) { } - @Test(groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public void testContinueWorkflowNegativeReply() throws WorkflowAbortedException { addDescription("Test the step for updating the checksums will continue the workflow in case " + "of FAILURE operation event and AbortOnFailedContributor = false ."); @@ -184,9 +188,9 @@ public Void answer(InvocationOnMock invocation) { anyString(), any(ContributorQuery[].class), any(EventHandler.class)); when(integrityContributors.getActiveContributors()) - .thenReturn(new HashSet<>(Arrays.asList(TEST_PILLAR_1))) + .thenReturn(new HashSet<>(List.of(TEST_PILLAR_1))) .thenReturn(new HashSet<>()); - when(integrityContributors.getFailedContributors()).thenReturn(new HashSet<>(Arrays.asList(TEST_PILLAR_1))); + when(integrityContributors.getFailedContributors()).thenReturn(new HashSet<>(List.of(TEST_PILLAR_1))); settings.getReferenceSettings().getIntegrityServiceSettings().setAbortOnFailedContributor(false); UpdateChecksumsStep step = new IncrementalUpdateChecksumsStep(collector, model, alerter, createChecksumSpecTYPE(), @@ -199,14 +203,15 @@ public Void answer(InvocationOnMock invocation) { verify(alerter).integrityFailed(anyString(), eq(TEST_COLLECTION)); } - @Test(groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public void testIngestOfResults() throws WorkflowAbortedException { addDescription("Test the step for updating the checksums delivers the results to the integrity model."); final ResultingChecksums resultingChecksums = createResultingChecksums(DEFAULT_CHECKSUM, TEST_FILE_1); doAnswer(new Answer() { public Void answer(InvocationOnMock invocation) { EventHandler eventHandler = (EventHandler) invocation.getArguments()[6]; - eventHandler.handleEvent(new IdentificationCompleteEvent(TEST_COLLECTION, Arrays.asList(TEST_PILLAR_1))); + eventHandler.handleEvent(new IdentificationCompleteEvent(TEST_COLLECTION, List.of(TEST_PILLAR_1))); eventHandler.handleEvent(new ChecksumsCompletePillarEvent(TEST_PILLAR_1, TEST_COLLECTION, resultingChecksums, createChecksumSpecTYPE(), false)); eventHandler.handleEvent(new CompleteEvent(TEST_COLLECTION, null)); @@ -217,9 +222,9 @@ public Void answer(InvocationOnMock invocation) { anyString(), any(ContributorQuery[].class), any(EventHandler.class)); when(integrityContributors.getActiveContributors()) - .thenReturn(new HashSet<>(Arrays.asList(TEST_PILLAR_1))).thenReturn(new HashSet<>()); + .thenReturn(new HashSet<>(List.of(TEST_PILLAR_1))).thenReturn(new HashSet<>()); when(integrityContributors.getActiveContributors()) - .thenReturn(new HashSet<>(Arrays.asList(TEST_PILLAR_1))).thenReturn(new HashSet<>()); + .thenReturn(new HashSet<>(List.of(TEST_PILLAR_1))).thenReturn(new HashSet<>()); UpdateChecksumsStep step = new IncrementalUpdateChecksumsStep(collector, model, alerter, createChecksumSpecTYPE(), settings, TEST_COLLECTION, integrityContributors); @@ -230,14 +235,15 @@ public Void answer(InvocationOnMock invocation) { verifyNoMoreInteractions(alerter); } - @Test(groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public void testCallForChangingChecksumStates() throws WorkflowAbortedException { addDescription("Test the step for updating the checksums delivers the results to the integrity model."); final ResultingChecksums resultingChecksums = createResultingChecksums(DEFAULT_CHECKSUM, TEST_FILE_1); doAnswer(new Answer() { public Void answer(InvocationOnMock invocation) { EventHandler eventHandler = (EventHandler) invocation.getArguments()[6]; - eventHandler.handleEvent(new IdentificationCompleteEvent(TEST_COLLECTION, Arrays.asList(TEST_PILLAR_1))); + eventHandler.handleEvent(new IdentificationCompleteEvent(TEST_COLLECTION, List.of(TEST_PILLAR_1))); eventHandler.handleEvent(new ChecksumsCompletePillarEvent(TEST_PILLAR_1, TEST_COLLECTION, resultingChecksums, createChecksumSpecTYPE(), false)); eventHandler.handleEvent(new CompleteEvent(TEST_COLLECTION, null)); @@ -248,7 +254,7 @@ public Void answer(InvocationOnMock invocation) { anyString(), any(ContributorQuery[].class), any(EventHandler.class)); when(integrityContributors.getActiveContributors()) - .thenReturn(new HashSet<>(Arrays.asList(TEST_PILLAR_1))).thenReturn(new HashSet<>()); + .thenReturn(new HashSet<>(List.of(TEST_PILLAR_1))).thenReturn(new HashSet<>()); UpdateChecksumsStep step = new FullUpdateChecksumsStep(collector, model, alerter, createChecksumSpecTYPE(), settings, TEST_COLLECTION, integrityContributors); @@ -260,7 +266,8 @@ public Void answer(InvocationOnMock invocation) { verifyNoMoreInteractions(alerter); } - @Test(groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public void testPartialResults() throws WorkflowAbortedException { addDescription("Test that the number of partial is used for generating more than one request."); final ResultingChecksums resultingChecksums = createResultingChecksums(DEFAULT_CHECKSUM, TEST_FILE_1); @@ -273,7 +280,7 @@ public void testPartialResults() throws WorkflowAbortedException { public Void answer(InvocationOnMock invocation) { EventHandler eventHandler = (EventHandler) invocation.getArguments()[6]; - eventHandler.handleEvent(new IdentificationCompleteEvent(TEST_COLLECTION, Arrays.asList(TEST_PILLAR_1))); + eventHandler.handleEvent(new IdentificationCompleteEvent(TEST_COLLECTION, List.of(TEST_PILLAR_1))); eventHandler.handleEvent(new ChecksumsCompletePillarEvent(TEST_PILLAR_1, TEST_COLLECTION, resultingChecksums, createChecksumSpecTYPE(), firstPage)); firstPage = false; @@ -285,8 +292,8 @@ public Void answer(InvocationOnMock invocation) { anyString(), any(ContributorQuery[].class), any(EventHandler.class)); when(integrityContributors.getActiveContributors()) - .thenReturn(new HashSet<>(Arrays.asList(TEST_PILLAR_1))) - .thenReturn(new HashSet<>(Arrays.asList(TEST_PILLAR_1))) + .thenReturn(new HashSet<>(List.of(TEST_PILLAR_1))) + .thenReturn(new HashSet<>(List.of(TEST_PILLAR_1))) .thenReturn(new HashSet<>()); UpdateChecksumsStep step = new IncrementalUpdateChecksumsStep(collector, model, alerter, createChecksumSpecTYPE(), @@ -298,7 +305,8 @@ public Void answer(InvocationOnMock invocation) { any(ChecksumSpecTYPE.class), any(), anyString(), any(ContributorQuery[].class), any(EventHandler.class)); } - @Test(groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public void testFullChecksumCollection() throws WorkflowAbortedException { addDescription("Test that the full list of checksums is requested."); @@ -314,7 +322,7 @@ public Void answer(InvocationOnMock invocation) { when(model.getDateForNewestChecksumEntryForPillar(anyString(), anyString())).thenReturn(new Date(0)); when(integrityContributors.getActiveContributors()) - .thenReturn(new HashSet<>(Arrays.asList(TEST_PILLAR_1))).thenReturn(new HashSet<>()); + .thenReturn(new HashSet<>(List.of(TEST_PILLAR_1))).thenReturn(new HashSet<>()); UpdateChecksumsStep step = new FullUpdateChecksumsStep(collector, model, alerter, createChecksumSpecTYPE(), settings, TEST_COLLECTION, integrityContributors); @@ -329,7 +337,8 @@ public Void answer(InvocationOnMock invocation) { verifyNoMoreInteractions(alerter); } - @Test(groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public void testIncrementalChecksumCollection() throws WorkflowAbortedException { addDescription("Test that only the list of new checksums is requested."); @@ -344,7 +353,7 @@ public Void answer(InvocationOnMock invocation) { anyString(), any(ContributorQuery[].class), any(EventHandler.class)); when(integrityContributors.getActiveContributors()) - .thenReturn(new HashSet<>(Arrays.asList(TEST_PILLAR_1))).thenReturn(new HashSet<>()); + .thenReturn(new HashSet<>(List.of(TEST_PILLAR_1))).thenReturn(new HashSet<>()); UpdateChecksumsStep step = new IncrementalUpdateChecksumsStep(collector, model, alerter, createChecksumSpecTYPE(), settings, TEST_COLLECTION, integrityContributors); diff --git a/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/workflow/step/UpdateFileIDsStepTest.java b/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/workflow/step/UpdateFileIDsStepTest.java index bc019e992..e5a3aed84 100644 --- a/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/workflow/step/UpdateFileIDsStepTest.java +++ b/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/workflow/step/UpdateFileIDsStepTest.java @@ -35,14 +35,15 @@ import org.bitrepository.client.eventhandler.OperationFailedEvent; import org.bitrepository.common.utils.CalendarUtils; import org.bitrepository.service.exception.WorkflowAbortedException; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; -import org.testng.Assert; -import org.testng.annotations.Test; import java.math.BigInteger; -import java.util.Arrays; import java.util.HashSet; +import java.util.List; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; @@ -58,7 +59,8 @@ public class UpdateFileIDsStepTest extends WorkflowstepTest { public static final String TEST_PILLAR_1 = "test-pillar-1"; public static final String TEST_FILE_1 = "test-file-1"; - @Test(groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public void testPositiveReply() throws WorkflowAbortedException { addDescription("Test the step for updating the file ids can handle COMPLETE operation event."); doAnswer(new Answer() { @@ -72,7 +74,7 @@ public Void answer(InvocationOnMock invocation) { any(EventHandler.class)); when(integrityContributors.getActiveContributors()) - .thenReturn(new HashSet<>(Arrays.asList(TEST_PILLAR_1))).thenReturn(new HashSet<>()); + .thenReturn(new HashSet<>(List.of(TEST_PILLAR_1))).thenReturn(new HashSet<>()); UpdateFileIDsStep step = new FullUpdateFileIDsStep(collector, model, alerter, settings, TEST_COLLECTION, integrityContributors); @@ -83,7 +85,8 @@ public Void answer(InvocationOnMock invocation) { verifyNoMoreInteractions(alerter); } - @Test(groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public void testAbortWorkflowWhenNegativeReply() { addDescription("Test the step for updating the file ids will throw an WorkflowAbortedException" + "when AbortOnFailedContributor is set to true and a FAILED event is received."); @@ -99,9 +102,9 @@ public Void answer(InvocationOnMock invocation) { any(EventHandler.class)); when(integrityContributors.getActiveContributors()) - .thenReturn(new HashSet<>(Arrays.asList(TEST_PILLAR_1))) + .thenReturn(new HashSet<>(List.of(TEST_PILLAR_1))) .thenReturn(new HashSet<>()); - when(integrityContributors.getFailedContributors()).thenReturn(new HashSet<>(Arrays.asList(TEST_PILLAR_1))); + when(integrityContributors.getFailedContributors()).thenReturn(new HashSet<>(List.of(TEST_PILLAR_1))); settings.getReferenceSettings().getIntegrityServiceSettings().setAbortOnFailedContributor(true); UpdateFileIDsStep step = new FullUpdateFileIDsStep(collector, model, alerter, settings, TEST_COLLECTION, @@ -109,7 +112,7 @@ public Void answer(InvocationOnMock invocation) { try { step.performStep(); - Assert.fail("The step should have thrown an WorkflowAbortedException"); + Assertions.fail("The step should have thrown an WorkflowAbortedException"); } catch (WorkflowAbortedException e) { // nothing to do here } @@ -121,7 +124,8 @@ public Void answer(InvocationOnMock invocation) { verify(alerter).integrityFailed(anyString(), anyString()); } - @Test(groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public void testRetryCollectionWhenNegativeReply() throws WorkflowAbortedException { addDescription("Test the step for updating the file ids will retry on a FAILED event"); final ResultingFileIDs resultingFileIDs = createResultingFileIDs(TEST_FILE_1); @@ -134,7 +138,7 @@ public Void answer(InvocationOnMock invocation) { eventHandler.handleEvent(new ContributorFailedEvent(TEST_PILLAR_1, TEST_COLLECTION, ResponseCode.FAILURE)); eventHandler.handleEvent(new OperationFailedEvent(TEST_COLLECTION, "Operation failed", null)); } else { - eventHandler.handleEvent(new IdentificationCompleteEvent(TEST_COLLECTION, Arrays.asList(TEST_PILLAR_1))); + eventHandler.handleEvent(new IdentificationCompleteEvent(TEST_COLLECTION, List.of(TEST_PILLAR_1))); eventHandler.handleEvent(new FileIDsCompletePillarEvent( TEST_PILLAR_1, TEST_COLLECTION, resultingFileIDs, false)); eventHandler.handleEvent(new CompleteEvent(TEST_COLLECTION, null)); @@ -147,8 +151,8 @@ public Void answer(InvocationOnMock invocation) { any(EventHandler.class)); when(integrityContributors.getActiveContributors()) - .thenReturn(new HashSet<>(Arrays.asList(TEST_PILLAR_1))) - .thenReturn(new HashSet<>(Arrays.asList(TEST_PILLAR_1))) + .thenReturn(new HashSet<>(List.of(TEST_PILLAR_1))) + .thenReturn(new HashSet<>(List.of(TEST_PILLAR_1))) .thenReturn(new HashSet<>()); when(integrityContributors.getFailedContributors()).thenReturn(new HashSet<>()); @@ -165,7 +169,8 @@ public Void answer(InvocationOnMock invocation) { verify(integrityContributors).finishContributor(eq(TEST_PILLAR_1)); } - @Test(groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public void testContinueWorkflowWhenNegativeReply() throws WorkflowAbortedException { addDescription("Test the step for updating the file ids will continue when getting an FAILED operation event" + " when AbortOnFailedContributor is set to false"); @@ -181,8 +186,8 @@ public Void answer(InvocationOnMock invocation) { any(EventHandler.class)); when(integrityContributors.getActiveContributors()) - .thenReturn(new HashSet<>(Arrays.asList(TEST_PILLAR_1))).thenReturn(new HashSet<>()); - when(integrityContributors.getFailedContributors()).thenReturn(new HashSet<>(Arrays.asList(TEST_PILLAR_1))); + .thenReturn(new HashSet<>(List.of(TEST_PILLAR_1))).thenReturn(new HashSet<>()); + when(integrityContributors.getFailedContributors()).thenReturn(new HashSet<>(List.of(TEST_PILLAR_1))); settings.getReferenceSettings().getIntegrityServiceSettings().setAbortOnFailedContributor(false); UpdateFileIDsStep step = new FullUpdateFileIDsStep(collector, model, alerter, settings, TEST_COLLECTION, @@ -198,14 +203,15 @@ public Void answer(InvocationOnMock invocation) { - @Test(groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public void testIngestOfResults() throws WorkflowAbortedException { addDescription("Test the step for updating the file ids can ingest the data correctly into the store."); final ResultingFileIDs resultingFileIDs = createResultingFileIDs(TEST_FILE_1); doAnswer(new Answer() { public Void answer(InvocationOnMock invocation) { EventHandler eventHandler = (EventHandler) invocation.getArguments()[4]; - eventHandler.handleEvent(new IdentificationCompleteEvent(TEST_COLLECTION, Arrays.asList(TEST_PILLAR_1))); + eventHandler.handleEvent(new IdentificationCompleteEvent(TEST_COLLECTION, List.of(TEST_PILLAR_1))); eventHandler.handleEvent(new FileIDsCompletePillarEvent( TEST_PILLAR_1, TEST_COLLECTION, resultingFileIDs, false)); eventHandler.handleEvent(new CompleteEvent(TEST_COLLECTION, null)); @@ -216,7 +222,7 @@ public Void answer(InvocationOnMock invocation) { any(EventHandler.class)); when(integrityContributors.getActiveContributors()) - .thenReturn(new HashSet<>(Arrays.asList(TEST_PILLAR_1))).thenReturn(new HashSet<>()); + .thenReturn(new HashSet<>(List.of(TEST_PILLAR_1))).thenReturn(new HashSet<>()); UpdateFileIDsStep step = new FullUpdateFileIDsStep(collector, model, alerter, settings, TEST_COLLECTION, integrityContributors); @@ -226,7 +232,8 @@ public Void answer(InvocationOnMock invocation) { } - @Test(groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public void testPartialResults() throws WorkflowAbortedException { addDescription("Test that the number of partial is used for generating more than one request."); final ResultingFileIDs resultingFileIDs = createResultingFileIDs(TEST_FILE_1); @@ -238,7 +245,7 @@ public void testPartialResults() throws WorkflowAbortedException { boolean firstPage = true; public Void answer(InvocationOnMock invocation) { EventHandler eventHandler = (EventHandler) invocation.getArguments()[4]; - eventHandler.handleEvent(new IdentificationCompleteEvent(TEST_COLLECTION, Arrays.asList(TEST_PILLAR_1))); + eventHandler.handleEvent(new IdentificationCompleteEvent(TEST_COLLECTION, List.of(TEST_PILLAR_1))); eventHandler.handleEvent( new FileIDsCompletePillarEvent(TEST_PILLAR_1, TEST_COLLECTION, resultingFileIDs, firstPage)); firstPage = false; @@ -252,8 +259,8 @@ public Void answer(InvocationOnMock invocation) { any(EventHandler.class)); when(integrityContributors.getActiveContributors()) - .thenReturn(new HashSet<>(Arrays.asList(TEST_PILLAR_1))) - .thenReturn(new HashSet<>(Arrays.asList(TEST_PILLAR_1))) + .thenReturn(new HashSet<>(List.of(TEST_PILLAR_1))) + .thenReturn(new HashSet<>(List.of(TEST_PILLAR_1))) .thenReturn(new HashSet<>()); UpdateFileIDsStep step = new FullUpdateFileIDsStep(collector, model, alerter, settings, TEST_COLLECTION, diff --git a/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/workflow/step/WorkflowstepTest.java b/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/workflow/step/WorkflowstepTest.java index f6740ed49..e19a10689 100644 --- a/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/workflow/step/WorkflowstepTest.java +++ b/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/workflow/step/WorkflowstepTest.java @@ -31,7 +31,7 @@ import org.bitrepository.integrityservice.workflow.IntegrityContributors; import org.bitrepository.service.audit.AuditTrailManager; import org.jaccept.structure.ExtendedTestCase; -import org.testng.annotations.BeforeMethod; +import org.junit.jupiter.api.BeforeEach; import javax.xml.datatype.DatatypeConfigurationException; import javax.xml.datatype.DatatypeFactory; @@ -50,7 +50,7 @@ public class WorkflowstepTest extends ExtendedTestCase { protected AuditTrailManager auditManager; protected IntegrityContributors integrityContributors; - @BeforeMethod(alwaysRun = true) + @BeforeEach public void setup() throws DatatypeConfigurationException { settings = TestSettingsProvider.reloadSettings(this.getClass().getSimpleName()); settings.getRepositorySettings().getCollections().getCollection().get(0).getPillarIDs().getPillarID().clear(); diff --git a/bitrepository-monitoring-service/src/main/java/org/bitrepository/monitoringservice/alarm/BasicMonitoringServiceAlerter.java b/bitrepository-monitoring-service/src/main/java/org/bitrepository/monitoringservice/alarm/BasicMonitoringServiceAlerter.java index 68979bc4a..96aa20336 100644 --- a/bitrepository-monitoring-service/src/main/java/org/bitrepository/monitoringservice/alarm/BasicMonitoringServiceAlerter.java +++ b/bitrepository-monitoring-service/src/main/java/org/bitrepository/monitoringservice/alarm/BasicMonitoringServiceAlerter.java @@ -75,7 +75,7 @@ public void checkStatuses() { alarm.setAlarmCode(AlarmCode.COMPONENT_FAILURE); alarm.setAlarmText("The following components have become " + "unresponsive: " - + nonRespondingComponents.toString()); + + nonRespondingComponents); error(alarm); } } diff --git a/bitrepository-monitoring-service/src/main/java/org/bitrepository/monitoringservice/status/ComponentStatusStore.java b/bitrepository-monitoring-service/src/main/java/org/bitrepository/monitoringservice/status/ComponentStatusStore.java index caedf674a..fe4a4dec6 100644 --- a/bitrepository-monitoring-service/src/main/java/org/bitrepository/monitoringservice/status/ComponentStatusStore.java +++ b/bitrepository-monitoring-service/src/main/java/org/bitrepository/monitoringservice/status/ComponentStatusStore.java @@ -35,7 +35,7 @@ */ public class ComponentStatusStore implements StatusStore { /** The log.*/ - private Logger log = LoggerFactory.getLogger(getClass()); + private final Logger log = LoggerFactory.getLogger(getClass()); /** The mapping between components and their respective status.*/ private final ConcurrentMap statusMap; diff --git a/bitrepository-monitoring-service/src/test/java/org/bitrepository/monitoringservice/MockGetStatusClient.java b/bitrepository-monitoring-service/src/test/java/org/bitrepository/monitoringservice/MockGetStatusClient.java index 07d815d29..2e7d7eff2 100644 --- a/bitrepository-monitoring-service/src/test/java/org/bitrepository/monitoringservice/MockGetStatusClient.java +++ b/bitrepository-monitoring-service/src/test/java/org/bitrepository/monitoringservice/MockGetStatusClient.java @@ -25,7 +25,7 @@ import org.bitrepository.client.eventhandler.EventHandler; public class MockGetStatusClient implements GetStatusClient { - private int callsToShutdown = 0; + private final int callsToShutdown = 0; public int getCallsToShutdown() { return callsToShutdown; } diff --git a/bitrepository-monitoring-service/src/test/java/org/bitrepository/monitoringservice/alarm/MonitorAlerterTest.java b/bitrepository-monitoring-service/src/test/java/org/bitrepository/monitoringservice/alarm/MonitorAlerterTest.java index 360a3d294..c6ec055b4 100644 --- a/bitrepository-monitoring-service/src/test/java/org/bitrepository/monitoringservice/alarm/MonitorAlerterTest.java +++ b/bitrepository-monitoring-service/src/test/java/org/bitrepository/monitoringservice/alarm/MonitorAlerterTest.java @@ -31,8 +31,9 @@ import org.bitrepository.monitoringservice.status.ComponentStatusCode; import org.bitrepository.protocol.IntegrationTest; import org.bitrepository.settings.referencesettings.AlarmLevel; -import org.testng.Assert; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; import java.math.BigInteger; import java.util.HashMap; @@ -40,7 +41,8 @@ public class MonitorAlerterTest extends IntegrationTest { - @Test(groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public void testMonitorAlerter() throws Exception { addDescription("Tests the " + BasicMonitoringServiceAlerter.class.getName()); addStep("Setup", ""); @@ -52,12 +54,12 @@ public void testMonitorAlerter() throws Exception { BasicMonitoringServiceAlerter alerter = new BasicMonitoringServiceAlerter( settingsForCUT, messageBus, AlarmLevel.ERROR, store); - Assert.assertEquals(store.getCallsForGetStatusMap(), 0); + Assertions.assertEquals(0, store.getCallsForGetStatusMap()); addStep("Check statuses with an empty map.", "Should only make a call for GetStatusMap"); store.statuses = new HashMap<>(); alerter.checkStatuses(); - Assert.assertEquals(store.getCallsForGetStatusMap(), 1); + Assertions.assertEquals(1, store.getCallsForGetStatusMap()); alarmReceiver.checkNoMessageIsReceived(AlarmMessage.class); addStep("Check the status when a positive entry exists.", "Should make another call for the GetStatusMap"); @@ -65,7 +67,7 @@ public void testMonitorAlerter() throws Exception { cs.updateStatus(createPositiveStatus()); store.statuses.put(componentID, cs); alerter.checkStatuses(); - Assert.assertEquals(store.getCallsForGetStatusMap(), 2); + Assertions.assertEquals(2, store.getCallsForGetStatusMap()); alarmReceiver.checkNoMessageIsReceived(AlarmMessage.class); addStep("Check the status when a negative entry exists.", @@ -73,10 +75,10 @@ public void testMonitorAlerter() throws Exception { cs.updateReplies(); store.statuses.put(componentID, cs); alerter.checkStatuses(); - Assert.assertEquals(store.getCallsForGetStatusMap(), 3); + Assertions.assertEquals(3, store.getCallsForGetStatusMap()); alarmReceiver.waitForMessage(AlarmMessage.class); - Assert.assertEquals(cs.getStatus(), ComponentStatusCode.UNRESPONSIVE); + Assertions.assertEquals(ComponentStatusCode.UNRESPONSIVE, cs.getStatus()); } private ResultingStatus createPositiveStatus() { diff --git a/bitrepository-monitoring-service/src/test/java/org/bitrepository/monitoringservice/collector/StatusCollectorTest.java b/bitrepository-monitoring-service/src/test/java/org/bitrepository/monitoringservice/collector/StatusCollectorTest.java index 1d9a3c877..f2d975c2d 100644 --- a/bitrepository-monitoring-service/src/test/java/org/bitrepository/monitoringservice/collector/StatusCollectorTest.java +++ b/bitrepository-monitoring-service/src/test/java/org/bitrepository/monitoringservice/collector/StatusCollectorTest.java @@ -27,25 +27,29 @@ import org.bitrepository.monitoringservice.MockGetStatusClient; import org.bitrepository.monitoringservice.MockStatusStore; import org.jaccept.structure.ExtendedTestCase; -import org.testng.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; import javax.xml.datatype.DatatypeFactory; import javax.xml.datatype.Duration; +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class StatusCollectorTest extends ExtendedTestCase { Settings settings; - private int INTERVAL = 500; - private int INTERVAL_DELAY = 250; + private final int INTERVAL = 500; + private final int INTERVAL_DELAY = 250; - @BeforeClass (alwaysRun = true) + @BeforeAll public void setup() { settings = TestSettingsProvider.reloadSettings("StatusCollectorUnderTest"); } - @Test(groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public void testStatusCollector() throws Exception { addDescription("Tests the status collector."); addStep("Setup", ""); @@ -57,11 +61,11 @@ public void testStatusCollector() throws Exception { settings.getReferenceSettings().getMonitoringServiceSettings().setCollectionInterval(intervalXmlDur); addStep("Create the collector", ""); - Assert.assertEquals(store.getCallsForGetStatusMap(), 0); - Assert.assertEquals(store.getCallsForUpdateReplayCounts(), 0); - Assert.assertEquals(store.getCallsForUpdateStatus(), 0); - Assert.assertEquals(client.getCallsToGetStatus(), 0); - Assert.assertEquals(client.getCallsToShutdown(), 0); + Assertions.assertEquals(0, store.getCallsForGetStatusMap()); + Assertions.assertEquals(0, store.getCallsForUpdateReplayCounts()); + Assertions.assertEquals(0, store.getCallsForUpdateStatus()); + Assertions.assertEquals(0, client.getCallsToGetStatus()); + Assertions.assertEquals(0, client.getCallsToShutdown()); StatusCollector collector = new StatusCollector(client, settings, store, alerter); addStep("Start the collector", "It should immediately call the client and store."); @@ -69,33 +73,33 @@ public void testStatusCollector() throws Exception { synchronized(this) { wait(INTERVAL_DELAY); } - Assert.assertEquals(store.getCallsForGetStatusMap(), 0); - Assert.assertEquals(store.getCallsForUpdateReplayCounts(), 1); - Assert.assertEquals(store.getCallsForUpdateStatus(), 0); - Assert.assertEquals(client.getCallsToGetStatus(), 1); - Assert.assertEquals(client.getCallsToShutdown(), 0); + Assertions.assertEquals(0, store.getCallsForGetStatusMap()); + Assertions.assertEquals(1, store.getCallsForUpdateReplayCounts()); + Assertions.assertEquals(0, store.getCallsForUpdateStatus()); + Assertions.assertEquals(1, client.getCallsToGetStatus()); + Assertions.assertEquals(0, client.getCallsToShutdown()); addStep("wait 2 * the interval", "It should call the client and store two times more."); synchronized(this) { - wait(2 * INTERVAL); + wait(2L * INTERVAL); } collector.stop(); - Assert.assertEquals(store.getCallsForGetStatusMap(), 0); - Assert.assertEquals(store.getCallsForUpdateReplayCounts(), 3); - Assert.assertEquals(store.getCallsForUpdateStatus(), 0); - Assert.assertEquals(client.getCallsToGetStatus(), 3); - Assert.assertEquals(client.getCallsToShutdown(), 0); + Assertions.assertEquals(0, store.getCallsForGetStatusMap()); + Assertions.assertEquals(3, store.getCallsForUpdateReplayCounts()); + Assertions.assertEquals(0, store.getCallsForUpdateStatus()); + Assertions.assertEquals(3, client.getCallsToGetStatus()); + Assertions.assertEquals(0, client.getCallsToShutdown()); addStep("wait the interval + delay again", "It should not have made any more calls"); synchronized(this) { wait(INTERVAL + INTERVAL_DELAY); } - Assert.assertEquals(store.getCallsForGetStatusMap(), 0); - Assert.assertEquals(store.getCallsForUpdateReplayCounts(), 3); - Assert.assertEquals(store.getCallsForUpdateStatus(), 0); - Assert.assertEquals(client.getCallsToGetStatus(), 3); - Assert.assertEquals(client.getCallsToShutdown(), 0); + Assertions.assertEquals(0, store.getCallsForGetStatusMap()); + Assertions.assertEquals(3, store.getCallsForUpdateReplayCounts()); + Assertions.assertEquals(0, store.getCallsForUpdateStatus()); + Assertions.assertEquals(3, client.getCallsToGetStatus()); + Assertions.assertEquals(0, client.getCallsToShutdown()); } } diff --git a/bitrepository-monitoring-service/src/test/java/org/bitrepository/monitoringservice/collector/StatusEventHandlerTest.java b/bitrepository-monitoring-service/src/test/java/org/bitrepository/monitoringservice/collector/StatusEventHandlerTest.java index 2660c6806..3afa69037 100644 --- a/bitrepository-monitoring-service/src/test/java/org/bitrepository/monitoringservice/collector/StatusEventHandlerTest.java +++ b/bitrepository-monitoring-service/src/test/java/org/bitrepository/monitoringservice/collector/StatusEventHandlerTest.java @@ -5,16 +5,16 @@ * Copyright (C) 2010 - 2012 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% @@ -30,59 +30,61 @@ import org.bitrepository.monitoringservice.MockAlerter; import org.bitrepository.monitoringservice.MockStatusStore; import org.jaccept.structure.ExtendedTestCase; -import org.testng.Assert; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; public class StatusEventHandlerTest extends ExtendedTestCase { - + public static final String TEST_COLLECTION = "collection1"; - - @Test(groups = {"regressiontest"}) + + @Test + @Tag("regressiontest") public void testStatusEventHandler() throws Exception { addDescription("Test the GetStatusEventHandler handling of events"); addStep("Setup", ""); MockStatusStore store = new MockStatusStore(); MockAlerter alerter = new MockAlerter(); GetStatusEventHandler eventHandler = new GetStatusEventHandler(store, alerter); - + addStep("Validate initial calls to the mocks", "No calls expected"); - Assert.assertEquals(store.getCallsForGetStatusMap(), 0); - Assert.assertEquals(store.getCallsForUpdateReplayCounts(), 0); - Assert.assertEquals(store.getCallsForUpdateStatus(), 0); - Assert.assertEquals(alerter.getCallsForCheckStatuses(), 0); - + Assertions.assertEquals(0, store.getCallsForGetStatusMap()); + Assertions.assertEquals(0, store.getCallsForUpdateReplayCounts()); + Assertions.assertEquals(0, store.getCallsForUpdateStatus()); + Assertions.assertEquals(0, alerter.getCallsForCheckStatuses()); + addStep("Test an unhandled event.", "Should not make any calls."); AbstractOperationEvent event = new DefaultEvent(TEST_COLLECTION); event.setEventType(OperationEventType.WARNING); eventHandler.handleEvent(event); - - Assert.assertEquals(store.getCallsForGetStatusMap(), 0); - Assert.assertEquals(store.getCallsForUpdateReplayCounts(), 0); - Assert.assertEquals(store.getCallsForUpdateStatus(), 0); - Assert.assertEquals(alerter.getCallsForCheckStatuses(), 0); - + + Assertions.assertEquals(0, store.getCallsForGetStatusMap()); + Assertions.assertEquals(0, store.getCallsForUpdateReplayCounts()); + Assertions.assertEquals(0, store.getCallsForUpdateStatus()); + Assertions.assertEquals(0, alerter.getCallsForCheckStatuses()); + addStep("Test the Complete event", "Should make a call to the alerter"); event = new CompleteEvent(TEST_COLLECTION, null); eventHandler.handleEvent(event); - Assert.assertEquals(store.getCallsForGetStatusMap(), 0); - Assert.assertEquals(store.getCallsForUpdateReplayCounts(), 0); - Assert.assertEquals(store.getCallsForUpdateStatus(), 0); - Assert.assertEquals(alerter.getCallsForCheckStatuses(), 1); - + Assertions.assertEquals(0, store.getCallsForGetStatusMap()); + Assertions.assertEquals(0, store.getCallsForUpdateReplayCounts()); + Assertions.assertEquals(0, store.getCallsForUpdateStatus()); + Assertions.assertEquals(1, alerter.getCallsForCheckStatuses()); + addStep("Test the Failed event", "Should make another call to the alerter"); event = new OperationFailedEvent(null, "info", null); eventHandler.handleEvent(event); - Assert.assertEquals(store.getCallsForGetStatusMap(), 0); - Assert.assertEquals(store.getCallsForUpdateReplayCounts(), 0); - Assert.assertEquals(store.getCallsForUpdateStatus(), 0); - Assert.assertEquals(alerter.getCallsForCheckStatuses(), 2); - + Assertions.assertEquals(0, store.getCallsForGetStatusMap()); + Assertions.assertEquals(0, store.getCallsForUpdateReplayCounts()); + Assertions.assertEquals(0, store.getCallsForUpdateStatus()); + Assertions.assertEquals(2, alerter.getCallsForCheckStatuses()); + addStep("Test the component complete status", "Should attempt to update the store"); event = new StatusCompleteContributorEvent("ContributorID", "dummy-collection", null); eventHandler.handleEvent(event); - Assert.assertEquals(store.getCallsForGetStatusMap(), 0); - Assert.assertEquals(store.getCallsForUpdateReplayCounts(), 0); - Assert.assertEquals(store.getCallsForUpdateStatus(), 1); - Assert.assertEquals(alerter.getCallsForCheckStatuses(), 2); + Assertions.assertEquals(0, store.getCallsForGetStatusMap()); + Assertions.assertEquals(0, store.getCallsForUpdateReplayCounts()); + Assertions.assertEquals(1, store.getCallsForUpdateStatus()); + Assertions.assertEquals(2, alerter.getCallsForCheckStatuses()); } } diff --git a/bitrepository-monitoring-service/src/test/java/org/bitrepository/monitoringservice/status/ComponentStatusStoreTest.java b/bitrepository-monitoring-service/src/test/java/org/bitrepository/monitoringservice/status/ComponentStatusStoreTest.java index c93d24701..4c3b7f0a6 100644 --- a/bitrepository-monitoring-service/src/test/java/org/bitrepository/monitoringservice/status/ComponentStatusStoreTest.java +++ b/bitrepository-monitoring-service/src/test/java/org/bitrepository/monitoringservice/status/ComponentStatusStoreTest.java @@ -28,23 +28,27 @@ import org.bitrepository.common.settings.TestSettingsProvider; import org.bitrepository.common.utils.CalendarUtils; import org.jaccept.structure.ExtendedTestCase; -import org.testng.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; import java.util.HashSet; import java.util.Map; import java.util.Set; +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class ComponentStatusStoreTest extends ExtendedTestCase { Settings settings; - @BeforeClass (alwaysRun = true) + @BeforeAll public void setup() { settings = TestSettingsProvider.reloadSettings("ComponentStatusStoreUnderTest"); } - @Test(groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public void testComponentStatus() throws Exception { addDescription("Tests the compontent status"); addStep("Setup", ""); @@ -55,45 +59,45 @@ public void testComponentStatus() throws Exception { addStep("Validate the initial content", "Should be one component with a 'new and empty' component status."); Map statuses = store.getStatusMap(); - Assert.assertEquals(statuses.size(), 1); + Assertions.assertEquals(1, statuses.size()); ComponentStatus newStatus = new ComponentStatus(); - Assert.assertNotNull(statuses.get(componentId)); - Assert.assertEquals(statuses.get(componentId).getInfo(), newStatus.getInfo()); - Assert.assertEquals(statuses.get(componentId).getNumberOfMissingReplies(), newStatus.getNumberOfMissingReplies()); - Assert.assertEquals(statuses.get(componentId).getLastReplyDate(), newStatus.getLastReplyDate()); - Assert.assertEquals(statuses.get(componentId).getStatus(), newStatus.getStatus()); + Assertions.assertNotNull(statuses.get(componentId)); + Assertions.assertEquals(statuses.get(componentId).getInfo(), newStatus.getInfo()); + Assertions.assertEquals(statuses.get(componentId).getNumberOfMissingReplies(), newStatus.getNumberOfMissingReplies()); + Assertions.assertEquals(statuses.get(componentId).getLastReplyDate(), newStatus.getLastReplyDate()); + Assertions.assertEquals(statuses.get(componentId).getStatus(), newStatus.getStatus()); addStep("Update the replay counts and validate ", "it should increases the 'number of missing replies' by 1"); store.updateReplyCounts(); statuses = store.getStatusMap(); - Assert.assertEquals(statuses.size(), 1); - Assert.assertNotNull(statuses.get(componentId)); - Assert.assertEquals(statuses.get(componentId).getInfo(), newStatus.getInfo()); - Assert.assertEquals(statuses.get(componentId).getNumberOfMissingReplies(), 1); - Assert.assertEquals(statuses.get(componentId).getLastReplyDate(), newStatus.getLastReplyDate()); - Assert.assertEquals(statuses.get(componentId).getStatus(), newStatus.getStatus()); + Assertions.assertEquals(1, statuses.size()); + Assertions.assertNotNull(statuses.get(componentId)); + Assertions.assertEquals(statuses.get(componentId).getInfo(), newStatus.getInfo()); + Assertions.assertEquals(1, statuses.get(componentId).getNumberOfMissingReplies()); + Assertions.assertEquals(statuses.get(componentId).getLastReplyDate(), newStatus.getLastReplyDate()); + Assertions.assertEquals(statuses.get(componentId).getStatus(), newStatus.getStatus()); addStep("Test what happens when an invalid component id attempted to be updated.", "Should not affect content."); store.updateStatus("BAD-COMPONENT-ID", null); statuses = store.getStatusMap(); - Assert.assertEquals(statuses.size(), 1); - Assert.assertNotNull(statuses.get(componentId)); - Assert.assertEquals(statuses.get(componentId).getInfo(), newStatus.getInfo()); - Assert.assertEquals(statuses.get(componentId).getNumberOfMissingReplies(), 1); - Assert.assertEquals(statuses.get(componentId).getLastReplyDate(), newStatus.getLastReplyDate()); - Assert.assertEquals(statuses.get(componentId).getStatus(), newStatus.getStatus()); + Assertions.assertEquals(1, statuses.size()); + Assertions.assertNotNull(statuses.get(componentId)); + Assertions.assertEquals(statuses.get(componentId).getInfo(), newStatus.getInfo()); + Assertions.assertEquals(1, statuses.get(componentId).getNumberOfMissingReplies()); + Assertions.assertEquals(statuses.get(componentId).getLastReplyDate(), newStatus.getLastReplyDate()); + Assertions.assertEquals(statuses.get(componentId).getStatus(), newStatus.getStatus()); addStep("Try giving it a positive status", "Should be inserted into the store."); ResultingStatus resStatus = createPositiveStatus(); store.updateStatus(componentId, resStatus); statuses = store.getStatusMap(); - Assert.assertEquals(statuses.size(), 1); - Assert.assertNotNull(statuses.get(componentId)); - Assert.assertEquals(statuses.get(componentId).getInfo(), resStatus.getStatusInfo().getStatusText()); - Assert.assertEquals(statuses.get(componentId).getNumberOfMissingReplies(), 0); - Assert.assertEquals(statuses.get(componentId).getLastReplyDate(), resStatus.getStatusTimestamp()); - Assert.assertEquals(statuses.get(componentId).getStatus().value(), resStatus.getStatusInfo().getStatusCode().name()); + Assertions.assertEquals(1, statuses.size()); + Assertions.assertNotNull(statuses.get(componentId)); + Assertions.assertEquals(statuses.get(componentId).getInfo(), resStatus.getStatusInfo().getStatusText()); + Assertions.assertEquals(0, statuses.get(componentId).getNumberOfMissingReplies()); + Assertions.assertEquals(statuses.get(componentId).getLastReplyDate(), resStatus.getStatusTimestamp()); + Assertions.assertEquals(statuses.get(componentId).getStatus().value(), resStatus.getStatusInfo().getStatusCode().name()); } private ResultingStatus createPositiveStatus() { diff --git a/bitrepository-reference-pillar/pom.xml b/bitrepository-reference-pillar/pom.xml index 201fa8ebc..4b720e059 100644 --- a/bitrepository-reference-pillar/pom.xml +++ b/bitrepository-reference-pillar/pom.xml @@ -1,170 +1,194 @@ - - 4.0.0 - - org.bitrepository.reference - bitrepository-parent - 1.12-SNAPSHOT - + + 4.0.0 + + org.bitrepository.reference + bitrepository-parent + 1.12-SNAPSHOT + - bitrepository-reference-pillar - Bitrepository Reference Pillar - http://maven.apache.org - - - org.bitrepository.reference - bitrepository-core - ${project.version} - - - org.bitrepository.reference - bitrepository-service - ${project.version} - - - - org.bitrepository.reference - bitrepository-core - ${project.version} - test-jar - test - - - ${project.groupId} - bitrepository-service - ${project.version} - test-jar - test - - - ${project.groupId} - bitrepository-client - ${project.version} - test - - - ${project.groupId} - bitrepository-client - ${project.version} - test-jar - test - - - org.apache.activemq - activemq-broker - ${activemq.version} - test - - - - - - maven-jar-plugin - - - **/testprops/* - **/conf/* - **/checksumdb*.jar - - - - - maven-dependency-plugin - - - unpack-shared-sqlscripts - - unpack-dependencies - - generate-resources - - ${project.build.directory}/classes - ${project.groupId} - compile - bitrepository-service - true - **/*.sql - - - - - - maven-assembly-plugin - - posix - - src/main/assembly/assembly.xml - src/test/assembly/assembly.xml - src/main/assembly/deploy-assembly.xml - src/test/assembly/test-deploy-assembly.xml - - - - - distribution - package - - single - - - - - - - - - - org.eclipse.m2e - lifecycle-mapping - 1.0.0 - - - - - - org.apache.maven.plugins - maven-dependency-plugin - [2.8,) - - unpack-dependencies - - - - - - - - - - - - - - - - - integration-test - + bitrepository-reference-pillar + Bitrepository Reference Pillar + http://maven.apache.org + + + org.bitrepository.reference + bitrepository-core + ${project.version} + + + org.testng + testng + 7.11.0 + test + + + org.bitrepository.reference + bitrepository-service + ${project.version} + + + + org.bitrepository.reference + bitrepository-core + ${project.version} + test-jar + test + + + ${project.groupId} + bitrepository-service + ${project.version} + test-jar + test + + + ${project.groupId} + bitrepository-client + ${project.version} + test + + + ${project.groupId} + bitrepository-client + ${project.version} + test-jar + test + + + org.apache.activemq + activemq-broker + ${activemq.version} + test + + + - - maven-failsafe-plugin - - - src/test/resources/testprops/full-pillar-test.xml - src/test/resources/testprops/checksum-pillar-test.xml - - - - - - integration-test - verify - - - - + + maven-jar-plugin + + + **/testprops/* + **/conf/* + **/checksumdb*.jar + + + + + maven-dependency-plugin + + + unpack-shared-sqlscripts + + unpack-dependencies + + prepare-package + + ${project.build.directory}/classes + ${project.groupId} + compile + bitrepository-service + true + **/*.sql + + + + + + org.apache.maven.plugins + maven-surefire-plugin + 3.5.4 + + + org.junit.jupiter + junit-jupiter-engine + 5.13.4 + + + org.junit.platform + junit-platform-suite-engine + 1.13.4 + + + + + maven-assembly-plugin + + posix + + src/main/assembly/assembly.xml + src/test/assembly/assembly.xml + src/main/assembly/deploy-assembly.xml + src/test/assembly/test-deploy-assembly.xml + + + + + distribution + package + + single + + + + - - - + + + + + org.eclipse.m2e + lifecycle-mapping + 1.0.0 + + + + + + org.apache.maven.plugins + maven-dependency-plugin + [2.8,) + + unpack-dependencies + + + + + + + + + + + + + + + + + integration-test + + + + maven-failsafe-plugin + + + src/test/resources/testprops/full-pillar-test.xml + src/test/resources/testprops/checksum-pillar-test.xml + + + + + + integration-test + verify + + + + + + + + diff --git a/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/messagehandler/GetFileRequestHandler.java b/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/messagehandler/GetFileRequestHandler.java index 9d2828c38..220912442 100644 --- a/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/messagehandler/GetFileRequestHandler.java +++ b/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/messagehandler/GetFileRequestHandler.java @@ -49,9 +49,6 @@ import java.io.InputStream; import java.math.BigInteger; import java.net.URL; -import java.net.URLDecoder; -import java.nio.charset.StandardCharsets; -import java.util.UUID; public class GetFileRequestHandler extends PerformRequestHandler { private final Logger log = LoggerFactory.getLogger(getClass()); diff --git a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/BitrepositoryChecksumPillarTestSuite.java b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/BitrepositoryChecksumPillarTestSuite.java new file mode 100644 index 000000000..aac24f08d --- /dev/null +++ b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/BitrepositoryChecksumPillarTestSuite.java @@ -0,0 +1,67 @@ +package org.bitrepository.pillar; + +import org.bitrepository.pillar.integration.PillarSuiteExtension; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.platform.suite.api.ExcludeTags; +import org.junit.platform.suite.api.IncludeTags; +import org.junit.platform.suite.api.SelectClasses; +import org.junit.platform.suite.api.SelectPackages; +import org.junit.platform.suite.api.Suite; +import org.junit.platform.suite.api.SuiteDisplayName; + +/** + * BitrepositoryPillarTestSuite is a JUnit 5 suite class that groups and configures multiple test classes + * for the BitRepositoryPillar project. This suite uses JUnit 5 annotations to select test classes, packages, + * and tags, and extend the suite with custom extensions. + * + *

JUnit 5 Annotations Used:

+ *
    + *
  • {@link Suite}: Indicates that this class is a JUnit 5 suite. It groups multiple test classes + * into a single test suite.
  • + *
  • {@link SelectClasses}: Specifies the test classes to be included in the suite. The value is an array + * of class references to the test classes.
  • + *
  • {@link SelectPackages}: Specifies the test packages to be included in the suite. The value is an array + * of package names.
  • + *
  • {@link IncludeTags}: Specifies the tags to include in the suite. The value is an array of tag names.
  • + *
  • {@link ExcludeTags}: Specifies the tags to exclude from the suite. The value is an array of tag names.
  • + *
  • {@link ExtendWith}: Specifies the extensions to be applied to the suite. The value is an array of + * extension classes.
  • + *
+ * + *

Options in a JUnit 5 Suite:

+ *
    + *
  • Selecting Test Classes: Use the {@link SelectClasses} annotation to specify the test + * classes to be included in the suite. The value is an array of class references to the test classes.
  • + *
  • Selecting Test Packages: Use the {@link SelectPackages} annotation to specify the test + * packages to be included in the suite. The value is an array of package names.
  • + *
  • Selecting Tests by Tag: Use the {@link IncludeTags} and {@link ExcludeTags} annotations + * to specify the tags to include or exclude in the suite. The value is an array of tag names.
  • + *
  • Extending the Suite: Use the {@link ExtendWith} annotation to specify custom extensions + * to be applied to the suite. The value is an array of extension classes.
  • + *
+ * + *

Example Usage:

+ *
+ * {@code
+ * @Suite
+ * @SelectClasses({BitrepositoryPillarTest.class}) // List your test classes here
+ * @SelectPackages("org.bitrepository.pillar") // List your test packages here
+ * @IncludeTags("integration") // List your include tags here
+ * @ExcludeTags("slow") // List your exclude tags here
+ * @ExtendWith(GlobalSuiteExtension.class)
+ * public class BitrepositoryTestSuite {
+ *     // No need for methods here; this just groups and extends
+ * }
+ * }
+ * 
+ */ +@Suite +@SuiteDisplayName("Checksum Pillar Acceptance Test") +@SelectPackages({ + "org.bitrepository.pillar.messagehandling", + "org.bitrepository.pillar.integration" +}) +@IncludeTags({/*"regressiontest", */PillarTestGroups.CHECKSUM_PILLAR_TEST}) +@ExtendWith(PillarSuiteExtension.class) +public class BitrepositoryChecksumPillarTestSuite { +} diff --git a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/BitrepositoryPillarTestSuite.java b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/BitrepositoryPillarTestSuite.java new file mode 100644 index 000000000..663e37dc8 --- /dev/null +++ b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/BitrepositoryPillarTestSuite.java @@ -0,0 +1,67 @@ +package org.bitrepository.pillar; + +import org.bitrepository.pillar.integration.PillarSuiteExtension; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.platform.suite.api.ExcludeTags; +import org.junit.platform.suite.api.IncludeTags; +import org.junit.platform.suite.api.SelectClasses; +import org.junit.platform.suite.api.SelectPackages; +import org.junit.platform.suite.api.Suite; +import org.junit.platform.suite.api.SuiteDisplayName; + +/** + * BitrepositoryPillarTestSuite is a JUnit 5 suite class that groups and configures multiple test classes + * for the BitRepositoryPillar project. This suite uses JUnit 5 annotations to select test classes, packages, + * and tags, and extend the suite with custom extensions. + * + *

JUnit 5 Annotations Used:

+ *
    + *
  • {@link Suite}: Indicates that this class is a JUnit 5 suite. It groups multiple test classes + * into a single test suite.
  • + *
  • {@link SelectClasses}: Specifies the test classes to be included in the suite. The value is an array + * of class references to the test classes.
  • + *
  • {@link SelectPackages}: Specifies the test packages to be included in the suite. The value is an array + * of package names.
  • + *
  • {@link IncludeTags}: Specifies the tags to include in the suite. The value is an array of tag names.
  • + *
  • {@link ExcludeTags}: Specifies the tags to exclude from the suite. The value is an array of tag names.
  • + *
  • {@link ExtendWith}: Specifies the extensions to be applied to the suite. The value is an array of + * extension classes.
  • + *
+ * + *

Options in a JUnit 5 Suite:

+ *
    + *
  • Selecting Test Classes: Use the {@link SelectClasses} annotation to specify the test + * classes to be included in the suite. The value is an array of class references to the test classes.
  • + *
  • Selecting Test Packages: Use the {@link SelectPackages} annotation to specify the test + * packages to be included in the suite. The value is an array of package names.
  • + *
  • Selecting Tests by Tag: Use the {@link IncludeTags} and {@link ExcludeTags} annotations + * to specify the tags to include or exclude in the suite. The value is an array of tag names.
  • + *
  • Extending the Suite: Use the {@link ExtendWith} annotation to specify custom extensions + * to be applied to the suite. The value is an array of extension classes.
  • + *
+ * + *

Example Usage:

+ *
+ * {@code
+ * @Suite
+ * @SelectClasses({BitrepositoryPillarTest.class}) // List your test classes here
+ * @SelectPackages("org.bitrepository.pillar") // List your test packages here
+ * @IncludeTags("integration") // List your include tags here
+ * @ExcludeTags("slow") // List your exclude tags here
+ * @ExtendWith(GlobalSuiteExtension.class)
+ * public class BitrepositoryTestSuite {
+ *     // No need for methods here; this just groups and extends
+ * }
+ * }
+ * 
+ */ +@Suite +@SuiteDisplayName("Full Pillar Acceptance Test") +@SelectPackages({ + "org.bitrepository.pillar.messagehandling", + "org.bitrepository.pillar.integration" +}) +@IncludeTags({"regressiontest", PillarTestGroups.CHECKSUM_PILLAR_TEST}) +@ExtendWith(PillarSuiteExtension.class) +public class BitrepositoryPillarTestSuite { +} diff --git a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/DefaultPillarTest.java b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/DefaultPillarTest.java index 338bd9899..bc3118356 100644 --- a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/DefaultPillarTest.java +++ b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/DefaultPillarTest.java @@ -8,12 +8,12 @@ * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * + * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . @@ -111,7 +111,7 @@ protected void createReferencePillar() { } public void shutdownMediator() { - if(mediator != null) { + if (mediator != null) { mediator.close(); mediator = null; } @@ -121,11 +121,12 @@ public void shutdownMediator() { protected String getComponentID() { return "ReferencePillar-" + testMethodName; } + private void initializeArchiveWithEmptyFile() throws IOException { addFixture("Initialize the Reference pillar cache with an empty file in default collection " + collectionID); - archives.downloadFileForValidation(DEFAULT_FILE_ID, collectionID, new ByteArrayInputStream(new byte[0])); - archives.moveToArchive(DEFAULT_FILE_ID, collectionID); - csCache.insertChecksumCalculation(DEFAULT_FILE_ID, collectionID, EMPTY_FILE_CHECKSUM, new Date()); + archives.downloadFileForValidation(defaultFileId, collectionID, new ByteArrayInputStream(new byte[0])); + archives.moveToArchive(defaultFileId, collectionID); + csCache.insertChecksumCalculation(defaultFileId, collectionID, EMPTY_FILE_CHECKSUM, new Date()); } } diff --git a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/MediatorTest.java b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/MediatorTest.java index 0866dc3cf..f9d3490f6 100644 --- a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/MediatorTest.java +++ b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/MediatorTest.java @@ -35,9 +35,10 @@ import org.bitrepository.service.audit.MockAuditManager; import org.bitrepository.service.contributor.ResponseDispatcher; import org.bitrepository.service.contributor.handler.RequestHandler; -import org.testng.Assert; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; import java.math.BigInteger; import java.util.ArrayList; @@ -49,7 +50,7 @@ public class MediatorTest extends DefaultFixturePillarTest { MessageHandlerContext context; StorageModel model = null; - @BeforeMethod (alwaysRun=true) + @BeforeEach public void initialiseTest() { audits = new MockAuditManager(); context = new MessageHandlerContext( @@ -60,7 +61,9 @@ public void initialiseTest() { audits); } - @Test( groups = {"regressiontest", "pillartest"}) + @Test + @Tag("regressiontest") + @Tag("pillartest") public void testMediatorRuntimeExceptionHandling() { addDescription("Tests the handling of a runtime exception"); addStep("Setup create and start the mediator.", ""); @@ -84,8 +87,8 @@ public void testMediatorRuntimeExceptionHandling() { messageBus.sendMessage(request); MessageResponse response = clientReceiver.waitForMessage(IdentifyContributorsForGetStatusResponse.class); - Assert.assertEquals(response.getResponseInfo().getResponseCode(), ResponseCode.FAILURE); - Assert.assertNotNull(alarmReceiver.waitForMessage(AlarmMessage.class)); + Assertions.assertEquals(ResponseCode.FAILURE, response.getResponseInfo().getResponseCode()); + Assertions.assertNotNull(alarmReceiver.waitForMessage(AlarmMessage.class)); } finally { mediator.close(); } diff --git a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/common/SettingsHelperTest.java b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/common/SettingsHelperTest.java index c64ba2f3f..5963a36c6 100644 --- a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/common/SettingsHelperTest.java +++ b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/common/SettingsHelperTest.java @@ -22,17 +22,19 @@ package org.bitrepository.pillar.common; -import org.bitrepository.pillar.integration.func.Assert; import org.bitrepository.settings.repositorysettings.Collection; import org.bitrepository.settings.repositorysettings.PillarIDs; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class SettingsHelperTest { - @Test( groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public void getPillarCollectionsTest() { String myPillarID = "myPillarID"; String otherPillarID = "OtherPillar"; @@ -43,14 +45,14 @@ public void getPillarCollectionsTest() { collection.add(createCollection("otherCollection", new String[] {otherPillarID})); List myCollections = SettingsHelper.getPillarCollections(myPillarID, collection); - Assert.assertEquals(myCollections.size(), 2); - Assert.assertEquals("myFirstCollection", myCollections.get(0)); - Assert.assertEquals("mySecondCollection", myCollections.get(1)); + Assertions.assertEquals(2, myCollections.size()); + Assertions.assertEquals("myFirstCollection", myCollections.get(0)); + Assertions.assertEquals("mySecondCollection", myCollections.get(1)); List otherCollections = SettingsHelper.getPillarCollections(otherPillarID, collection); - Assert.assertEquals(otherCollections.size(), 2); - Assert.assertEquals("mySecondCollection", otherCollections.get(0)); - Assert.assertEquals("otherCollection", otherCollections.get(1)); + Assertions.assertEquals(2, otherCollections.size()); + Assertions.assertEquals("mySecondCollection", otherCollections.get(0)); + Assertions.assertEquals("otherCollection", otherCollections.get(1)); } private Collection createCollection(String collectionID, String[] pillarIDs) { diff --git a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/ChecksumPillarTestSuite.java b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/ChecksumPillarTestSuite.java new file mode 100644 index 000000000..395ddeded --- /dev/null +++ b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/ChecksumPillarTestSuite.java @@ -0,0 +1,52 @@ +package org.bitrepository.pillar.integration; + +import org.bitrepository.pillar.PillarTestGroups; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.platform.suite.api.IncludeTags; +import org.junit.platform.suite.api.SelectPackages; +import org.junit.platform.suite.api.Suite; +import org.junit.platform.suite.api.SuiteDisplayName; + +/** + * JUnit 5 suite entry-point for the Checksum Pillar acceptance tests. + * + *

Direct replacement for the TestNG suite XML: + *

{@code
+ * 
+ *   
+ *     
+ *     
+ *       
+ *     
+ *   
+ * 
+ * }
+ * + *

How to run

+ *
    + *
  • Maven: + * {@code mvn test -Dtest=ChecksumPillarTestSuite -Dbitrepository.pillar.type=checksum} + *
  • + *
  • IDE: Run this class directly as a JUnit 5 suite. + * Set the system property {@code bitrepository.pillar.type=checksum} in the + * run configuration. + *
  • + *
+ * + *

Pillar type

+ * The system property {@code bitrepository.pillar.type} tells {@link PillarSuiteExtension} + * whether to start a checksum or reference pillar. This suite defaults to {@code checksum}. + * If you need a reference-pillar suite, create a sibling class and set the property to + * {@code reference}. + */ +@Suite +@SuiteDisplayName("Checksum Pillar Acceptance Test") +@SelectPackages({ + "org.bitrepository.pillar.messagehandling", + "org.bitrepository.pillar.integration" +}) +@IncludeTags({"regressiontest", PillarTestGroups.CHECKSUM_PILLAR_TEST}) +@ExtendWith(PillarSuiteExtension.class) +public class ChecksumPillarTestSuite { + // Suite classes are purely declarative – no code here. +} diff --git a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/EmbeddedPillar.java b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/EmbeddedPillar.java index 0abeef08b..cc32fd3ea 100644 --- a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/EmbeddedPillar.java +++ b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/EmbeddedPillar.java @@ -6,16 +6,16 @@ * Copyright (C) 2010 - 2012 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% @@ -26,14 +26,14 @@ import org.bitrepository.common.utils.FileUtils; import org.bitrepository.pillar.Pillar; import org.bitrepository.pillar.PillarComponentFactory; -import org.bitrepository.protocol.messagebus.MessageBus; -import org.bitrepository.protocol.messagebus.MessageBusManager; import org.bitrepository.service.LifeCycledService; import org.bitrepository.settings.referencesettings.CollectionDirs; import org.bitrepository.settings.referencesettings.PillarType; import java.io.File; +import static org.bitrepository.protocol.IntegrationTest.messageBus; + public class EmbeddedPillar implements LifeCycledService { private final Pillar pillar; @@ -42,7 +42,8 @@ private EmbeddedPillar(Pillar pillar) { } @Override - public void start() {} + public void start() { + } @Override public void shutdown() { @@ -50,25 +51,26 @@ public void shutdown() { } public static EmbeddedPillar createReferencePillar(Settings pillarSettings) { - MessageBus messageBus = initialize(pillarSettings); pillarSettings.getReferenceSettings().getPillarSettings().setPillarType(PillarType.FILE); + initialize(pillarSettings); + System.out.println("DEBUG: EmbeddedPillar creating FILE pillar with messageBus@" + System.identityHashCode(messageBus)); return new EmbeddedPillar(PillarComponentFactory.getInstance().createPillar(pillarSettings, messageBus)); } public static EmbeddedPillar createChecksumPillar(Settings pillarSettings) { - MessageBus messageBus = initialize(pillarSettings); pillarSettings.getReferenceSettings().getPillarSettings().setPillarType(PillarType.CHECKSUM); + initialize(pillarSettings); + System.out.println("DEBUG: EmbeddedPillar creating CHECKSUM pillar with messageBus@" + System.identityHashCode(messageBus)); return new EmbeddedPillar(PillarComponentFactory.getInstance().createPillar(pillarSettings, messageBus)); } - private static MessageBus initialize(Settings pillarSettings) { + private static void initialize(Settings pillarSettings) { ReferencePillarDerbyDBTestUtils dbUtils = new ReferencePillarDerbyDBTestUtils(pillarSettings); dbUtils.createEmptyDatabases(); for (CollectionDirs collectionDir : pillarSettings.getReferenceSettings().getPillarSettings().getCollectionDirs()) { - for (String dir : collectionDir.getFileDirs() ) { + for (String dir : collectionDir.getFileDirs()) { FileUtils.deleteDirIfExists(new File(dir)); } } - return MessageBusManager.getMessageBus(); } } diff --git a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/PillarIntegrationTest.java b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/PillarIntegrationTest.java index 352e4f9ff..9e9e131dd 100644 --- a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/PillarIntegrationTest.java +++ b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/PillarIntegrationTest.java @@ -5,16 +5,16 @@ * Copyright (C) 2010 - 2012 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% @@ -37,6 +37,7 @@ import org.bitrepository.protocol.FileExchange; import org.bitrepository.protocol.IntegrationTest; import org.bitrepository.protocol.ProtocolComponentFactory; +import org.bitrepository.protocol.fileexchange.HttpServerConfiguration; import org.bitrepository.protocol.messagebus.MessageBusManager; import org.bitrepository.protocol.security.BasicMessageAuthenticator; import org.bitrepository.protocol.security.BasicMessageSigner; @@ -46,37 +47,48 @@ import org.bitrepository.protocol.security.MessageSigner; import org.bitrepository.protocol.security.OperationAuthorizer; import org.bitrepository.protocol.security.PermissionStore; -import org.bitrepository.protocol.security.SecurityManager; import org.jaccept.TestEventManager; -import org.testng.ITestContext; -import org.testng.ITestResult; -import org.testng.annotations.AfterClass; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.AfterSuite; -import org.testng.annotations.BeforeClass; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.TestInfo; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.api.extension.ExtendWith; import javax.jms.JMSException; import java.io.IOException; import java.io.InputStream; -import java.util.Arrays; +import java.io.UncheckedIOException; +import java.net.MalformedURLException; +import java.net.URL; /** * Super class for all tests which should test functionality on a single pillar. - * + *

* Note That no setup/teardown is possible in this test of external pillars, so tests need to be written * to be invariant against the initial pillar state. */ +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +@ExtendWith(PillarSuiteExtension.class) public abstract class PillarIntegrationTest extends IntegrationTest { - /** The path to the directory containing the integration test configuration files */ + /** + * The path to the directory containing the integration test configuration files + */ protected static final String PATH_TO_CONFIG_DIR = System.getProperty( "pillar.integrationtest.settings.path", - "conf"); /** The path to the directory containing the integration test configuration files */ + "conf"); + /** + * The path to the directory containing the integration test configuration files + */ protected static final String PATH_TO_TESTPROPS_DIR = System.getProperty( "pillar.integrationtest.testprops.path", "testprops"); public static final String TEST_CONFIGURATION_FILE_NAME = "pillar-integration-test.properties"; + private static String DEFAULT_UPLOAD_FILE_ADDRESS; + private static Object DEFAULT_DOWNLOAD_FILE_ADDRESS; protected static PillarIntegrationTestConfiguration testConfiguration; - private EmbeddedPillar embeddedPillar; + protected EmbeddedPillar embeddedPillar; protected PillarFileManager pillarFileManager; protected static ClientProvider clientProvider; @@ -84,38 +96,139 @@ public abstract class PillarIntegrationTest extends IntegrationTest { protected static String nonDefaultCollectionId; protected static String irrelevantCollectionId; protected static ClientEventLogger clientEventHandler; + protected static URL DEFAULT_FILE_URL; + protected static String DEFAULT_FILE_ID = "default-test-file.txt"; @Override protected void initializeCUT() { super.initializeCUT(); - reloadMessageBus(); + System.out.println("DEBUG: PillarIntegrationTest.initializeCUT - messageBus@" + System.identityHashCode(messageBus)); + clientProvider = new ClientProvider(securityManager, settingsForTestClient, testEventManager); pillarFileManager = new PillarFileManager(collectionID, - getPillarID(), settingsForTestClient, clientProvider, testEventManager, httpServerConfiguration); + getPillarID(), settingsForTestClient, clientProvider, testEventManager, httpServerConfiguration); clientEventHandler = new ClientEventLogger(testEventManager); } - @BeforeClass(alwaysRun = true) - @Override - public void initializeSuite(ITestContext testContext) { - testConfiguration = - new PillarIntegrationTestConfiguration(PATH_TO_TESTPROPS_DIR + "/" + TEST_CONFIGURATION_FILE_NAME); - super.initializeSuite(testContext); - //MessageBusManager.injectCustomMessageBus(MessageBusManager.DEFAULT_MESSAGE_BUS, messageBus); - setupRealMessageBus(); - startEmbeddedPillar(testContext); - reloadMessageBus(); + /** + * Runs once before all test methods in each concrete subclass. + * + *

The sequence replicates the original TestNG {@code initializeSuite()}: + *

    + *
  1. Load {@link PillarIntegrationTestConfiguration}.
  2. + *
  3. Replicate {@code super.initializeSuite()}: load Settings, create SecurityManager, etc.
  4. + *
  5. Start the embedded pillar (guarded: only once per suite).
  6. + *
  7. Set up the message bus.
  8. + *
  9. Create {@link ClientProvider} and resolve collection IDs.
  10. + *
  11. Upload the default test file.
  12. + *
+ */ + @BeforeAll + static void setupClass() throws Exception { + testConfiguration = new PillarIntegrationTestConfiguration( + PATH_TO_TESTPROPS_DIR + "/" + TEST_CONFIGURATION_FILE_NAME); + + PillarIntegrationTestHelper helper = new PillarIntegrationTestHelper(); + + settingsForCUT = helper.loadSettings(testConfiguration.getPillarUnderTestID()); + settingsForTestClient = helper.loadSettings("TestSuiteInitialiser"); + + helper.makeUserSpecificSettings(settingsForCUT); + helper.makeUserSpecificSettings(settingsForTestClient); + + httpServerConfiguration = new HttpServerConfiguration( + settingsForTestClient.getReferenceSettings().getFileExchangeSettings()); + collectionID = settingsForTestClient.getCollections().get(0).getID(); + + securityManager = helper.createSecurityManager(); + + DEFAULT_FILE_ID = "DefaultFile"; + try { + DEFAULT_FILE_URL = httpServerConfiguration.getURL(TestFileHelper.DEFAULT_FILE_ID); + DEFAULT_DOWNLOAD_FILE_ADDRESS = DEFAULT_FILE_URL.toExternalForm(); + DEFAULT_UPLOAD_FILE_ADDRESS = DEFAULT_FILE_URL.toExternalForm() + "-" + DEFAULT_FILE_ID; + } catch (MalformedURLException e) { + throw new RuntimeException("Never happens", e); + } + } + + @BeforeEach() + public void setupPillarIntegrationTest(TestInfo testInfo) { + if (testConfiguration == null) { + testConfiguration = new PillarIntegrationTestConfiguration(PATH_TO_TESTPROPS_DIR + "/" + TEST_CONFIGURATION_FILE_NAME); + } + + if (testConfiguration.useEmbeddedPillar() + && !PillarSuiteExtension.isPillarAlreadyStarted()) { + + SettingsUtils.initialize(settingsForCUT); + + EmbeddedPillar pillar; + if (PillarSuiteExtension.isChecksumPillar()) { + pillar = EmbeddedPillar.createChecksumPillar(settingsForCUT); + } else { + pillar = EmbeddedPillar.createReferencePillar(settingsForCUT); + } + + PillarSuiteExtension.registerPillar(pillar); + } + clientProvider = new ClientProvider(securityManager, settingsForTestClient, testEventManager); nonDefaultCollectionId = settingsForTestClient.getCollections().get(1).getID(); irrelevantCollectionId = settingsForTestClient.getCollections().get(2).getID(); - putDefaultFile(); +// putDefaultFile(); + } + + + /** + * Helper class to access instance methods from static context. + * Temporary instance used only during setupClass(). + */ + private static class PillarIntegrationTestHelper extends PillarIntegrationTest { + @Override + protected Settings loadSettings(String componentID) { + return super.loadSettings(componentID); + } + + @Override + protected org.bitrepository.protocol.security.SecurityManager createSecurityManager() { + return super.createSecurityManager(); + } + + protected void makeUserSpecificSettings(Settings settings) { + // From IntegrationTest - modify settings to add username postfix + String topicPostfix = getTopicPostfix(); + if (topicPostfix != null && !topicPostfix.isEmpty()) { + settings.getRepositorySettings().getProtocolSettings() + .setCollectionDestination(settings.getRepositorySettings() + .getProtocolSettings().getCollectionDestination() + topicPostfix); + settings.getRepositorySettings().getProtocolSettings() + .setAlarmDestination(settings.getRepositorySettings() + .getProtocolSettings().getAlarmDestination() + topicPostfix); + } + } } +// +// @AfterAll +// static void teardownClass() { +// if (!testConfiguration.useEmbeddedMessagebus()) { +// MessageBusManager.clear(); +// if (messageBus != null) { +// try { +// messageBus.close(); +// } catch (JMSException e) { +// e.printStackTrace(); +// } +// messageBus = null; +// } +// } +// } - @AfterClass(alwaysRun = true) + @AfterAll public void shutdownRealMessageBus() { - if(!useEmbeddedMessageBus()) { + if (!useEmbeddedMessageBus()) { MessageBusManager.clear(); - if(messageBus != null) { + if (messageBus != null) { try { messageBus.close(); } catch (JMSException e) { @@ -125,37 +238,58 @@ public void shutdownRealMessageBus() { } } } - - @AfterSuite(alwaysRun = true) - @Override - public void shutdownSuite() { - stopEmbeddedReferencePillar(); - super.shutdownSuite(); - } - @AfterMethod(alwaysRun = true) - public void addFailureContextInfo(ITestResult result) { + /** + * Runs before each test method. + * + *

Mirrors the original {@code initializeCUT()}: re-injects the ConversationMediator and + * creates the per-test helpers. + */ + @BeforeEach + void setupTest() { + reloadMessageBus(); + + clientProvider = new ClientProvider(securityManager, settingsForTestClient, testEventManager); + + pillarFileManager = new PillarFileManager( + collectionID, getPillarID(), settingsForTestClient, + clientProvider, testEventManager, httpServerConfiguration); + + clientEventHandler = new ClientEventLogger(testEventManager); } - protected void setupRealMessageBus() { - if(!useEmbeddedMessageBus()) { - MessageBusManager.clear(); - messageBus = MessageBusManager.getMessageBus(settingsForCUT, securityManager); - } else { - MessageBusManager.injectCustomMessageBus(MessageBusManager.DEFAULT_MESSAGE_BUS, messageBus); - } + @AfterEach + public void addFailureContextInfo() { } @Override protected void setupMessageBus() { //Shortcircuit this so the messagebus is NOT INITIALISED BEFORE THE CONFIGURATION - //super.setupMessageBus(); + super.setupMessageBus(); + setupRealMessageBus(); } - @Override - public void initMessagebus() { - //Shortcircuit this so the messagebus is NOT INITIALISED BEFORE THE CONFIGURATION - //super.initMessagebus(); + /** + * Sets up the message bus after the test configuration is available. + * + *

    + *
  • Real message bus: clear any stale instance, then obtain a fresh one.
  • + *
  • Embedded message bus: inject the already-started embedded instance so + * all components share it.
  • + *
+ */ + private static void setupRealMessageBus() { + if (!testConfiguration.useEmbeddedMessagebus()) { + MessageBusManager.clear(); + messageBus = MessageBusManager.getMessageBus(settingsForCUT, securityManager); + } else { + MessageBusManager.injectCustomMessageBus(MessageBusManager.DEFAULT_MESSAGE_BUS, messageBus); + } + } + + protected static void reloadMessageBus() { + ConversationMediatorManager.injectCustomConversationMediator( + new CollectionBasedConversationMediator(settingsForTestClient, securityManager)); } /** @@ -163,14 +297,19 @@ public void initMessagebus() { * The type of pillar (full or checksum) is baed on the test group used, eg. if the group is * checksumPillarTest a checksum pillar is started, else a normal 'full' reference pillar is started. *

- * @param testContext + * + * @param testInfo */ - protected void startEmbeddedPillar(ITestContext testContext) { + protected void startEmbeddedPillar(TestInfo testInfo) { + System.out.println("DEBUG: startEmbeddedPillar - useEmbeddedPillar=" + testConfiguration.useEmbeddedPillar()); + System.out.println("DEBUG: startEmbeddedPillar - tags=" + testInfo.getTags()); if (testConfiguration.useEmbeddedPillar()) { SettingsUtils.initialize(settingsForCUT); - if (Arrays.asList(testContext.getIncludedGroups()).contains(PillarTestGroups.CHECKSUM_PILLAR_TEST)) { + if (testInfo.getTags().contains(PillarTestGroups.CHECKSUM_PILLAR_TEST)) { + System.out.println("DEBUG: Creating CHECKSUM pillar"); embeddedPillar = EmbeddedPillar.createChecksumPillar(settingsForCUT); } else { + System.out.println("DEBUG: Creating REFERENCE pillar"); embeddedPillar = EmbeddedPillar.createReferencePillar(settingsForCUT); } } @@ -181,12 +320,15 @@ protected void stopEmbeddedReferencePillar() { embeddedPillar.shutdown(); } } + @Override public boolean useEmbeddedMessageBus() { return testConfiguration.useEmbeddedMessagebus(); } - /** Loads the pillar test specific settings */ + /** + * Loads the pillar test specific settings + */ @Override protected Settings loadSettings(String componentID) { SettingsProvider settingsLoader = @@ -197,7 +339,7 @@ protected Settings loadSettings(String componentID) { protected String getPillarID() { return testConfiguration.getPillarUnderTestID(); } - + protected long getOperationTimeout() { return testConfiguration.getPillarOperationTimeout(); } @@ -206,6 +348,7 @@ protected long getOperationTimeout() { * Overrides the default settings modification, as this only works if the test can inject the modified settings into * the pillar. This means that if we are not using an embedded pillar we need to use the 'raw' collection settings, * eg. we can not add a special postfix. + * * @Override */ protected String getTopicPostfix() { @@ -214,68 +357,88 @@ protected String getTopicPostfix() { } else return ""; } + /** + * Creates the SecurityManager. With an embedded pillar the parent implementation is + * sufficient; with an external pillar we build one from the private-key location in the + * test configuration. + */ @Override - protected SecurityManager createSecurityManager() { + protected org.bitrepository.protocol.security.SecurityManager createSecurityManager() { if (testConfiguration.useEmbeddedPillar()) { return super.createSecurityManager(); - } else { - PermissionStore permissionStore = new PermissionStore(); - MessageAuthenticator authenticator = new BasicMessageAuthenticator(permissionStore); - MessageSigner signer = new BasicMessageSigner(); - OperationAuthorizer authorizer = new BasicOperationAuthorizer(permissionStore); - org.bitrepository.protocol.security.SecurityManager securityManager = - new BasicSecurityManager(settingsForTestClient.getRepositorySettings(), - testConfiguration.getPrivateKeyFileLocation(), - authenticator, signer, authorizer, permissionStore, settingsForTestClient.getComponentID()); - return securityManager; } + + PermissionStore permissionStore = new PermissionStore(); + MessageAuthenticator authenticator = new BasicMessageAuthenticator(permissionStore); + MessageSigner signer = new BasicMessageSigner(); + OperationAuthorizer authorizer = new BasicOperationAuthorizer(permissionStore); + + return new BasicSecurityManager( + settingsForTestClient.getRepositorySettings(), + testConfiguration.getPrivateKeyFileLocation(), + authenticator, signer, authorizer, permissionStore, + settingsForTestClient.getComponentID()); } +// @Override +// protected SecurityManager createSecurityManager() { +// if (testConfiguration.useEmbeddedPillar()) { +// return super.createSecurityManager(); +// } else { +// PermissionStore permissionStore = new PermissionStore(); +// MessageAuthenticator authenticator = new BasicMessageAuthenticator(permissionStore); +// MessageSigner signer = new BasicMessageSigner(); +// OperationAuthorizer authorizer = new BasicOperationAuthorizer(permissionStore); +// return new BasicSecurityManager(settingsForTestClient.getRepositorySettings(), +// testConfiguration.getPrivateKeyFileLocation(), +// authenticator, signer, authorizer, permissionStore, settingsForTestClient.getComponentID()); +// } +// } + @Override protected String getComponentID() { return getPillarID() + "-test-client"; } - protected void reloadMessageBus() { - ConversationMediatorManager.injectCustomConversationMediator( - new CollectionBasedConversationMediator(settingsForTestClient, securityManager)); - } - @Override protected void afterMethodVerification() { // Do not run the normal verification of all messages been handled. Message receivers are only used for // logging purposes here. } - protected void putDefaultFile() { + protected static void putDefaultFile() { try { FileExchange fe = ProtocolComponentFactory.getInstance().getFileExchange(settingsForCUT); - try(InputStream fis = getClass().getClassLoader().getResourceAsStream("default-test-file.txt")) { - fe.putFile(fis, DEFAULT_FILE_URL); + try (InputStream fis = Thread.currentThread().getContextClassLoader().getResourceAsStream("default-test-file.txt")) { + fe.putFile(fis, defaultFileUrl); } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); + throw new UncheckedIOException(e); } - - + + clientProvider.getPutClient().putFile( - collectionID, DEFAULT_FILE_URL, DEFAULT_FILE_ID, 10L, TestFileHelper.getDefaultFileChecksum(), - null, clientEventHandler, null); + collectionID, defaultFileUrl, defaultFileId, 10L, TestFileHelper.getDefaultFileChecksum(), + null, clientEventHandler, null); clientProvider.getPutClient().putFile( - nonDefaultCollectionId, DEFAULT_FILE_URL, DEFAULT_FILE_ID, 10L, TestFileHelper.getDefaultFileChecksum(), + nonDefaultCollectionId, defaultFileUrl, defaultFileId, 10L, TestFileHelper.getDefaultFileChecksum(), null, clientEventHandler, null); } catch (OperationFailedException e) { throw new RuntimeException(e); } } - /** Used to listen for operation event and log this. */ + /** + * Used to listen for operation event and log this. + */ public class ClientEventLogger implements EventHandler { - /** The TestEventManager used to manage the event for the associated test. */ + /** + * The TestEventManager used to manage the event for the associated test. + */ private final TestEventManager testEventManager; - /** The constructor. + /** + * The constructor. * * @param testEventManager The TestEventManager used to manage the event for the associated test. */ @@ -286,7 +449,7 @@ public ClientEventLogger(TestEventManager testEventManager) { @Override public void handleEvent(OperationEvent event) { - testEventManager.addResult("Received event: "+ event); + testEventManager.addResult("Received event: " + event); } } } diff --git a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/PillarSuiteExtension.java b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/PillarSuiteExtension.java new file mode 100644 index 000000000..a678fbd16 --- /dev/null +++ b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/PillarSuiteExtension.java @@ -0,0 +1,77 @@ +package org.bitrepository.pillar.integration; + +import org.junit.jupiter.api.extension.BeforeAllCallback; +import org.junit.jupiter.api.extension.ExtensionContext; + +public class PillarSuiteExtension implements BeforeAllCallback { + + /** + * System property that selects the pillar type. + */ + public static final String PILLAR_TYPE_PROPERTY = "bitrepository.pillar.type"; + + private static final String CHECKSUM = "checksum"; + + /** + * The pillar instance (null until first test class registers it). + */ + private static volatile EmbeddedPillar embeddedPillar = null; + + /** + * Guard to ensure shutdown hook is only registered once. + */ + private static volatile boolean shutdownHookRegistered = false; + + /** + * Lock for synchronized access. + */ + private static final Object LOCK = new Object(); + + @Override + public void beforeAll(ExtensionContext context) { + // Extension hook – currently unused; registration happens via static method. + } + + /** + * Returns {@code true} if a pillar has already been started. + * {@link PillarIntegrationTest} calls this to decide whether to start a new one. + */ + public static boolean isPillarAlreadyStarted() { + return embeddedPillar != null; + } + + /** + * Registers the given {@link EmbeddedPillar} and ensures it will be shut down + * when the JVM exits. + * + *

This must be called exactly once, from the first test class's {@code @BeforeAll}. + */ + public static void registerPillar(EmbeddedPillar pillar) { + synchronized (LOCK) { + if (embeddedPillar != null) { + throw new IllegalStateException("Pillar already registered"); + } + embeddedPillar = pillar; + + // Register shutdown hook to ensure pillar is stopped even if tests fail + if (!shutdownHookRegistered) { + Runtime.getRuntime().addShutdownHook(new Thread(() -> { + if (embeddedPillar != null) { + embeddedPillar.shutdown(); + } + }, "pillar-shutdown")); + shutdownHookRegistered = true; + } + } + } + + /** + * Returns {@code true} when the suite should use a checksum pillar. + *

+ * {@code testContext.getIncludedGroups().contains("checksumPillarTest")}. + */ + public static boolean isChecksumPillar() { + String type = System.getProperty(PILLAR_TYPE_PROPERTY, CHECKSUM); + return CHECKSUM.equalsIgnoreCase(type); + } +} diff --git a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/Assert.java b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/Assert.java index a2739f3cd..dd34d774f 100644 --- a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/Assert.java +++ b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/Assert.java @@ -24,7 +24,7 @@ import java.util.List; -public class Assert extends org.testng.Assert { +public class Assert extends org.junit.jupiter.api.Assertions { public static void assertEmpty(List list2Test, String message) { if (!list2Test.isEmpty()) { diff --git a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/DefaultPillarIdentificationTest.java b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/DefaultPillarIdentificationTest.java index bcf9a5713..b52c7c0cc 100644 --- a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/DefaultPillarIdentificationTest.java +++ b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/DefaultPillarIdentificationTest.java @@ -26,11 +26,16 @@ import org.bitrepository.bitrepositorymessages.MessageRequest; import org.bitrepository.bitrepositorymessages.MessageResponse; import org.bitrepository.pillar.PillarTestGroups; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + public abstract class DefaultPillarIdentificationTest extends DefaultPillarMessagingTest { - @Test( groups = {PillarTestGroups.FULL_PILLAR_TEST, PillarTestGroups.CHECKSUM_PILLAR_TEST}) + @Test + @Tag(PillarTestGroups.FULL_PILLAR_TEST) + @Tag(PillarTestGroups.CHECKSUM_PILLAR_TEST) public void irrelevantCollectionTest() { addDescription("Verifies identification works correctly for a collection not defined for the pillar"); addStep("Sending a putFile identification with a irrelevant collectionID. eg. the " + @@ -44,7 +49,7 @@ public void irrelevantCollectionTest() { protected void assertPositivResponseIsReceived() { MessageResponse receivedResponse = receiveResponse(); - Assert.assertEquals(receivedResponse.getResponseInfo().getResponseCode(), - ResponseCode.IDENTIFICATION_POSITIVE); + Assertions.assertEquals(ResponseCode.IDENTIFICATION_POSITIVE, + receivedResponse.getResponseInfo().getResponseCode()); } } diff --git a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/DefaultPillarMessagingTest.java b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/DefaultPillarMessagingTest.java index 211a8d0b7..ab5f91c1b 100644 --- a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/DefaultPillarMessagingTest.java +++ b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/DefaultPillarMessagingTest.java @@ -5,16 +5,16 @@ * Copyright (C) 2010 - 2012 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% @@ -26,7 +26,10 @@ import org.bitrepository.bitrepositorymessages.MessageRequest; import org.bitrepository.bitrepositorymessages.MessageResponse; import org.bitrepository.pillar.PillarTestGroups; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + /** * Contains the tests for exploringa pillars handling of general messaging. The concrete class needs to @@ -35,7 +38,9 @@ */ public abstract class DefaultPillarMessagingTest extends PillarFunctionTest { - @Test( groups = {PillarTestGroups.FULL_PILLAR_TEST, PillarTestGroups.CHECKSUM_PILLAR_TEST} ) + @Test + @Tag(PillarTestGroups.FULL_PILLAR_TEST) + @Tag(PillarTestGroups.CHECKSUM_PILLAR_TEST) public void missingCollectionIDTest() { addDescription("Verifies the a missing collectionID in the request is rejected"); addStep("Sending a request without a collectionID.", @@ -45,15 +50,17 @@ public void missingCollectionIDTest() { messageBus.sendMessage(request); MessageResponse receivedResponse = receiveResponse(); - Assert.assertEquals(receivedResponse.getResponseInfo().getResponseCode(), - ResponseCode.REQUEST_NOT_UNDERSTOOD_FAILURE); + Assertions.assertEquals(ResponseCode.REQUEST_NOT_UNDERSTOOD_FAILURE, + receivedResponse.getResponseInfo().getResponseCode()); } - @Test ( groups = {PillarTestGroups.FULL_PILLAR_TEST, PillarTestGroups.CHECKSUM_PILLAR_TEST} ) + @Test + @Tag(PillarTestGroups.FULL_PILLAR_TEST) + @Tag(PillarTestGroups.CHECKSUM_PILLAR_TEST) public void otherCollectionTest() { addDescription("Verifies identification works correctly for a second collection defined for pillar"); addStep("Sending a identify request with a non-default collectionID (not the first collection) " + - "the pillar is part of", + "the pillar is part of", "The pillar under test should make a positive response"); MessageRequest request = createRequest(); request.setCollectionID(nonDefaultCollectionId); @@ -62,7 +69,10 @@ public void otherCollectionTest() { } protected abstract MessageRequest createRequest(); + protected abstract MessageResponse receiveResponse(); + protected abstract void assertPositivResponseIsReceived(); + protected abstract void assertNoResponseIsReceived(); } diff --git a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/DefaultPillarOperationTest.java b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/DefaultPillarOperationTest.java index 597e1f40b..e3edd0b12 100644 --- a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/DefaultPillarOperationTest.java +++ b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/DefaultPillarOperationTest.java @@ -24,12 +24,13 @@ import org.bitrepository.bitrepositoryelements.ResponseCode; import org.bitrepository.bitrepositorymessages.MessageResponse; +import org.junit.jupiter.api.Assertions; public abstract class DefaultPillarOperationTest extends DefaultPillarMessagingTest { protected void assertPositivResponseIsReceived() { MessageResponse receivedResponse = receiveResponse(); - Assert.assertEquals(receivedResponse.getResponseInfo().getResponseCode(), - ResponseCode.OPERATION_COMPLETED); + Assertions.assertEquals(ResponseCode.OPERATION_COMPLETED, + receivedResponse.getResponseInfo().getResponseCode()); } } diff --git a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/PillarFunctionTest.java b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/PillarFunctionTest.java index 31e3c5a6a..c07bdce80 100644 --- a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/PillarFunctionTest.java +++ b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/PillarFunctionTest.java @@ -5,16 +5,16 @@ * Copyright (C) 2010 - 2012 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% @@ -24,11 +24,11 @@ import org.bitrepository.pillar.integration.PillarIntegrationTest; import org.bitrepository.pillar.messagefactories.PutFileMessageFactory; import org.bitrepository.protocol.bus.MessageReceiver; -import org.testng.annotations.BeforeMethod; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.TestInfo; -import java.lang.reflect.Method; -import java.util.Arrays; import java.util.Collection; +import java.util.Collections; /** * The parent class for pillar acceptance tests. The tests can be run in a multi pillar collection has the tests will @@ -38,12 +38,14 @@ public abstract class PillarFunctionTest extends PillarIntegrationTest { protected static final Long DEFAULT_FILE_SIZE = 10L; protected PutFileMessageFactory msgFactory; protected String testSpecificFileID; - /** Used for receiving responses from the pillar */ + /** + * Used for receiving responses from the pillar + */ protected MessageReceiver clientReceiver; - @BeforeMethod(alwaysRun=true) - public void generalMethodSetup(Method method) throws Exception { - testSpecificFileID = method.getName() + "File-" + createDate(); + @BeforeEach + public void generalMethodSetup(TestInfo testInfo) throws Exception { + testSpecificFileID = testInfo.getTestMethod().orElseThrow().getName() + "File-" + createDate(); } @Override @@ -53,7 +55,7 @@ protected void registerMessageReceivers() { clientReceiver = new MessageReceiver(settingsForTestClient.getReceiverDestinationID(), testEventManager); addReceiver(clientReceiver); - Collection pillarFilter = Arrays.asList(testConfiguration.getPillarUnderTestID()); + Collection pillarFilter = Collections.singletonList(testConfiguration.getPillarUnderTestID()); clientReceiver.setFromFilter(pillarFilter); alarmReceiver.setFromFilter(pillarFilter); } diff --git a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/deletefile/DeleteFileRequestIT.java b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/deletefile/DeleteFileRequestIT.java index f8491c66b..bbb8e6e8d 100644 --- a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/deletefile/DeleteFileRequestIT.java +++ b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/deletefile/DeleteFileRequestIT.java @@ -5,16 +5,16 @@ * Copyright (C) 2010 - 2012 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% @@ -37,63 +37,66 @@ import org.bitrepository.pillar.PillarTestGroups; import org.bitrepository.pillar.integration.func.DefaultPillarOperationTest; import org.bitrepository.pillar.messagefactories.DeleteFileMessageFactory; -import org.testng.Assert; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; -import java.lang.reflect.Method; import java.util.concurrent.TimeUnit; public class DeleteFileRequestIT extends DefaultPillarOperationTest { protected DeleteFileMessageFactory msgFactory; private String pillarDestination; - @BeforeMethod(alwaysRun=true) - public void initialiseReferenceTest(Method method) throws Exception { + @BeforeEach + public void initialiseReferenceTest() throws Exception { pillarDestination = lookupDeleteFileDestination(); msgFactory = new DeleteFileMessageFactory(collectionID, settingsForTestClient, getPillarID(), pillarDestination); clientProvider.getPutClient().putFile( - collectionID, DEFAULT_FILE_URL, testSpecificFileID, 10L, TestFileHelper.getDefaultFileChecksum(), + collectionID, defaultFileUrl, testSpecificFileID, 10L, TestFileHelper.getDefaultFileChecksum(), null, null, null); clientProvider.getPutClient().putFile( - nonDefaultCollectionId, DEFAULT_FILE_URL, testSpecificFileID, 10L, TestFileHelper.getDefaultFileChecksum(), + nonDefaultCollectionId, defaultFileUrl, testSpecificFileID, 10L, TestFileHelper.getDefaultFileChecksum(), null, null, null); } - @Test( groups = {PillarTestGroups.FULL_PILLAR_TEST, PillarTestGroups.CHECKSUM_PILLAR_TEST}) + @Test + @Tag(PillarTestGroups.FULL_PILLAR_TEST) + @Tag(PillarTestGroups.CHECKSUM_PILLAR_TEST) public void normalDeleteFileTest() { addDescription("Tests a normal DeleteFile sequence"); addStep("Send a DeleteFile request to " + testConfiguration.getPillarUnderTestID(), "The pillar should generate a OPERATION_ACCEPTED_PROGRESS progress response followed by a " + - "OPERATION_COMPLETED final response"); + "OPERATION_COMPLETED final response"); DeleteFileRequest deleteRequest = (DeleteFileRequest) createRequest(); deleteRequest.setFileID(testSpecificFileID); messageBus.sendMessage(deleteRequest); DeleteFileProgressResponse progressResponse = clientReceiver.waitForMessage(DeleteFileProgressResponse.class, getOperationTimeout(), TimeUnit.SECONDS); - Assert.assertNotNull(progressResponse); - Assert.assertEquals(progressResponse.getCorrelationID(), deleteRequest.getCorrelationID()); - Assert.assertEquals(progressResponse.getFrom(), getPillarID()); - Assert.assertEquals(progressResponse.getPillarID(), getPillarID()); - Assert.assertEquals(progressResponse.getResponseInfo().getResponseCode(), - ResponseCode.OPERATION_ACCEPTED_PROGRESS); + Assertions.assertNotNull(progressResponse); + Assertions.assertEquals(progressResponse.getCorrelationID(), deleteRequest.getCorrelationID()); + Assertions.assertEquals(progressResponse.getFrom(), getPillarID()); + Assertions.assertEquals(progressResponse.getPillarID(), getPillarID()); + Assertions.assertEquals(ResponseCode.OPERATION_ACCEPTED_PROGRESS, + progressResponse.getResponseInfo().getResponseCode()); DeleteFileFinalResponse finalResponse = (DeleteFileFinalResponse) receiveResponse(); - Assert.assertNotNull(finalResponse); - Assert.assertEquals(finalResponse.getResponseInfo().getResponseCode(), ResponseCode.OPERATION_COMPLETED); - Assert.assertEquals(finalResponse.getCorrelationID(), deleteRequest.getCorrelationID()); - Assert.assertEquals(finalResponse.getFrom(), getPillarID()); - Assert.assertEquals(finalResponse.getPillarID(), getPillarID()); + Assertions.assertNotNull(finalResponse); + Assertions.assertEquals(ResponseCode.OPERATION_COMPLETED, finalResponse.getResponseInfo().getResponseCode()); + Assertions.assertEquals(finalResponse.getCorrelationID(), deleteRequest.getCorrelationID()); + Assertions.assertEquals(finalResponse.getFrom(), getPillarID()); + Assertions.assertEquals(finalResponse.getPillarID(), getPillarID()); } - - @Test( groups = {PillarTestGroups.FULL_PILLAR_TEST}) + + @Test + @Tag(PillarTestGroups.FULL_PILLAR_TEST) public void requestNewChecksumDeleteFileTest() { addDescription("Tests a normal DeleteFile sequence"); addStep("Send a DeleteFile request to " + testConfiguration.getPillarUnderTestID(), "The pillar should generate a OPERATION_ACCEPTED_PROGRESS progress response followed by a " + - "OPERATION_COMPLETED final response"); - + "OPERATION_COMPLETED final response"); + ChecksumSpecTYPE requestedChecksumSpec = new ChecksumSpecTYPE(); requestedChecksumSpec.setChecksumType(ChecksumType.HMAC_MD5); try { @@ -108,27 +111,27 @@ public void requestNewChecksumDeleteFileTest() { DeleteFileProgressResponse progressResponse = clientReceiver.waitForMessage(DeleteFileProgressResponse.class, getOperationTimeout(), TimeUnit.SECONDS); - Assert.assertNotNull(progressResponse); - Assert.assertEquals(progressResponse.getCorrelationID(), deleteRequest.getCorrelationID()); - Assert.assertEquals(progressResponse.getFrom(), getPillarID()); - Assert.assertEquals(progressResponse.getPillarID(), getPillarID()); - Assert.assertEquals(progressResponse.getResponseInfo().getResponseCode(), - ResponseCode.OPERATION_ACCEPTED_PROGRESS); + Assertions.assertNotNull(progressResponse); + Assertions.assertEquals(progressResponse.getCorrelationID(), deleteRequest.getCorrelationID()); + Assertions.assertEquals(progressResponse.getFrom(), getPillarID()); + Assertions.assertEquals(progressResponse.getPillarID(), getPillarID()); + Assertions.assertEquals(ResponseCode.OPERATION_ACCEPTED_PROGRESS, + progressResponse.getResponseInfo().getResponseCode()); DeleteFileFinalResponse finalResponse = (DeleteFileFinalResponse) receiveResponse(); - Assert.assertNotNull(finalResponse); - Assert.assertEquals(finalResponse.getResponseInfo().getResponseCode(), ResponseCode.OPERATION_COMPLETED); - Assert.assertEquals(finalResponse.getCorrelationID(), deleteRequest.getCorrelationID()); - Assert.assertEquals(finalResponse.getFrom(), getPillarID()); - Assert.assertNotNull(finalResponse.getChecksumDataForExistingFile()); - Assert.assertEquals(finalResponse.getChecksumDataForExistingFile().getChecksumSpec(), + Assertions.assertNotNull(finalResponse); + Assertions.assertEquals(ResponseCode.OPERATION_COMPLETED, finalResponse.getResponseInfo().getResponseCode()); + Assertions.assertEquals(finalResponse.getCorrelationID(), deleteRequest.getCorrelationID()); + Assertions.assertEquals(finalResponse.getFrom(), getPillarID()); + Assertions.assertNotNull(finalResponse.getChecksumDataForExistingFile()); + Assertions.assertEquals(finalResponse.getChecksumDataForExistingFile().getChecksumSpec(), requestedChecksumSpec); - Assert.assertEquals(finalResponse.getPillarID(), getPillarID()); + Assertions.assertEquals(finalResponse.getPillarID(), getPillarID()); } @Override protected MessageRequest createRequest() { - return msgFactory.createDeleteFileRequest(TestFileHelper.getDefaultFileChecksum(), null, DEFAULT_FILE_ID); + return msgFactory.createDeleteFileRequest(TestFileHelper.getDefaultFileChecksum(), null, defaultFileId); } @Override diff --git a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/deletefile/IdentifyPillarsForDeleteFileIT.java b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/deletefile/IdentifyPillarsForDeleteFileIT.java index 9f6998afc..57f80a78c 100644 --- a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/deletefile/IdentifyPillarsForDeleteFileIT.java +++ b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/deletefile/IdentifyPillarsForDeleteFileIT.java @@ -5,16 +5,16 @@ * Copyright (C) 2010 - 2012 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% @@ -28,82 +28,88 @@ import org.bitrepository.bitrepositorymessages.MessageResponse; import org.bitrepository.common.utils.ChecksumUtils; import org.bitrepository.pillar.PillarTestGroups; -import org.bitrepository.pillar.integration.func.Assert; import org.bitrepository.pillar.integration.func.DefaultPillarIdentificationTest; import org.bitrepository.pillar.messagefactories.DeleteFileMessageFactory; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + public class IdentifyPillarsForDeleteFileIT extends DefaultPillarIdentificationTest { protected DeleteFileMessageFactory msgFactory; - @BeforeMethod(alwaysRun=true) + @BeforeEach public void initialiseReferenceTest() throws Exception { msgFactory = new DeleteFileMessageFactory(collectionID, settingsForTestClient, getPillarID(), null); } - @Test( groups = {PillarTestGroups.FULL_PILLAR_TEST}) + @Test + @Tag(PillarTestGroups.FULL_PILLAR_TEST) public void normalIdentificationTest() { addDescription("Verifies the normal behaviour for deleteFile identification"); addStep("Sending a deleteFile identification.", - "The pillar under test should make a response with the correct elements."); - IdentifyPillarsForDeleteFileRequest identifyRequest = (IdentifyPillarsForDeleteFileRequest) createRequest(); + "The pillar under test should make a response with the correct elements."); + IdentifyPillarsForDeleteFileRequest identifyRequest = (IdentifyPillarsForDeleteFileRequest) createRequest(); messageBus.sendMessage(identifyRequest); IdentifyPillarsForDeleteFileResponse receivedIdentifyResponse = clientReceiver.waitForMessage( IdentifyPillarsForDeleteFileResponse.class); - Assert.assertEquals(receivedIdentifyResponse.getCollectionID(), identifyRequest.getCollectionID()); - Assert.assertEquals(receivedIdentifyResponse.getCorrelationID(), identifyRequest.getCorrelationID()); - Assert.assertEquals(receivedIdentifyResponse.getFrom(), getPillarID()); - Assert.assertEquals(receivedIdentifyResponse.getFileID(), DEFAULT_FILE_ID); - Assert.assertEquals(receivedIdentifyResponse.getPillarID(), getPillarID()); - Assert.assertNull(receivedIdentifyResponse.getPillarChecksumSpec()); - Assert.assertEquals(receivedIdentifyResponse.getResponseInfo().getResponseCode(), - ResponseCode.IDENTIFICATION_POSITIVE); - Assert.assertEquals(receivedIdentifyResponse.getDestination(), identifyRequest.getReplyTo()); + Assertions.assertEquals(receivedIdentifyResponse.getCollectionID(), identifyRequest.getCollectionID()); + Assertions.assertEquals(receivedIdentifyResponse.getCorrelationID(), identifyRequest.getCorrelationID()); + Assertions.assertEquals(receivedIdentifyResponse.getFrom(), getPillarID()); + Assertions.assertEquals(receivedIdentifyResponse.getFileID(), defaultFileId); + Assertions.assertEquals(receivedIdentifyResponse.getPillarID(), getPillarID()); + Assertions.assertNull(receivedIdentifyResponse.getPillarChecksumSpec()); + Assertions.assertEquals(ResponseCode.IDENTIFICATION_POSITIVE, + receivedIdentifyResponse.getResponseInfo().getResponseCode()); + Assertions.assertEquals(receivedIdentifyResponse.getDestination(), identifyRequest.getReplyTo()); } - @Test( groups = {PillarTestGroups.CHECKSUM_PILLAR_TEST}) + @Test + @Tag(PillarTestGroups.CHECKSUM_PILLAR_TEST) public void identificationTestForChecksumPillar() { addDescription("Verifies the normal behaviour for deleteFile identification for a checksum pillar"); addStep("Sending a deleteFile identification.", "The pillar under test should make a response with the correct elements. The only different from a " + - "full pillar is that the checksum pillar will respond with the default checksum spec."); + "full pillar is that the checksum pillar will respond with the default checksum spec."); IdentifyPillarsForDeleteFileRequest identifyRequest = (IdentifyPillarsForDeleteFileRequest) createRequest(); messageBus.sendMessage(identifyRequest); IdentifyPillarsForDeleteFileResponse receivedIdentifyResponse = clientReceiver.waitForMessage( IdentifyPillarsForDeleteFileResponse.class); - Assert.assertEquals(receivedIdentifyResponse.getCollectionID(), identifyRequest.getCollectionID()); - Assert.assertEquals(receivedIdentifyResponse.getCorrelationID(), identifyRequest.getCorrelationID()); - Assert.assertEquals(receivedIdentifyResponse.getFrom(), getPillarID()); - Assert.assertEquals(receivedIdentifyResponse.getPillarChecksumSpec().getChecksumType(), + Assertions.assertEquals(receivedIdentifyResponse.getCollectionID(), identifyRequest.getCollectionID()); + Assertions.assertEquals(receivedIdentifyResponse.getCorrelationID(), identifyRequest.getCorrelationID()); + Assertions.assertEquals(receivedIdentifyResponse.getFrom(), getPillarID()); + Assertions.assertEquals(receivedIdentifyResponse.getPillarChecksumSpec().getChecksumType(), ChecksumUtils.getDefault(settingsForCUT).getChecksumType()); - Assert.assertEquals(receivedIdentifyResponse.getPillarID(), getPillarID()); - Assert.assertEquals(receivedIdentifyResponse.getResponseInfo().getResponseCode(), - ResponseCode.IDENTIFICATION_POSITIVE); - Assert.assertEquals(receivedIdentifyResponse.getDestination(), identifyRequest.getReplyTo()); + Assertions.assertEquals(receivedIdentifyResponse.getPillarID(), getPillarID()); + Assertions.assertEquals(ResponseCode.IDENTIFICATION_POSITIVE, + receivedIdentifyResponse.getResponseInfo().getResponseCode()); + Assertions.assertEquals(receivedIdentifyResponse.getDestination(), identifyRequest.getReplyTo()); } - @Test( groups = {PillarTestGroups.FULL_PILLAR_TEST, PillarTestGroups.CHECKSUM_PILLAR_TEST}) + @Test + @Tag(PillarTestGroups.FULL_PILLAR_TEST) + @Tag(PillarTestGroups.CHECKSUM_PILLAR_TEST) public void fileDoesNotExistsTest() { addDescription("Verifies that a request for a non-existing file is handled correctly"); addStep("Sending a deleteFile identification for a file not in the pillar.", "The pillar under test should send a FILE_NOT_FOUND_FAILURE response."); IdentifyPillarsForDeleteFileRequest identifyRequest = msgFactory.createIdentifyPillarsForDeleteFileRequest( - NON_DEFAULT_FILE_ID); + nonDefaultFileId); messageBus.sendMessage(identifyRequest); IdentifyPillarsForDeleteFileResponse receivedIdentifyResponse = clientReceiver.waitForMessage( IdentifyPillarsForDeleteFileResponse.class); - Assert.assertEquals(receivedIdentifyResponse.getResponseInfo().getResponseCode(), - ResponseCode.FILE_NOT_FOUND_FAILURE); + Assertions.assertEquals(ResponseCode.FILE_NOT_FOUND_FAILURE, + receivedIdentifyResponse.getResponseInfo().getResponseCode()); } @Override protected MessageRequest createRequest() { - return msgFactory.createIdentifyPillarsForDeleteFileRequest(DEFAULT_FILE_ID); + return msgFactory.createIdentifyPillarsForDeleteFileRequest(defaultFileId); } @Override diff --git a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/getaudittrails/GetAuditTrailsTest.java b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/getaudittrails/GetAuditTrailsTest.java index 50224a84f..012542586 100644 --- a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/getaudittrails/GetAuditTrailsTest.java +++ b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/getaudittrails/GetAuditTrailsTest.java @@ -27,12 +27,14 @@ import org.bitrepository.client.exceptions.NegativeResponseException; import org.bitrepository.pillar.PillarTestGroups; import org.bitrepository.pillar.integration.func.PillarFunctionTest; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; import java.util.List; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + public class GetAuditTrailsTest extends PillarFunctionTest { @Override @@ -41,8 +43,10 @@ protected void initializeCUT() { settingsForTestClient.getRepositorySettings().getGetAuditTrailSettings().getNonPillarContributorIDs().clear(); } - @Test ( groups = {PillarTestGroups.FULL_PILLAR_TEST, PillarTestGroups.CHECKSUM_PILLAR_TEST} ) - public void eventSortingTest() throws NegativeResponseException{ + @Test + @Tag(PillarTestGroups.FULL_PILLAR_TEST) + @Tag(PillarTestGroups.CHECKSUM_PILLAR_TEST) + public void eventSortingTest() throws NegativeResponseException{ addDescription("Test whether the audit trails are sorted based on sequence numbers, with the largest " + "sequence number last.."); addFixture("Ensure at least two files are present on the pillar."); @@ -62,7 +66,9 @@ public void eventSortingTest() throws NegativeResponseException{ } } - @Test ( groups = {PillarTestGroups.FULL_PILLAR_TEST, PillarTestGroups.CHECKSUM_PILLAR_TEST} ) + @Test + @Tag(PillarTestGroups.FULL_PILLAR_TEST) + @Tag(PillarTestGroups.CHECKSUM_PILLAR_TEST) public void maxNumberOfResultTest() { addDescription("Verifies the size of the result set can be limited by setting the maxNumberOfResult parameter."); addFixture("Ensure at least two files are present on the pillar"); @@ -79,12 +85,14 @@ public void maxNumberOfResultTest() { "audit event in the full list."); AuditTrailQuery singleEventQuery = new AuditTrailQuery(getPillarID(), null, null, 1); List singleEventList = getAuditTrails(singleEventQuery, null); - assertEquals(singleEventList.size(), 1, "The result didn't contain a single event"); + assertEquals(1, singleEventList.size(), "The result didn't contain a single event"); assertEquals(singleEventList.get(0), originalAuditTrailEventList.get(0), "The returned event wasn't equal to the first event"); } - @Test ( groups = {PillarTestGroups.FULL_PILLAR_TEST, PillarTestGroups.CHECKSUM_PILLAR_TEST} ) + @Test + @Tag(PillarTestGroups.FULL_PILLAR_TEST) + @Tag(PillarTestGroups.CHECKSUM_PILLAR_TEST) public void minSequenceNumberTest() { addDescription("Test the pillar support for only retrieving events with sequence number higher than the " + "provided MinSequenceNumber" + @@ -119,7 +127,9 @@ public void minSequenceNumberTest() { "First event in second page different from last element in first page"); } - @Test ( groups = {PillarTestGroups.FULL_PILLAR_TEST, PillarTestGroups.CHECKSUM_PILLAR_TEST} ) + @Test + @Tag(PillarTestGroups.FULL_PILLAR_TEST) + @Tag(PillarTestGroups.CHECKSUM_PILLAR_TEST) public void maxSequenceNumberTest() { addDescription("Test the pillar support for only retrieving audit event with SequenceNumbers lower than " + "MaxSequenceNumber."); @@ -148,7 +158,7 @@ public void maxSequenceNumberTest() { AuditTrailQuery firstSequenceNumberQuery = new AuditTrailQuery(getPillarID(), null, smallestSequenceNumber, null); limitedEventList = getAuditTrails(firstSequenceNumberQuery, null); - assertEquals(limitedEventList.size(), 1, "Received list with size of " + limitedEventList.size() + " " + + assertEquals(1, limitedEventList.size(), "Received list with size of " + limitedEventList.size() + " " + "when requesting audit trail with MaxSequenceNumber set to first event (expected 1 event)"); assertEquals(limitedEventList.get(0), originalAuditTrailEventList.get(0), diff --git a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/getchecksums/GetChecksumQueryTest.java b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/getchecksums/GetChecksumQueryTest.java index 507fd185f..b35bbf93b 100644 --- a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/getchecksums/GetChecksumQueryTest.java +++ b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/getchecksums/GetChecksumQueryTest.java @@ -25,9 +25,10 @@ import org.bitrepository.bitrepositoryelements.ChecksumDataForChecksumSpecTYPE; import org.bitrepository.common.utils.CalendarUtils; import org.bitrepository.pillar.PillarTestGroups; -import org.bitrepository.pillar.integration.func.Assert; import org.bitrepository.pillar.integration.func.PillarFunctionTest; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; import javax.xml.datatype.XMLGregorianCalendar; import java.util.GregorianCalendar; @@ -35,7 +36,9 @@ public class GetChecksumQueryTest extends PillarFunctionTest { - @Test ( groups = {PillarTestGroups.FULL_PILLAR_TEST, PillarTestGroups.CHECKSUM_PILLAR_TEST} ) + @Test + @Tag(PillarTestGroups.FULL_PILLAR_TEST) + @Tag( PillarTestGroups.CHECKSUM_PILLAR_TEST) public void checksumSortingTest() { addDescription("Test whether the checksum result is sorted oldest to newest."); addFixture("Ensure at least two files are present on the pillar"); @@ -46,14 +49,16 @@ public void checksumSortingTest() { List originalChecksumList = pillarFileManager.getChecksums(null, null, null); for (int counter = 0 ; counter < originalChecksumList.size() - 1 ; counter ++) { - Assert.assertTrue(originalChecksumList.get(counter).getCalculationTimestamp().compare( + Assertions.assertTrue(originalChecksumList.get(counter).getCalculationTimestamp().compare( originalChecksumList.get(counter + 1).getCalculationTimestamp()) <= 0, "Checksum (" + counter + ") " + originalChecksumList.get(counter) + " newer than following checksum(" + counter + ") " + originalChecksumList.get(counter + 1)); } } - @Test ( groups = {PillarTestGroups.FULL_PILLAR_TEST, PillarTestGroups.CHECKSUM_PILLAR_TEST} ) + @Test + @Tag(PillarTestGroups.FULL_PILLAR_TEST) + @Tag(PillarTestGroups.CHECKSUM_PILLAR_TEST) public void maxNumberOfResultTest() { addDescription("Verifies the size of the result set can be limited by setting the maxNumberOfResult parameter."); addFixture("Ensure at least two files are present on the pillar"); @@ -68,12 +73,14 @@ public void maxNumberOfResultTest() { ContributorQuery singleChecksumQuery = new ContributorQuery(getPillarID(), null, null, 1); List singleChecksumList = pillarFileManager.getChecksums(null, singleChecksumQuery, null); - Assert.assertEquals(singleChecksumList.size(), 1, "The result didn't contain a single checksum"); - Assert.assertEquals(singleChecksumList.get(0), originalChecksumList.get(0), + Assertions.assertEquals(1, singleChecksumList.size(), "The result didn't contain a single checksum"); + Assertions.assertEquals(singleChecksumList.get(0), originalChecksumList.get(0), "The returned checksum wasn't equal to the oldest checksum"); } - @Test ( groups = {PillarTestGroups.FULL_PILLAR_TEST, PillarTestGroups.CHECKSUM_PILLAR_TEST} ) + @Test + @Tag(PillarTestGroups.FULL_PILLAR_TEST) + @Tag(PillarTestGroups.CHECKSUM_PILLAR_TEST) public void minTimeStampTest() { addDescription("Test the pillar support for only retrieving checksums newer that a given time. " + "Note that this test assumes there is at least 2 checksums with different timestamps." + @@ -86,7 +93,7 @@ public void minTimeStampTest() { "A list with at least 2 different timestamps (it is not the fault of the pillar if this fails, but " + "the test needs this to be satisfied to make sense)."); List originalChecksumList = pillarFileManager.getChecksums(null, null, null); - Assert.assertTrue(originalChecksumList.get(0).getCalculationTimestamp().compare( + Assertions.assertTrue(originalChecksumList.get(0).getCalculationTimestamp().compare( originalChecksumList.get(originalChecksumList.size()-1).getCalculationTimestamp()) != 0, "The timestamps of the first and last checksum are the same."); @@ -96,13 +103,13 @@ public void minTimeStampTest() { ContributorQuery query = new ContributorQuery(getPillarID(), oldestTimestamp.toGregorianCalendar().getTime(), null, null); List limitedChecksumList = pillarFileManager.getChecksums(null, query, null); - Assert.assertEquals(limitedChecksumList.size(), originalChecksumList.size(), + Assertions.assertEquals(limitedChecksumList.size(), originalChecksumList.size(), "Differing size of checksum lists"); - Assert.assertEquals(limitedChecksumList.get(0), originalChecksumList.get(0), + Assertions.assertEquals(limitedChecksumList.get(0), originalChecksumList.get(0), "Different first list element when setting oldest minTimestamp"); - Assert.assertEquals(limitedChecksumList.get(limitedChecksumList.size()-1), originalChecksumList.get(originalChecksumList.size()-1), + Assertions.assertEquals(limitedChecksumList.get(limitedChecksumList.size()-1), originalChecksumList.get(originalChecksumList.size()-1), "Different last list element when setting oldest minTimestamp"); - Assert.assertTrue(limitedChecksumList.get(0).getCalculationTimestamp().compare( + Assertions.assertTrue(limitedChecksumList.get(0).getCalculationTimestamp().compare( limitedChecksumList.get(limitedChecksumList.size()-1).getCalculationTimestamp()) <= 0, "First checksum has newer timestamp than last checksum"); @@ -111,10 +118,9 @@ public void minTimeStampTest() { XMLGregorianCalendar newestTimestamp = originalChecksumList.get(originalChecksumList.size()-1).getCalculationTimestamp(); query = new ContributorQuery(getPillarID(), newestTimestamp.toGregorianCalendar().getTime(), null, null); limitedChecksumList = pillarFileManager.getChecksums(null, query, null); - Assert.assertFalse(limitedChecksumList.isEmpty(), + Assertions.assertFalse(limitedChecksumList.isEmpty(), "Empty list returned when when minTimestamp is set to newest calculated checksum timestamp"); - Assert.assertTrue(limitedChecksumList.get(0).getCalculationTimestamp().compare(newestTimestamp) == 0, - "Different timestamps in the set of newest checksums." + limitedChecksumList); + Assertions.assertEquals(0, limitedChecksumList.get(0).getCalculationTimestamp().compare(newestTimestamp), "Different timestamps in the set of newest checksums." + limitedChecksumList); addStep("Request checksums with MinTimeStamp set to the timestamp of the newest checksum + 10 ms", "No checksums are returned."); @@ -122,12 +128,13 @@ public void minTimeStampTest() { newerThanNewestTimestamp.add(GregorianCalendar.MILLISECOND, 10); query = new ContributorQuery(getPillarID(), newerThanNewestTimestamp.getTime(), null, null); limitedChecksumList = pillarFileManager.getChecksums(null, query, null); - Assert.assertEmpty(limitedChecksumList, + Assertions.assertTrue(limitedChecksumList.isEmpty(), "Non-empty checksum list returned with newerThanNewestTimestamp(" + CalendarUtils.getXmlGregorianCalendar(newerThanNewestTimestamp) + ") query"); } - @Test ( groups = {PillarTestGroups.FULL_PILLAR_TEST, PillarTestGroups.CHECKSUM_PILLAR_TEST} ) + @Test + @Tag(PillarTestGroups.FULL_PILLAR_TEST) @Tag(PillarTestGroups.CHECKSUM_PILLAR_TEST) public void maxTimeStampTest() { addDescription("Test the pillar support for only retrieving checksums older than a given time. " + "Note that this test assumes there is at least 2 checksums with different timestamps. " + @@ -141,7 +148,7 @@ public void maxTimeStampTest() { "A list with at least 2 different timestamps (it is not the fault of the pillar if this fails, but " + "the test needs this to be satisfied to make sense)."); List originalChecksumList = pillarFileManager.getChecksums(null, null, null); - Assert.assertTrue(originalChecksumList.get(0).getCalculationTimestamp().compare( + Assertions.assertTrue(originalChecksumList.get(0).getCalculationTimestamp().compare( originalChecksumList.get(originalChecksumList.size()-1).getCalculationTimestamp()) != 0, "The timestamps of the first and last checksum are the same."); @@ -151,13 +158,13 @@ public void maxTimeStampTest() { ContributorQuery query = new ContributorQuery(getPillarID(), null, newestTimestamp.toGregorianCalendar().getTime(), null); List limitedChecksumList = pillarFileManager.getChecksums(null, query, null); - Assert.assertEquals(limitedChecksumList.size(), originalChecksumList.size(), + Assertions.assertEquals(limitedChecksumList.size(), originalChecksumList.size(), "Differing size of checksum lists"); - Assert.assertEquals(limitedChecksumList.get(0), originalChecksumList.get(0), + Assertions.assertEquals(limitedChecksumList.get(0), originalChecksumList.get(0), "Different first list element when setting newest maxTimestamp"); - Assert.assertEquals(limitedChecksumList.get(limitedChecksumList.size()-1), originalChecksumList.get(originalChecksumList.size()-1), + Assertions.assertEquals(limitedChecksumList.get(limitedChecksumList.size()-1), originalChecksumList.get(originalChecksumList.size()-1), "Different last list element when setting newest maxTimestamp"); - Assert.assertTrue(limitedChecksumList.get(0).getCalculationTimestamp().compare( + Assertions.assertTrue(limitedChecksumList.get(0).getCalculationTimestamp().compare( limitedChecksumList.get(limitedChecksumList.size()-1).getCalculationTimestamp()) <= 0, "First checksum has newer timestamp than last checksum"); @@ -167,9 +174,8 @@ public void maxTimeStampTest() { query = new ContributorQuery(getPillarID(), null, oldestTimestamp.toGregorianCalendar().getTime(), null); limitedChecksumList = pillarFileManager.getChecksums(null, query, null); - Assert.assertFalse(limitedChecksumList.isEmpty(), "At least one checksum with the oldest timestamp should be returned."); - Assert.assertTrue(limitedChecksumList.get(0).getCalculationTimestamp().compare(oldestTimestamp) == 0, - "Different timestamps in the set of oldest checksums." + limitedChecksumList); + Assertions.assertFalse(limitedChecksumList.isEmpty(), "At least one checksum with the oldest timestamp should be returned."); + Assertions.assertEquals(0, limitedChecksumList.get(0).getCalculationTimestamp().compare(oldestTimestamp), "Different timestamps in the set of oldest checksums." + limitedChecksumList); addStep("Request checksums with MaxTimeStamp set to the timestamp of the oldest checksum - 10 ms", "No checksums are returned."); @@ -177,7 +183,7 @@ public void maxTimeStampTest() { olderThanOldestTimestamp.add(GregorianCalendar.MILLISECOND, -10); query = new ContributorQuery(getPillarID(), null, olderThanOldestTimestamp.getTime(), null); limitedChecksumList = pillarFileManager.getChecksums(null, query, null); - Assert.assertEmpty(limitedChecksumList, + Assertions.assertTrue(limitedChecksumList.isEmpty(), "Non-empty checksum list returned with olderThanOldestTimestamp(" + CalendarUtils.getXmlGregorianCalendar(olderThanOldestTimestamp) + ") query"); } diff --git a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/getchecksums/GetChecksumTest.java b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/getchecksums/GetChecksumTest.java index 0d43ddef6..081860f95 100644 --- a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/getchecksums/GetChecksumTest.java +++ b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/getchecksums/GetChecksumTest.java @@ -5,16 +5,16 @@ * Copyright (C) 2010 - 2012 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% @@ -29,28 +29,33 @@ import org.bitrepository.common.utils.Base16Utils; import org.bitrepository.pillar.PillarTestGroups; import org.bitrepository.pillar.integration.func.PillarFunctionTest; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; import java.util.List; -import static org.testng.Assert.assertNotNull; -import static org.testng.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class GetChecksumTest extends PillarFunctionTest { - @BeforeClass + @BeforeAll public void retrieveFirst2Files() { //ToDo } - @Test ( groups = {PillarTestGroups.FULL_PILLAR_TEST, PillarTestGroups.CHECKSUM_PILLAR_TEST} ) + @Test + @Tag(PillarTestGroups.FULL_PILLAR_TEST) + @Tag(PillarTestGroups.CHECKSUM_PILLAR_TEST) public void md5ChecksumsForAllFilesTest() throws NegativeResponseException { addDescription("Test the pillar support for MD5 type checksums"); pillarFileManager.ensureNumberOfFilesOnPillar(2, testMethodName); addStep("Request MD5 checksums for all files on the pillar", - "A list (at least 2 long) of MD5 checksums should be returned."); + "A list (at least 2 long) of MD5 checksums should be returned."); ChecksumSpecTYPE checksumSpec = new ChecksumSpecTYPE(); checksumSpec.setChecksumType(ChecksumType.MD5); List checksums = pillarFileManager.getChecksums(checksumSpec, @@ -58,31 +63,33 @@ public void md5ChecksumsForAllFilesTest() throws NegativeResponseException { assertTrue(checksums.size() >= 2, "The length of the returned checksums were less that 2"); addStep("Retrieve the first two files and verify that the checksums are correct", - "Not implemented"); + "Not implemented"); // ToDo implement this } - - @Test ( groups = {PillarTestGroups.FULL_PILLAR_TEST} ) + + @Test + @Tag(PillarTestGroups.FULL_PILLAR_TEST) public void sha1ChecksumsForDefaultTest() throws NegativeResponseException { addDescription("Test the pillar support for SHA1 type checksums"); pillarFileManager.ensureNumberOfFilesOnPillar(2, testMethodName); addStep("Request SHA1 checksums for the DefaultFile on the pillar", - "The SHA1 checksum for the default file should be returned should be returned (Not checked yet)."); + "The SHA1 checksum for the default file should be returned should be returned (Not checked yet)."); ChecksumSpecTYPE checksumSpec = new ChecksumSpecTYPE(); checksumSpec.setChecksumType(ChecksumType.SHA1); List checksums = pillarFileManager.getChecksums( - checksumSpec, null, DEFAULT_FILE_ID); + checksumSpec, null, defaultFileId); assertNotNull(checksums.get(0)); } - @Test ( groups = {PillarTestGroups.FULL_PILLAR_TEST} ) + @Test + @Tag(PillarTestGroups.FULL_PILLAR_TEST) public void md5SaltChecksumsForDefaultTest() throws NegativeResponseException { addDescription("Test the pillar support for MD5 type checksums with a salt"); pillarFileManager.ensureNumberOfFilesOnPillar(2, testMethodName); addStep("Request salted MD5 checksums for the default on the pillar", - "The correct of SHA1 checksum should be returned (Not checked yet)."); + "The correct of SHA1 checksum should be returned (Not checked yet)."); ChecksumSpecTYPE checksumSpec = new ChecksumSpecTYPE(); checksumSpec.setChecksumType(ChecksumType.HMAC_MD5); try { @@ -91,17 +98,18 @@ public void md5SaltChecksumsForDefaultTest() throws NegativeResponseException { System.err.println(e.getMessage()); } List checksums = pillarFileManager.getChecksums( - checksumSpec, null, DEFAULT_FILE_ID); + checksumSpec, null, defaultFileId); assertNotNull(checksums.get(0)); } - - @Test ( groups = {PillarTestGroups.FULL_PILLAR_TEST} ) + + @Test + @Tag(PillarTestGroups.FULL_PILLAR_TEST) public void sha1SaltChecksumsForDefaultTest() throws NegativeResponseException { addDescription("Test the pillar support for SHA1 type checksums with a salt"); pillarFileManager.ensureNumberOfFilesOnPillar(2, testMethodName); addStep("Request salted SHA1 checksums for the default on the pillar", - "The correct of SHA1 checksum should be returned (Not checked yet)."); + "The correct of SHA1 checksum should be returned (Not checked yet)."); ChecksumSpecTYPE checksumSpec = new ChecksumSpecTYPE(); checksumSpec.setChecksumType(ChecksumType.HMAC_SHA1); try { @@ -110,7 +118,7 @@ public void sha1SaltChecksumsForDefaultTest() throws NegativeResponseException { System.err.println(e.getMessage()); } List checksums = pillarFileManager.getChecksums( - checksumSpec, null, DEFAULT_FILE_ID); + checksumSpec, null, defaultFileId); assertNotNull(checksums.get(0)); - } + } } diff --git a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/getchecksums/IdentifyPillarsForGetChecksumsIT.java b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/getchecksums/IdentifyPillarsForGetChecksumsIT.java index 51fd55102..a3cb8c580 100644 --- a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/getchecksums/IdentifyPillarsForGetChecksumsIT.java +++ b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/getchecksums/IdentifyPillarsForGetChecksumsIT.java @@ -5,16 +5,16 @@ * Copyright (C) 2010 - 2012 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% @@ -33,30 +33,34 @@ import org.bitrepository.pillar.PillarTestGroups; import org.bitrepository.pillar.integration.func.DefaultPillarIdentificationTest; import org.bitrepository.pillar.messagefactories.GetChecksumsMessageFactory; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertNotNull; public class IdentifyPillarsForGetChecksumsIT extends DefaultPillarIdentificationTest { protected GetChecksumsMessageFactory msgFactory; - @BeforeMethod(alwaysRun=true) + @BeforeEach public void initialiseReferenceTest() throws Exception { msgFactory = new GetChecksumsMessageFactory(collectionID, settingsForTestClient, getPillarID(), null); clearReceivers(); } - @Test( groups = {PillarTestGroups.FULL_PILLAR_TEST, PillarTestGroups.CHECKSUM_PILLAR_TEST}) + @Test + @Tag(PillarTestGroups.FULL_PILLAR_TEST) + @Tag(PillarTestGroups.CHECKSUM_PILLAR_TEST) public void normalIdentificationTest() { addDescription("Verifies the normal behaviour for getChecksums identification"); addStep("Setup for test", "2 files on the pillar"); pillarFileManager.ensureNumberOfFilesOnPillar(2, testMethodName); - + addStep("Sending a identify request.", - "The pillar under test should make a response with the correct elements."); - FileIDs fileids = FileIDsUtils.createFileIDs(DEFAULT_FILE_ID); + "The pillar under test should make a response with the correct elements."); + FileIDs fileids = FileIDsUtils.createFileIDs(defaultFileId); ChecksumSpecTYPE csSpec = ChecksumUtils.getDefault(settingsForCUT); addStep("Create and send the identify request message.", @@ -79,19 +83,21 @@ public void normalIdentificationTest() { assertEquals(receivedIdentifyResponse.getPillarID(), getPillarID(), "Received unexpected 'PillarID' in response."); assertNotNull(receivedIdentifyResponse.getReplyTo()); - assertEquals(receivedIdentifyResponse.getResponseInfo().getResponseCode(), - ResponseCode.IDENTIFICATION_POSITIVE, + assertEquals(ResponseCode.IDENTIFICATION_POSITIVE, + receivedIdentifyResponse.getResponseInfo().getResponseCode(), "Received unexpected 'Response' in response."); } - @Test( groups = {PillarTestGroups.FULL_PILLAR_TEST, PillarTestGroups.CHECKSUM_PILLAR_TEST}) + @Test + @Tag(PillarTestGroups.FULL_PILLAR_TEST) + @Tag(PillarTestGroups.CHECKSUM_PILLAR_TEST) public void nonExistingFileTest() { addDescription("Tests that the pillar is able to reject a GetChecksums requests for a file, which it " + - "does not have during the identification phase."); + "does not have during the identification phase."); addStep("Setup for test", "2 files on the pillar"); //pillarFileManager.ensureNumberOfFilesOnPillar(2, testMethodName); - FileIDs fileids = FileIDsUtils.createFileIDs(NON_DEFAULT_FILE_ID); + FileIDs fileids = FileIDsUtils.createFileIDs(nonDefaultFileId); ChecksumSpecTYPE csSpec = ChecksumUtils.getDefault(settingsForCUT); addStep("Create and send the identify request message.", @@ -105,12 +111,14 @@ public void nonExistingFileTest() { IdentifyPillarsForGetChecksumsResponse receivedIdentifyResponse = clientReceiver.waitForMessage( IdentifyPillarsForGetChecksumsResponse.class); assertNotNull(receivedIdentifyResponse.getFileIDs().getFileID()); - assertEquals(receivedIdentifyResponse.getResponseInfo().getResponseCode(), - ResponseCode.FILE_NOT_FOUND_FAILURE, + assertEquals(ResponseCode.FILE_NOT_FOUND_FAILURE, + receivedIdentifyResponse.getResponseInfo().getResponseCode(), "Received unexpected 'ResponseCode' in response."); } - - @Test( groups = {PillarTestGroups.FULL_PILLAR_TEST, PillarTestGroups.CHECKSUM_PILLAR_TEST}) + + @Test + @Tag(PillarTestGroups.FULL_PILLAR_TEST) + @Tag(PillarTestGroups.CHECKSUM_PILLAR_TEST) public void allFilesTest() { addDescription("Tests that the pillar accepts a GetChecksums requests for all files, even though it does not have any files."); FileIDs fileids = FileIDsUtils.getAllFileIDs(); @@ -126,14 +134,14 @@ public void allFilesTest() { "The pillar should make a response."); IdentifyPillarsForGetChecksumsResponse receivedIdentifyResponse = clientReceiver.waitForMessage( IdentifyPillarsForGetChecksumsResponse.class); - assertEquals(receivedIdentifyResponse.getResponseInfo().getResponseCode(), - ResponseCode.IDENTIFICATION_POSITIVE, + assertEquals(ResponseCode.IDENTIFICATION_POSITIVE, + receivedIdentifyResponse.getResponseInfo().getResponseCode(), "Received unexpected 'ResponseCode' in response."); } @Override protected MessageRequest createRequest() { - return msgFactory.createIdentifyPillarsForGetChecksumsRequest(ChecksumUtils.getDefault(settingsForCUT), + return msgFactory.createIdentifyPillarsForGetChecksumsRequest(ChecksumUtils.getDefault(settingsForCUT), FileIDsUtils.getAllFileIDs()); } diff --git a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/getfile/GetFileRequestIT.java b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/getfile/GetFileRequestIT.java index 0dc4088cf..afd64e785 100644 --- a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/getfile/GetFileRequestIT.java +++ b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/getfile/GetFileRequestIT.java @@ -11,28 +11,29 @@ import org.bitrepository.bitrepositorymessages.MessageResponse; import org.bitrepository.common.utils.TestFileHelper; import org.bitrepository.pillar.PillarTestGroups; -import org.bitrepository.pillar.integration.func.Assert; import org.bitrepository.pillar.integration.func.PillarFunctionTest; import org.bitrepository.pillar.messagefactories.GetFileMessageFactory; import org.bitrepository.protocol.FileExchange; import org.bitrepository.protocol.ProtocolComponentFactory; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInfo; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; import java.io.IOException; import java.io.InputStream; -import java.lang.reflect.Method; import java.math.BigInteger; import java.net.URL; import java.nio.charset.StandardCharsets; import java.util.concurrent.TimeUnit; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertNotNull; -import static org.testng.Assert.assertNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; public class GetFileRequestIT extends PillarFunctionTest { private final Logger log = LoggerFactory.getLogger(this.getClass()); @@ -40,28 +41,30 @@ public class GetFileRequestIT extends PillarFunctionTest { protected URL testFileURL = null; protected FileExchange fe = null; - @BeforeMethod(alwaysRun=true) - public void initialiseReferenceTest(Method method) throws Exception { + @BeforeEach + public void initialiseReferenceTest() throws Exception { String pillarDestination = lookupGetFileDestination(); msgFactory = new GetFileMessageFactory(collectionID, settingsForTestClient, getPillarID(), pillarDestination); - testFileURL = new URL(DEFAULT_FILE_URL.toExternalForm() + System.currentTimeMillis()); + testFileURL = new URL(defaultFileUrl.toExternalForm() + System.currentTimeMillis()); fe = ProtocolComponentFactory.getInstance().getFileExchange(settingsForCUT); } - @AfterMethod(alwaysRun=true) - public void cleanUp(Method method) { + @AfterEach + public void cleanUp(TestInfo testInfo) { try { fe.deleteFile(testFileURL); } catch (Exception e) { - log.warn("Could not clean up file '{}' after method '{}'", testFileURL, method.getName()); + log.warn("Could not clean up file '{}' after method '{}'", testFileURL, + testInfo.getTestMethod().get().getName()); } } - @Test(groups = {PillarTestGroups.FULL_PILLAR_TEST}) + @Test + @Tag(PillarTestGroups.FULL_PILLAR_TEST) public void normalGetFileTest() throws IOException { addDescription("Tests a normal GetFile sequence"); addStep("Send a getFile request to " + testConfiguration.getPillarUnderTestID(), - "The pillar should send a final response with the following elements:

    " + + "The pillar should send a final response with the following elements:
      " + "
    1. 'CollectionID' element corresponding to the supplied value
    2. " + "
    3. 'CorrelationID' element corresponding to the supplied value
    4. " + "
    5. 'From' element corresponding to the pillars component ID
    6. " + @@ -70,7 +73,7 @@ public void normalGetFileTest() throws IOException { "
    7. 'FilePart' element should be null
    8. " + "
    9. 'PillarID' element corresponding to the pillars component ID
    10. " + "
    11. 'FileID' element corresponding to the supplied fileID
    12. " + - "
    13. 'FileAddress' element corresponding to the supplied FileAddress
    14. " + + "
    15. 'FileAddress' element corresponding to the supplied FileAddress
    16. " + "
    17. 'ResponseInfo.ResponseCode' element should be OPERATION_COMPLETED
    18. " + "
    "); @@ -97,7 +100,7 @@ public void normalGetFileTest() throws IOException { "Received unexpected 'FileAddress' element."); assertEquals(finalResponse.getPillarID(), getPillarID(), "Received unexpected 'PillarID' element."); - assertEquals(finalResponse.getResponseInfo().getResponseCode(), ResponseCode.OPERATION_COMPLETED, + assertEquals(ResponseCode.OPERATION_COMPLETED, finalResponse.getResponseInfo().getResponseCode(), "Received unexpected 'ResponseCode' element."); try (InputStream localFileIS = TestFileHelper.getDefaultFile(); @@ -109,7 +112,8 @@ public void normalGetFileTest() throws IOException { } } - @Test(groups = {PillarTestGroups.FULL_PILLAR_TEST}) + @Test + @Tag(PillarTestGroups.FULL_PILLAR_TEST) public void getFileWithFilePartTest() throws IOException { addDescription("Tests that a pillar is able to return a specified FilePart in the final response"); addStep("Send a getFile request to " + testConfiguration.getPillarUnderTestID() + " with a specified " + @@ -139,7 +143,8 @@ public void getFileWithFilePartTest() throws IOException { } } - @Test(groups = {PillarTestGroups.FULL_PILLAR_TEST}) + @Test + @Tag(PillarTestGroups.FULL_PILLAR_TEST) public void getMissingFileTest() { addDescription("Tests that a pillar gives an error when trying to get a non-existing file"); addStep("Send a getFile request to " + testConfiguration.getPillarUnderTestID() + " with a " + @@ -150,11 +155,12 @@ public void getMissingFileTest() { messageBus.sendMessage(getRequest); GetFileFinalResponse finalResponse = (GetFileFinalResponse) receiveResponse(); - assertEquals(finalResponse.getResponseInfo().getResponseCode(), ResponseCode.FILE_NOT_FOUND_FAILURE, + assertEquals(ResponseCode.FILE_NOT_FOUND_FAILURE, finalResponse.getResponseInfo().getResponseCode(), "Received unexpected 'ResponseCode' element."); } - @Test( groups = {PillarTestGroups.FULL_PILLAR_TEST} ) + @Test + @Tag(PillarTestGroups.FULL_PILLAR_TEST) public void missingCollectionIDTest() { addDescription("Verifies the a missing collectionID in the request is rejected"); addStep("Sending a request without a collectionID.", @@ -164,11 +170,12 @@ public void missingCollectionIDTest() { messageBus.sendMessage(request); MessageResponse receivedResponse = receiveResponse(); - Assert.assertEquals(receivedResponse.getResponseInfo().getResponseCode(), - ResponseCode.REQUEST_NOT_UNDERSTOOD_FAILURE); + Assertions.assertEquals(ResponseCode.REQUEST_NOT_UNDERSTOOD_FAILURE, + receivedResponse.getResponseInfo().getResponseCode()); } - @Test ( groups = {PillarTestGroups.FULL_PILLAR_TEST} ) + @Test + @Tag(PillarTestGroups.FULL_PILLAR_TEST) public void otherCollectionTest() { addDescription("Verifies identification works correctly for a second collection defined for pillar"); addStep("Sending a identify request with a non-default collectionID (not the first collection) " + @@ -181,7 +188,7 @@ public void otherCollectionTest() { } protected MessageRequest createRequest() { - return msgFactory.createGetFileRequest(testFileURL.toExternalForm(), DEFAULT_FILE_ID); + return msgFactory.createGetFileRequest(testFileURL.toExternalForm(), defaultFileId); } protected MessageResponse receiveResponse() { @@ -204,7 +211,7 @@ public String lookupGetFileDestination() { protected void assertPositivResponseIsReceived() { MessageResponse receivedResponse = receiveResponse(); - Assert.assertEquals(receivedResponse.getResponseInfo().getResponseCode(), - ResponseCode.OPERATION_COMPLETED); + Assertions.assertEquals(ResponseCode.OPERATION_COMPLETED, + receivedResponse.getResponseInfo().getResponseCode()); } } diff --git a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/getfile/IdentifyPillarsForGetFileIT.java b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/getfile/IdentifyPillarsForGetFileIT.java index 49d453d36..d0c23f7b6 100644 --- a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/getfile/IdentifyPillarsForGetFileIT.java +++ b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/getfile/IdentifyPillarsForGetFileIT.java @@ -5,16 +5,16 @@ * Copyright (C) 2010 - 2012 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% @@ -27,25 +27,27 @@ import org.bitrepository.pillar.PillarTestGroups; import org.bitrepository.pillar.integration.func.PillarFunctionTest; import org.bitrepository.pillar.messagefactories.GetFileMessageFactory; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; -import static org.testng.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; public class IdentifyPillarsForGetFileIT extends PillarFunctionTest { protected GetFileMessageFactory msgFactory; - @BeforeMethod(alwaysRun=true) + @BeforeEach public void initialiseReferenceTest() throws Exception { msgFactory = new GetFileMessageFactory(collectionID, settingsForTestClient, getPillarID(), null); } - @Test( groups = {PillarTestGroups.FULL_PILLAR_TEST}) + @Test + @Tag(PillarTestGroups.FULL_PILLAR_TEST) public void goodCaseIdentificationIT() { addDescription("Tests the general IdentifyPillarsForGetFile functionality of the pillar for the successful scenario."); addStep("Create and send the identify request message.", "Should be received and handled by the pillar."); - IdentifyPillarsForGetFileRequest identifyRequest = msgFactory.createIdentifyPillarsForGetFileRequest(DEFAULT_FILE_ID); + IdentifyPillarsForGetFileRequest identifyRequest = msgFactory.createIdentifyPillarsForGetFileRequest(defaultFileId); messageBus.sendMessage(identifyRequest); addStep("Retrieve and validate the response getPillarID() the pillar.", @@ -58,32 +60,33 @@ public void goodCaseIdentificationIT() { "Received unexpected 'CorrelationID' in response."); assertEquals(receivedIdentifyResponse.getFrom(), getPillarID(), "Received unexpected 'From' in response."); - assertEquals(receivedIdentifyResponse.getFileID(), DEFAULT_FILE_ID, + assertEquals(receivedIdentifyResponse.getFileID(), defaultFileId, "Received unexpected 'FileID' in response."); assertEquals(receivedIdentifyResponse.getPillarID(), getPillarID(), "Received unexpected 'PillarID' in response."); - assertEquals(receivedIdentifyResponse.getResponseInfo().getResponseCode(), - ResponseCode.IDENTIFICATION_POSITIVE, + assertEquals(ResponseCode.IDENTIFICATION_POSITIVE, + receivedIdentifyResponse.getResponseInfo().getResponseCode(), "Received unexpected 'ResponseCode' in response."); assertEquals(receivedIdentifyResponse.getDestination(), identifyRequest.getReplyTo(), "Received unexpected 'ReplyTo' in response."); } - @Test( groups = {PillarTestGroups.FULL_PILLAR_TEST}) + @Test + @Tag(PillarTestGroups.FULL_PILLAR_TEST) public void nonExistingFileIdentificationIT() { addDescription("Tests the IdentifyPillarsForGetFile functionality of the pillar for a IdentificationForGetFile " + "for a non existing file."); addStep("Create and send the identify request message.", "Should be received and handled by the pillar."); - IdentifyPillarsForGetFileRequest identifyRequest = msgFactory.createIdentifyPillarsForGetFileRequest(NON_DEFAULT_FILE_ID); + IdentifyPillarsForGetFileRequest identifyRequest = msgFactory.createIdentifyPillarsForGetFileRequest(nonDefaultFileId); messageBus.sendMessage(identifyRequest); addStep("Retrieve and validate the response getPillarID() the pillar.", "The pillar should make a response."); IdentifyPillarsForGetFileResponse receivedIdentifyResponse = clientReceiver.waitForMessage( IdentifyPillarsForGetFileResponse.class); - assertEquals(receivedIdentifyResponse.getResponseInfo().getResponseCode(), - ResponseCode.FILE_NOT_FOUND_FAILURE); + assertEquals(ResponseCode.FILE_NOT_FOUND_FAILURE, + receivedIdentifyResponse.getResponseInfo().getResponseCode()); } } diff --git a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/getfileids/GetFileIDsQueryTest.java b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/getfileids/GetFileIDsQueryTest.java index fb0794b65..ce86516c5 100644 --- a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/getfileids/GetFileIDsQueryTest.java +++ b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/getfileids/GetFileIDsQueryTest.java @@ -26,20 +26,24 @@ import org.bitrepository.common.utils.CalendarUtils; import org.bitrepository.pillar.PillarTestGroups; import org.bitrepository.pillar.integration.func.PillarFunctionTest; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; import javax.xml.datatype.XMLGregorianCalendar; import java.util.GregorianCalendar; import java.util.List; import static org.bitrepository.pillar.integration.func.Assert.assertEmpty; -import static org.bitrepository.pillar.integration.func.Assert.assertEquals; -import static org.bitrepository.pillar.integration.func.Assert.assertTrue; -import static org.testng.Assert.assertFalse; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + public class GetFileIDsQueryTest extends PillarFunctionTest { - @Test ( groups = {PillarTestGroups.FULL_PILLAR_TEST, PillarTestGroups.CHECKSUM_PILLAR_TEST} ) + @Test + @Tag(PillarTestGroups.FULL_PILLAR_TEST) + @Tag(PillarTestGroups.CHECKSUM_PILLAR_TEST) public void fileidsSortingTest() { addDescription("Test whether the file id result is sorted oldest to newest."); addFixture("Ensure at least two files are present on the pillar"); @@ -60,7 +64,9 @@ public void fileidsSortingTest() { } } - @Test ( groups = {PillarTestGroups.FULL_PILLAR_TEST, PillarTestGroups.CHECKSUM_PILLAR_TEST} ) + @Test + @Tag(PillarTestGroups.FULL_PILLAR_TEST) + @Tag(PillarTestGroups.CHECKSUM_PILLAR_TEST) public void maxNumberOfResultTest() { addDescription("Verifies the size of the result set can be limited by setting the maxNumberOfResult parameter."); addFixture("Ensure at least two files are present on the pillar"); @@ -76,12 +82,14 @@ public void maxNumberOfResultTest() { "a single file id should be returned. The file id should be the oldest/first file id in the full list."); ContributorQuery singleFileIDQuery = new ContributorQuery(getPillarID(), null, null, 1); List singleFileIDList = pillarFileManager.getFileIDs(singleFileIDQuery); - assertEquals(singleFileIDList.size(), 1, "The result didn't contain a single file id"); + assertEquals(1, singleFileIDList.size(), "The result didn't contain a single file id"); assertEquals(singleFileIDList.get(0), originalFileIDsList.get(0), "The returned file id wasn't equal to the oldest file id"); } - @Test ( groups = {PillarTestGroups.FULL_PILLAR_TEST, PillarTestGroups.CHECKSUM_PILLAR_TEST} ) + @Test + @Tag(PillarTestGroups.FULL_PILLAR_TEST) + @Tag(PillarTestGroups.CHECKSUM_PILLAR_TEST) public void minTimeStampTest() { addDescription("Test the pillar support for only retrieving file ids newer that a given time. " + "Note that this test assumes there is at least 2 file ids with different timestamps."); @@ -112,10 +120,8 @@ public void minTimeStampTest() { query = new ContributorQuery(getPillarID(), newestTimestamp.toGregorianCalendar().getTime(), null, null); limitedFileIDsList = pillarFileManager.getFileIDs(query); - assertTrue(!limitedFileIDsList.isEmpty(), - "Empty list returned when when minTimestamp is set to newest calculated checksum timestamp"); - assertTrue(limitedFileIDsList.get(0).getLastModificationTime().compare(newestTimestamp) == 0, - "Different timestamps in the set of newest file ids." + limitedFileIDsList); + assertFalse(limitedFileIDsList.isEmpty(), "Empty list returned when when minTimestamp is set to newest calculated checksum timestamp"); + assertEquals(0, limitedFileIDsList.get(0).getLastModificationTime().compare(newestTimestamp), "Different timestamps in the set of newest file ids." + limitedFileIDsList); addStep("Request file ids with MinTimeStamp set to the timestamp of the newest file id + 10 ms", "No file ids are returned."); @@ -127,7 +133,9 @@ public void minTimeStampTest() { CalendarUtils.getXmlGregorianCalendar(newerThanNewestTimestamp) + ") query"); } - @Test ( groups = {PillarTestGroups.FULL_PILLAR_TEST, PillarTestGroups.CHECKSUM_PILLAR_TEST} ) + @Test + @Tag(PillarTestGroups.FULL_PILLAR_TEST) + @Tag(PillarTestGroups.CHECKSUM_PILLAR_TEST) public void maxTimeStampTest() { addDescription("Test the pillar support for only retrieving file ids older that a given time. " + "Note that this test assumes there is at least 2 file ids with different timestamps."); @@ -160,8 +168,7 @@ public void maxTimeStampTest() { limitedFileIDsList = pillarFileManager.getFileIDs(query); assertFalse(limitedFileIDsList.isEmpty(), "At least one file id with the oldest timestamp should be " + "returned. The folliwing fileIDs where received: "); - assertTrue(limitedFileIDsList.get(0).getLastModificationTime().compare(oldestTimestamp) == 0, - "Different timestamps in the set of oldest file ids." + limitedFileIDsList); + assertEquals(0, limitedFileIDsList.get(0).getLastModificationTime().compare(oldestTimestamp), "Different timestamps in the set of oldest file ids." + limitedFileIDsList); addStep("Request file ids with MaxTimeStamp set to the timestamp of the oldest file id - 10 ms", "No file ids are returned."); diff --git a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/getfileids/GetFileIDsTest.java b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/getfileids/GetFileIDsTest.java index 2114671b2..1d90a8522 100644 --- a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/getfileids/GetFileIDsTest.java +++ b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/getfileids/GetFileIDsTest.java @@ -5,16 +5,16 @@ * Copyright (C) 2010 - 2012 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% @@ -33,24 +33,24 @@ import org.bitrepository.pillar.PillarTestGroups; import org.bitrepository.pillar.integration.func.DefaultPillarOperationTest; import org.bitrepository.pillar.messagefactories.GetFileIDsMessageFactory; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; -import java.lang.reflect.Method; import java.util.concurrent.TimeUnit; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertNotNull; -import static org.testng.Assert.assertNull; -import static org.testng.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; public class GetFileIDsTest extends DefaultPillarOperationTest { protected GetFileIDsMessageFactory msgFactory; private String pillarDestination; - @BeforeMethod(alwaysRun=true) - public void initialiseReferenceTest(Method method) throws Exception { + @BeforeEach + public void initialiseReferenceTest() throws Exception { msgFactory = new GetFileIDsMessageFactory(collectionID, settingsForTestClient, getPillarID(), null); pillarDestination = lookupPillarDestination(); msgFactory = new GetFileIDsMessageFactory(collectionID, settingsForTestClient, getPillarID(), @@ -59,20 +59,22 @@ public void initialiseReferenceTest(Method method) throws Exception { clearReceivers(); } - @Test( groups = {PillarTestGroups.FULL_PILLAR_TEST, PillarTestGroups.CHECKSUM_PILLAR_TEST}) + @Test + @Tag(PillarTestGroups.FULL_PILLAR_TEST) + @Tag(PillarTestGroups.CHECKSUM_PILLAR_TEST) public void pillarGetFileIDsTestSuccessCase() throws Exception { addDescription("Tests the GetFileIDs functionality of the pillar for the successful scenario."); addStep("Create and send a GetFileIDsRequest to the pillar.", "A GetFileIDsProgressResponse should be sent to the client with correct attributes follow by " + - "a GetFileIDsFinalResponse."); + "a GetFileIDsFinalResponse."); GetFileIDsRequest getFileIDsRequest = msgFactory.createGetFileIDsRequest( FileIDsUtils.getAllFileIDs(), null); messageBus.sendMessage(getFileIDsRequest); addStep("Retrieve the ProgressResponse for the GetFileIDs request", "A GetFileIDs progress response should be sent to the client with correct attributes."); - GetFileIDsProgressResponse progressResponse = clientReceiver.waitForMessage(GetFileIDsProgressResponse.class, + GetFileIDsProgressResponse progressResponse = clientReceiver.waitForMessage(GetFileIDsProgressResponse.class, getOperationTimeout(), TimeUnit.SECONDS); assertNotNull(progressResponse); assertEquals(progressResponse.getCorrelationID(), getFileIDsRequest.getCorrelationID()); @@ -80,59 +82,65 @@ public void pillarGetFileIDsTestSuccessCase() throws Exception { assertEquals(progressResponse.getFrom(), getPillarID()); assertEquals(progressResponse.getPillarID(), getPillarID()); assertEquals(progressResponse.getReplyTo(), pillarDestination); - assertEquals(progressResponse.getResponseInfo().getResponseCode(), - ResponseCode.OPERATION_ACCEPTED_PROGRESS); + assertEquals(ResponseCode.OPERATION_ACCEPTED_PROGRESS, + progressResponse.getResponseInfo().getResponseCode()); addStep("Retrieve the FinalResponse for the GetFileIDs request", "The GetFileIDs response should be sent by the pillar."); GetFileIDsFinalResponse finalResponse = (GetFileIDsFinalResponse) receiveResponse(); assertNotNull(finalResponse); - assertEquals(finalResponse.getResponseInfo().getResponseCode(), ResponseCode.OPERATION_COMPLETED); + assertEquals(ResponseCode.OPERATION_COMPLETED, finalResponse.getResponseInfo().getResponseCode()); assertEquals(finalResponse.getCorrelationID(), getFileIDsRequest.getCorrelationID()); assertEquals(finalResponse.getFileIDs(), FileIDsUtils.getAllFileIDs()); assertEquals(finalResponse.getFrom(), getPillarID()); assertEquals(finalResponse.getPillarID(), getPillarID()); assertEquals(finalResponse.getReplyTo(), pillarDestination); assertNull(finalResponse.getResultingFileIDs().getResultAddress()); - assertTrue(finalResponse.getResultingFileIDs().getFileIDsData().getFileIDsDataItems().getFileIDsDataItem().size() >= 2, + assertTrue(finalResponse.getResultingFileIDs().getFileIDsData().getFileIDsDataItems().getFileIDsDataItem().size() >= 2, "Should be at least 2 files, but found: " + finalResponse.getResultingFileIDs().getFileIDsData().getFileIDsDataItems().getFileIDsDataItem().size()); } - @Test( groups = {PillarTestGroups.FULL_PILLAR_TEST, PillarTestGroups.CHECKSUM_PILLAR_TEST}) + @Test + @Tag(PillarTestGroups.FULL_PILLAR_TEST) + @Tag(PillarTestGroups.CHECKSUM_PILLAR_TEST) public void pillarGetFileIDsTestFailedNoSuchFileInOperation() throws Exception { addDescription("Tests that the pillar is able to handle requests for a non-existing file correctly during " + - "the operation phase."); - FileIDs fileids = FileIDsUtils.createFileIDs(NON_DEFAULT_FILE_ID); + "the operation phase."); + FileIDs fileids = FileIDsUtils.createFileIDs(nonDefaultFileId); addStep("Send a GetFileIDs request for a non-existing file.", "A FILE_NOT_FOUND_FAILURE response should be generated."); GetFileIDsRequest getFileIDsRequest = msgFactory.createGetFileIDsRequest(fileids, null); messageBus.sendMessage(getFileIDsRequest); GetFileIDsFinalResponse finalResponse = (GetFileIDsFinalResponse) receiveResponse(); - assertEquals(finalResponse.getResponseInfo().getResponseCode(), ResponseCode.FILE_NOT_FOUND_FAILURE); + assertEquals(ResponseCode.FILE_NOT_FOUND_FAILURE, finalResponse.getResponseInfo().getResponseCode()); } - @Test( groups = {PillarTestGroups.FULL_PILLAR_TEST, PillarTestGroups.CHECKSUM_PILLAR_TEST}) + @Test + @Tag(PillarTestGroups.FULL_PILLAR_TEST) + @Tag(PillarTestGroups.CHECKSUM_PILLAR_TEST) public void pillarGetFileIDsSpecificFileIDRequest() throws Exception { addDescription("Tests that the pillar is able to handle requests for a non-existing file correctly during " + - "the operation phase."); - FileIDs fileids = FileIDsUtils.createFileIDs(DEFAULT_FILE_ID); + "the operation phase."); + FileIDs fileids = FileIDsUtils.createFileIDs(defaultFileId); addStep("Create and send a GetFileIDsRequest to the pillar.", "A GetFileIDsProgressResponse should be sent to the client with correct attributes follow by " + - "a GetFileIDsFinalResponse."); + "a GetFileIDsFinalResponse."); GetFileIDsRequest getFileIDsRequest = msgFactory.createGetFileIDsRequest(fileids, null); messageBus.sendMessage(getFileIDsRequest); - + addStep("Retrieve the FinalResponse for the GetFileIDs request.", "A OPERATION_COMPLETE final response only containing the requested file-id."); GetFileIDsFinalResponse finalResponse = (GetFileIDsFinalResponse) receiveResponse(); - assertEquals(finalResponse.getResultingFileIDs().getFileIDsData().getFileIDsDataItems().getFileIDsDataItem().size(), 1); - assertEquals(finalResponse.getResultingFileIDs().getFileIDsData().getFileIDsDataItems().getFileIDsDataItem().get(0).getFileID(), DEFAULT_FILE_ID); + assertEquals(1, finalResponse.getResultingFileIDs().getFileIDsData().getFileIDsDataItems().getFileIDsDataItem().size()); + assertEquals(finalResponse.getResultingFileIDs().getFileIDsData().getFileIDsDataItems().getFileIDsDataItem().get(0).getFileID(), defaultFileId); assertFalse(finalResponse.isSetPartialResult() && finalResponse.isPartialResult()); } - - @Test( groups = {PillarTestGroups.FULL_PILLAR_TEST, PillarTestGroups.CHECKSUM_PILLAR_TEST}) + + @Test + @Tag(PillarTestGroups.FULL_PILLAR_TEST) + @Tag(PillarTestGroups.CHECKSUM_PILLAR_TEST) public void pillarGetFileIDsTestBadDeliveryURL() throws Exception { addDescription("Test the case when the delivery URL is unaccessible."); String badURL = "http://localhost:61616/¾"; @@ -143,26 +151,26 @@ public void pillarGetFileIDsTestBadDeliveryURL() throws Exception { addStep("Retrieve the FinalResponse for the GetFileIDs request.", "A FILE_TRANSFER_FAILURE final response is expected."); GetFileIDsFinalResponse finalResponse = (GetFileIDsFinalResponse) receiveResponse(); - assertEquals(finalResponse.getResponseInfo().getResponseCode(), - ResponseCode.FILE_TRANSFER_FAILURE); + assertEquals(ResponseCode.FILE_TRANSFER_FAILURE, + finalResponse.getResponseInfo().getResponseCode()); } - @Test( groups = { - PillarTestGroups.FULL_PILLAR_TEST, - PillarTestGroups.CHECKSUM_PILLAR_TEST, - PillarTestGroups.RESULT_UPLOAD}) + @Test + @Tag(PillarTestGroups.FULL_PILLAR_TEST) + @Tag(PillarTestGroups.CHECKSUM_PILLAR_TEST) + @Tag(PillarTestGroups.RESULT_UPLOAD) public void pillarGetFileIDsTestDeliveryThroughUpload() throws Exception { addDescription("Test the case when the results should be delivered through the message ."); GetFileIDsRequest getFileIDsRequest = msgFactory.createGetFileIDsRequest( - FileIDsUtils.getAllFileIDs(), DEFAULT_UPLOAD_FILE_ADDRESS); + FileIDsUtils.getAllFileIDs(), defaultUploadFileAddress); messageBus.sendMessage(getFileIDsRequest); addStep("Retrieve the FinalResponse for the GetFileIDs request.", "A OPERATION_COMPLETE final response is expected containing the result provided address."); GetFileIDsFinalResponse finalResponse = (GetFileIDsFinalResponse) receiveResponse(); - assertEquals(finalResponse.getResponseInfo().getResponseCode(), - ResponseCode.OPERATION_COMPLETED); - assertEquals(finalResponse.getResultingFileIDs().getResultAddress(), DEFAULT_UPLOAD_FILE_ADDRESS); + assertEquals(ResponseCode.OPERATION_COMPLETED, + finalResponse.getResponseInfo().getResponseCode()); + assertEquals(finalResponse.getResultingFileIDs().getResultAddress(), defaultUploadFileAddress); } @Override diff --git a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/getfileids/IdentifyPillarsForGetFileIDsIT.java b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/getfileids/IdentifyPillarsForGetFileIDsIT.java index 8d946361e..e501de725 100644 --- a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/getfileids/IdentifyPillarsForGetFileIDsIT.java +++ b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/getfileids/IdentifyPillarsForGetFileIDsIT.java @@ -5,16 +5,16 @@ * Copyright (C) 2010 - 2012 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% @@ -31,31 +31,35 @@ import org.bitrepository.pillar.PillarTestGroups; import org.bitrepository.pillar.integration.func.DefaultPillarIdentificationTest; import org.bitrepository.pillar.messagefactories.GetFileIDsMessageFactory; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertNotNull; public class IdentifyPillarsForGetFileIDsIT extends DefaultPillarIdentificationTest { protected GetFileIDsMessageFactory msgFactory; - @BeforeMethod(alwaysRun=true) + @BeforeEach public void initialiseReferenceTest() throws Exception { msgFactory = new GetFileIDsMessageFactory(collectionID, settingsForTestClient, getPillarID(), null); clearReceivers(); } - @Test( groups = {PillarTestGroups.FULL_PILLAR_TEST, PillarTestGroups.CHECKSUM_PILLAR_TEST}) + @Test + @Tag(PillarTestGroups.FULL_PILLAR_TEST) + @Tag(PillarTestGroups.CHECKSUM_PILLAR_TEST) public void normalIdentificationTest() { addDescription("Verifies the normal behaviour for getFileIDs identification"); addStep("Setup for test", "2 files on the pillar"); pillarFileManager.ensureNumberOfFilesOnPillar(2, testMethodName); clearReceivers(); - + addStep("Sending a identify request.", - "The pillar under test should make a response with the correct elements."); - FileIDs fileids = FileIDsUtils.createFileIDs(DEFAULT_FILE_ID); + "The pillar under test should make a response with the correct elements."); + FileIDs fileids = FileIDsUtils.createFileIDs(defaultFileId); addStep("Create and send the identify request message.", "Should be received and handled by the pillar."); @@ -77,19 +81,21 @@ public void normalIdentificationTest() { assertEquals(receivedIdentifyResponse.getPillarID(), getPillarID(), "Received unexpected 'PillarID' in response."); assertNotNull(receivedIdentifyResponse.getReplyTo()); - assertEquals(receivedIdentifyResponse.getResponseInfo().getResponseCode(), - ResponseCode.IDENTIFICATION_POSITIVE, + assertEquals(ResponseCode.IDENTIFICATION_POSITIVE, + receivedIdentifyResponse.getResponseInfo().getResponseCode(), "Received unexpected 'Response' in response."); } - @Test( groups = {PillarTestGroups.FULL_PILLAR_TEST, PillarTestGroups.CHECKSUM_PILLAR_TEST}) + @Test + @Tag(PillarTestGroups.FULL_PILLAR_TEST) + @Tag(PillarTestGroups.CHECKSUM_PILLAR_TEST) public void nonExistingFileTest() { addDescription("Tests that the pillar is able to reject a GetFileIDs requests for a file, which it " + - "does not have during the identification phase."); + "does not have during the identification phase."); addStep("Setup for test", "2 files on the pillar"); //pillarFileManager.ensureNumberOfFilesOnPillar(2, testMethodName); - FileIDs fileids = FileIDsUtils.createFileIDs(NON_DEFAULT_FILE_ID); + FileIDs fileids = FileIDsUtils.createFileIDs(nonDefaultFileId); addStep("Create and send the identify request message.", "Should be received and handled by the pillar."); @@ -102,12 +108,14 @@ public void nonExistingFileTest() { IdentifyPillarsForGetFileIDsResponse receivedIdentifyResponse = clientReceiver.waitForMessage( IdentifyPillarsForGetFileIDsResponse.class); assertNotNull(receivedIdentifyResponse.getFileIDs().getFileID()); - assertEquals(receivedIdentifyResponse.getResponseInfo().getResponseCode(), - ResponseCode.FILE_NOT_FOUND_FAILURE, + assertEquals(ResponseCode.FILE_NOT_FOUND_FAILURE, + receivedIdentifyResponse.getResponseInfo().getResponseCode(), "Received unexpected 'ResponseCode' in response."); } - - @Test( groups = {PillarTestGroups.FULL_PILLAR_TEST, PillarTestGroups.CHECKSUM_PILLAR_TEST}) + + @Test + @Tag(PillarTestGroups.FULL_PILLAR_TEST) + @Tag(PillarTestGroups.CHECKSUM_PILLAR_TEST) public void allFilesTest() { addDescription("Tests that the pillar accepts a GetFileIDs requests for all files, even though it does not have any files."); FileIDs fileids = FileIDsUtils.getAllFileIDs(); @@ -122,8 +130,8 @@ public void allFilesTest() { "The pillar should make a response."); IdentifyPillarsForGetFileIDsResponse receivedIdentifyResponse = clientReceiver.waitForMessage( IdentifyPillarsForGetFileIDsResponse.class); - assertEquals(receivedIdentifyResponse.getResponseInfo().getResponseCode(), - ResponseCode.IDENTIFICATION_POSITIVE, + assertEquals(ResponseCode.IDENTIFICATION_POSITIVE, + receivedIdentifyResponse.getResponseInfo().getResponseCode(), "Received unexpected 'ResponseCode' in response."); } diff --git a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/getstatus/GetStatusRequestIT.java b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/getstatus/GetStatusRequestIT.java index 3b786cb70..2f8319b74 100644 --- a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/getstatus/GetStatusRequestIT.java +++ b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/getstatus/GetStatusRequestIT.java @@ -32,24 +32,24 @@ import org.bitrepository.pillar.integration.func.PillarFunctionTest; import org.bitrepository.pillar.messagefactories.GetStatusMessageFactory; import org.bitrepository.settings.referencesettings.AlarmLevel; -import org.testng.Assert; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; - -import java.lang.reflect.Method; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; public class GetStatusRequestIT extends PillarFunctionTest { protected GetStatusMessageFactory msgFactory; private String pillarDestination; - @BeforeMethod(alwaysRun=true) - public void initialiseReferenceTest(Method method) throws Exception { + @BeforeEach + public void initialiseReferenceTest() throws Exception { msgFactory = new GetStatusMessageFactory(null, settingsForTestClient, getPillarID(), null); pillarDestination = lookupPillarDestination(); msgFactory = new GetStatusMessageFactory(null, settingsForTestClient, getPillarID(), pillarDestination); } - @Test( groups = {PillarTestGroups.FULL_PILLAR_TEST, PillarTestGroups.CHECKSUM_PILLAR_TEST}) + @Test + @Tag(PillarTestGroups.FULL_PILLAR_TEST) @Tag(PillarTestGroups.CHECKSUM_PILLAR_TEST) public void normalGetStatusTest() { addDescription("Tests the GetStatus functionality of a pillar for the successful scenario."); @@ -60,13 +60,14 @@ public void normalGetStatusTest() { addStep("Receive and validate the final response", "Should be sent by the pillar."); GetStatusFinalResponse finalResponse = clientReceiver.waitForMessage(GetStatusFinalResponse.class); - Assert.assertNotNull(finalResponse); - Assert.assertEquals(finalResponse.getResponseInfo().getResponseCode(), ResponseCode.OPERATION_COMPLETED); - Assert.assertEquals(finalResponse.getCorrelationID(), request.getCorrelationID()); - Assert.assertEquals(finalResponse.getFrom(), getPillarID()); + Assertions.assertNotNull(finalResponse); + Assertions.assertEquals(ResponseCode.OPERATION_COMPLETED, finalResponse.getResponseInfo().getResponseCode()); + Assertions.assertEquals(finalResponse.getCorrelationID(), request.getCorrelationID()); + Assertions.assertEquals(finalResponse.getFrom(), getPillarID()); } - @Test( groups = {"failing"}) + @Test + @Tag("failing") public void checksumPillarGetStatusWrongContributor() { addDescription("Tests the GetStatus functionality of the reference pillar for the bad scenario, where a wrong " + "contributor id is given."); @@ -80,7 +81,7 @@ public void checksumPillarGetStatusWrongContributor() { messageBus.sendMessage(request); addStep("The pillar should send an alarm.", ""); - Assert.assertNotNull(alarmReceiver.waitForMessage(AlarmMessage.class)); + Assertions.assertNotNull(alarmReceiver.waitForMessage(AlarmMessage.class)); } diff --git a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/getstatus/IdentifyContributorsForGetStatusIT.java b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/getstatus/IdentifyContributorsForGetStatusIT.java index 15ede00e3..1a224a0ca 100644 --- a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/getstatus/IdentifyContributorsForGetStatusIT.java +++ b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/getstatus/IdentifyContributorsForGetStatusIT.java @@ -28,22 +28,24 @@ import org.bitrepository.pillar.PillarTestGroups; import org.bitrepository.pillar.integration.func.PillarFunctionTest; import org.bitrepository.pillar.messagefactories.GetStatusMessageFactory; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; -import java.lang.reflect.Method; +import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.testng.Assert.assertEquals; public class IdentifyContributorsForGetStatusIT extends PillarFunctionTest { protected GetStatusMessageFactory msgFactory; - @BeforeMethod(alwaysRun=true) - public void initialiseReferenceTest(Method method) throws Exception { + @BeforeEach + public void initialiseReferenceTest() throws Exception { msgFactory = new GetStatusMessageFactory(collectionID, settingsForTestClient, getPillarID(), null); } - @Test( groups = {PillarTestGroups.FULL_PILLAR_TEST, PillarTestGroups.CHECKSUM_PILLAR_TEST}) + @Test + @Tag(PillarTestGroups.FULL_PILLAR_TEST) + @Tag(PillarTestGroups.CHECKSUM_PILLAR_TEST) public void normalGetStatusTest() { addDescription("Tests the GetStatus functionality of a pillar for the successful scenario."); @@ -61,8 +63,8 @@ public void normalGetStatusTest() { "Received unexpected 'CorrelationID' in response."); assertEquals(receivedIdentifyResponse.getFrom(), getPillarID(), "Received unexpected 'PillarID' in response."); - assertEquals(receivedIdentifyResponse.getResponseInfo().getResponseCode(), - ResponseCode.IDENTIFICATION_POSITIVE, + assertEquals(ResponseCode.IDENTIFICATION_POSITIVE, + receivedIdentifyResponse.getResponseInfo().getResponseCode(), "Received unexpected 'ResponseCode' in response."); assertEquals(receivedIdentifyResponse.getDestination(), identifyRequest.getReplyTo(), "Received unexpected 'To' in response."); diff --git a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/multicollection/MultipleCollectionIT.java b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/multicollection/MultipleCollectionIT.java index 46c8c6f8d..cd993a253 100644 --- a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/multicollection/MultipleCollectionIT.java +++ b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/multicollection/MultipleCollectionIT.java @@ -5,16 +5,16 @@ * Copyright (C) 2010 - 2012 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% @@ -26,38 +26,43 @@ import org.bitrepository.common.utils.TestFileHelper; import org.bitrepository.pillar.PillarTestGroups; import org.bitrepository.pillar.integration.PillarIntegrationTest; -import org.bitrepository.pillar.integration.func.Assert; import org.bitrepository.protocol.bus.MessageReceiver; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; -import java.util.Arrays; import java.util.Collection; +import java.util.Collections; public class MultipleCollectionIT extends PillarIntegrationTest { - /** Used for receiving responses from the pillar */ + /** + * Used for receiving responses from the pillar + */ protected MessageReceiver clientReceiver; - @Test( groups = {PillarTestGroups.FULL_PILLAR_TEST, PillarTestGroups.CHECKSUM_PILLAR_TEST}) + @Test + @Tag(PillarTestGroups.FULL_PILLAR_TEST) + @Tag(PillarTestGroups.CHECKSUM_PILLAR_TEST) public void fileInOtherCollectionTest() throws Exception { addDescription("Tests that a file is put correctly to a second collection, and that the file can be access " + "with getFile, getChecksums, getFileIDs and can be replaced and deleted correctly."); addStep("Put the file to the second collection", "Should complete successfully"); clientProvider.getPutClient().putFile( - nonDefaultCollectionId, DEFAULT_FILE_URL, NON_DEFAULT_FILE_ID, 10L, TestFileHelper.getDefaultFileChecksum(), + nonDefaultCollectionId, defaultFileUrl, nonDefaultFileId, 10L, TestFileHelper.getDefaultFileChecksum(), null, null, null); addStep("Send a getFileIDs for the file in the second collection", "The fileID should be retrieved"); ContributorQuery query = new ContributorQuery(getPillarID(), null, null, null); - Assert.assertEquals(1, clientProvider.getGetFileIDsClient().getGetFileIDs( - nonDefaultCollectionId, new ContributorQuery[] {query}, NON_DEFAULT_FILE_ID, DEFAULT_FILE_URL, null).size()); + Assertions.assertEquals(1, clientProvider.getGetFileIDsClient().getGetFileIDs( + nonDefaultCollectionId, new ContributorQuery[]{query}, nonDefaultFileId, defaultFileUrl, null).size()); addStep("Send a getFileIDs for the file in the other collections", "The file should not be found here"); try { clientProvider.getGetFileIDsClient().getGetFileIDs( - collectionID, new ContributorQuery[] {query}, NON_DEFAULT_FILE_ID, DEFAULT_FILE_URL, null).size(); - Assert.fail("Should have throw a NegativeResponseException as the file doesn't exist in the default " + + collectionID, new ContributorQuery[]{query}, nonDefaultFileId, defaultFileUrl, null).size(); + Assertions.fail("Should have throw a NegativeResponseException as the file doesn't exist in the default " + "collection"); - } catch (NegativeResponseException nre){ + } catch (NegativeResponseException nre) { //Expected } } @@ -69,7 +74,7 @@ protected void registerMessageReceivers() { clientReceiver = new MessageReceiver(settingsForTestClient.getReceiverDestinationID(), testEventManager); addReceiver(clientReceiver); - Collection pillarFilter = Arrays.asList(testConfiguration.getPillarUnderTestID()); + Collection pillarFilter = Collections.singletonList(testConfiguration.getPillarUnderTestID()); clientReceiver.setFromFilter(pillarFilter); alarmReceiver.setFromFilter(pillarFilter); } diff --git a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/putfile/IdentifyPillarsForPutFileIT.java b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/putfile/IdentifyPillarsForPutFileIT.java index ebcfce9fe..736d0d20e 100644 --- a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/putfile/IdentifyPillarsForPutFileIT.java +++ b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/putfile/IdentifyPillarsForPutFileIT.java @@ -5,16 +5,16 @@ * Copyright (C) 2010 - 2012 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% @@ -30,37 +30,39 @@ import org.bitrepository.pillar.PillarTestGroups; import org.bitrepository.pillar.integration.func.DefaultPillarIdentificationTest; import org.bitrepository.pillar.messagefactories.PutFileMessageFactory; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; -import static org.bitrepository.pillar.integration.func.Assert.assertEquals; -import static org.bitrepository.pillar.integration.func.Assert.assertNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; public class IdentifyPillarsForPutFileIT extends DefaultPillarIdentificationTest { protected PutFileMessageFactory msgFactory; - @BeforeMethod(alwaysRun=true) + @BeforeEach public void initialiseReferenceTest() throws Exception { msgFactory = new PutFileMessageFactory(collectionID, settingsForTestClient, getPillarID(), null); } - @Test( groups = {PillarTestGroups.FULL_PILLAR_TEST}) + @Test + @Tag(PillarTestGroups.FULL_PILLAR_TEST) public void normalIdentificationTest() { addDescription("Verifies the normal behaviour for putFile identification"); addStep("Sending a putFile identification request.", - "The pillar under test should make a response with the following elements:
      " + - "
    1. 'CollectionID' element corresponding to the supplied value
    2. " + - "
    3. 'CorrelationID' element corresponding to the supplied value
    4. " + - "
    5. 'From' element corresponding to the pillars component ID
    6. " + - "
    7. 'To' element should be set to the value of the 'From' elements in the request
    8. " + - "
    9. 'Destination' element should be set to the value of 'ReplyTo' from the request
    10. " + - "
    11. 'ChecksumDataForExistingFile' element should be null
    12. " + - "
    13. 'PillarChecksumSpec' element should be null
    14. " + - "
    15. 'PillarID' element corresponding to the pillars component ID
    16. " + - "
    17. 'ResponseInfo.ResponseCode' element should be IDENTIFICATION_POSITIVE
    18. " + - "
    "); + "The pillar under test should make a response with the following elements:
      " + + "
    1. 'CollectionID' element corresponding to the supplied value
    2. " + + "
    3. 'CorrelationID' element corresponding to the supplied value
    4. " + + "
    5. 'From' element corresponding to the pillars component ID
    6. " + + "
    7. 'To' element should be set to the value of the 'From' elements in the request
    8. " + + "
    9. 'Destination' element should be set to the value of 'ReplyTo' from the request
    10. " + + "
    11. 'ChecksumDataForExistingFile' element should be null
    12. " + + "
    13. 'PillarChecksumSpec' element should be null
    14. " + + "
    15. 'PillarID' element corresponding to the pillars component ID
    16. " + + "
    17. 'ResponseInfo.ResponseCode' element should be IDENTIFICATION_POSITIVE
    18. " + + "
    "); IdentifyPillarsForPutFileRequest identifyRequest = msgFactory.createIdentifyPillarsForPutFileRequest( - NON_DEFAULT_FILE_ID, 0L); + nonDefaultFileId, 0L); messageBus.sendMessage(identifyRequest); IdentifyPillarsForPutFileResponse receivedIdentifyResponse = clientReceiver.waitForMessage( @@ -79,21 +81,22 @@ public void normalIdentificationTest() { "Received unexpected PillarChecksumSpec"); assertEquals(receivedIdentifyResponse.getPillarID(), getPillarID(), "Unexpected 'From' element in the received response:\n" + receivedIdentifyResponse + "\n"); - assertEquals(receivedIdentifyResponse.getResponseInfo().getResponseCode(), - ResponseCode.IDENTIFICATION_POSITIVE, + assertEquals(ResponseCode.IDENTIFICATION_POSITIVE, + receivedIdentifyResponse.getResponseInfo().getResponseCode(), "Received unexpected ResponseCode"); assertEquals(receivedIdentifyResponse.getDestination(), identifyRequest.getReplyTo(), "Received unexpected ReplyTo"); } - @Test( groups = {PillarTestGroups.CHECKSUM_PILLAR_TEST}) + @Test + @Tag(PillarTestGroups.CHECKSUM_PILLAR_TEST) public void identificationTestForChecksumPillar() { addDescription("Verifies the normal behaviour for putFile identification for a checksum pillar"); addStep("Sending a putFile identification.", "The pillar under test should make a response with the correct elements. The only different from a " + - "full pillar is that the checksum pillar will respond with the default checksum spec."); + "full pillar is that the checksum pillar will respond with the default checksum spec."); IdentifyPillarsForPutFileRequest identifyRequest = msgFactory.createIdentifyPillarsForPutFileRequest( - NON_DEFAULT_FILE_ID, 0L); + nonDefaultFileId, 0L); messageBus.sendMessage(identifyRequest); IdentifyPillarsForPutFileResponse receivedIdentifyResponse = clientReceiver.waitForMessage( @@ -105,34 +108,36 @@ public void identificationTestForChecksumPillar() { assertEquals(receivedIdentifyResponse.getPillarChecksumSpec().getChecksumType(), ChecksumUtils.getDefault(settingsForCUT).getChecksumType()); assertEquals(receivedIdentifyResponse.getPillarID(), getPillarID()); - assertEquals(receivedIdentifyResponse.getResponseInfo().getResponseCode(), - ResponseCode.IDENTIFICATION_POSITIVE); + assertEquals(ResponseCode.IDENTIFICATION_POSITIVE, + receivedIdentifyResponse.getResponseInfo().getResponseCode()); assertEquals(receivedIdentifyResponse.getDestination(), identifyRequest.getReplyTo()); } - @Test( groups = {PillarTestGroups.FULL_PILLAR_TEST, PillarTestGroups.CHECKSUM_PILLAR_TEST}) + @Test + @Tag(PillarTestGroups.FULL_PILLAR_TEST) + @Tag(PillarTestGroups.CHECKSUM_PILLAR_TEST) public void fileExistsTest() { addDescription("Verifies the exists of a file with the same ID is handled correctly. " + "This means that a checksum for the existing file is returned, enabling the client to continue with " + "the put operation for the pillars not yet containing the file. The client can easily " + - "implement idempotent behaviour based on this response." ); + "implement idempotent behaviour based on this response."); addStep("Sending a putFile identification for a file already in the pillar.", "The pillar under test should send a DUPLICATE_FILE_FAILURE response with the (default type) checksum " + "of the existing file."); IdentifyPillarsForPutFileRequest identifyRequest = msgFactory.createIdentifyPillarsForPutFileRequest( - DEFAULT_FILE_ID, 0L); + defaultFileId, 0L); messageBus.sendMessage(identifyRequest); IdentifyPillarsForPutFileResponse receivedIdentifyResponse = clientReceiver.waitForMessage( IdentifyPillarsForPutFileResponse.class); - assertEquals(receivedIdentifyResponse.getResponseInfo().getResponseCode(), - ResponseCode.DUPLICATE_FILE_FAILURE); + assertEquals(ResponseCode.DUPLICATE_FILE_FAILURE, + receivedIdentifyResponse.getResponseInfo().getResponseCode()); } @Override protected MessageRequest createRequest() { return msgFactory.createIdentifyPillarsForPutFileRequest( - NON_DEFAULT_FILE_ID, 0L); + nonDefaultFileId, 0L); } @Override diff --git a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/putfile/PutFileRequestIT.java b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/putfile/PutFileRequestIT.java index eff5fbac7..87e9a8731 100644 --- a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/putfile/PutFileRequestIT.java +++ b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/putfile/PutFileRequestIT.java @@ -5,16 +5,16 @@ * Copyright (C) 2010 - 2012 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% @@ -34,31 +34,33 @@ import org.bitrepository.pillar.PillarTestGroups; import org.bitrepository.pillar.integration.func.DefaultPillarOperationTest; import org.bitrepository.pillar.messagefactories.PutFileMessageFactory; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; -import java.lang.reflect.Method; import java.util.concurrent.TimeUnit; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertNotNull; -import static org.testng.Assert.assertNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; public class PutFileRequestIT extends DefaultPillarOperationTest { protected PutFileMessageFactory msgFactory; private String pillarDestination; - @BeforeMethod(alwaysRun=true) - public void initialiseReferenceTest(Method method) throws Exception { + @BeforeEach + public void initialiseReferenceTest() throws Exception { pillarDestination = lookupPutFileDestination(); msgFactory = new PutFileMessageFactory(collectionID, settingsForTestClient, getPillarID(), pillarDestination); } - @Test( groups = {PillarTestGroups.FULL_PILLAR_TEST, PillarTestGroups.CHECKSUM_PILLAR_TEST}) + @Test + @Tag(PillarTestGroups.FULL_PILLAR_TEST) + @Tag(PillarTestGroups.CHECKSUM_PILLAR_TEST) public void normalPutFileTest() { addDescription("Tests a normal PutFile sequence"); addStep("Send a putFile request to " + testConfiguration.getPillarUnderTestID(), - "The pillar should send a final response with the following elements:
      " + + "The pillar should send a final response with the following elements:
        " + "
      1. 'CollectionID' element corresponding to the supplied value
      2. " + "
      3. 'CorrelationID' element corresponding to the supplied value
      4. " + "
      5. 'From' element corresponding to the pillars component ID
      6. " + @@ -68,11 +70,11 @@ public void normalPutFileTest() { "
      7. 'ChecksumDataForNewFile' element should be null
      8. " + "
      9. 'PillarID' element corresponding to the pillars component ID
      10. " + "
      11. 'FileID' element corresponding to the supplied fileID
      12. " + - "
      13. 'FileAddress' element corresponding to the supplied FileAddress
      14. " + + "
      15. 'FileAddress' element corresponding to the supplied FileAddress
      16. " + "
      17. 'ResponseInfo.ResponseCode' element should be OPERATION_COMPLETED
      18. " + "
      "); PutFileRequest putRequest = msgFactory.createPutFileRequest( - TestFileHelper.getDefaultFileChecksum(), null, DEFAULT_DOWNLOAD_FILE_ADDRESS, testSpecificFileID, + TestFileHelper.getDefaultFileChecksum(), null, defaultDownloadFileAddress, testSpecificFileID, DEFAULT_FILE_SIZE); messageBus.sendMessage(putRequest); @@ -98,18 +100,19 @@ public void normalPutFileTest() { "Received unexpected 'FileAddress' element."); assertEquals(finalResponse.getPillarID(), getPillarID(), "Received unexpected 'PillarID' element."); - assertEquals(finalResponse.getResponseInfo().getResponseCode(), ResponseCode.OPERATION_COMPLETED, + assertEquals(ResponseCode.OPERATION_COMPLETED, finalResponse.getResponseInfo().getResponseCode(), "Received unexpected 'ResponseCode' element."); } - @Test( groups = {PillarTestGroups.FULL_PILLAR_TEST}) + @Test + @Tag(PillarTestGroups.FULL_PILLAR_TEST) public void putFileWithMD5ReturnChecksumTest() { addDescription("Tests that the pillar is able to return the default type checksum in the final response"); addStep("Send a putFile request to " + testConfiguration.getPillarUnderTestID() + " with the ", "The pillar should send a final response with the ChecksumRequestForNewFile elements containing the MD5 " + "checksum for the supplied file."); PutFileRequest putRequest = msgFactory.createPutFileRequest( - TestFileHelper.getDefaultFileChecksum(), null, DEFAULT_DOWNLOAD_FILE_ADDRESS, testSpecificFileID, + TestFileHelper.getDefaultFileChecksum(), null, defaultDownloadFileAddress, testSpecificFileID, DEFAULT_FILE_SIZE); putRequest.setChecksumRequestForNewFile(ChecksumUtils.getDefault(settingsForTestClient)); messageBus.sendMessage(putRequest); @@ -120,8 +123,10 @@ public void putFileWithMD5ReturnChecksumTest() { "Return MD5 checksum was not equals to checksum for default file."); } - @Test( groups = {PillarTestGroups.FULL_PILLAR_TEST, PillarTestGroups.CHECKSUM_PILLAR_TEST, - PillarTestGroups.OPERATION_ACCEPTED_PROGRESS}) + @Test + @Tag(PillarTestGroups.FULL_PILLAR_TEST) + @Tag(PillarTestGroups.CHECKSUM_PILLAR_TEST) + @Tag(PillarTestGroups.OPERATION_ACCEPTED_PROGRESS) public void putFileOperationAcceptedProgressTest() { addDescription("Tests a that a pillar sends progress response after receiving a putFile request."); @@ -134,13 +139,13 @@ public void putFileOperationAcceptedProgressTest() { "
    1. 'Destination' element should be set to the value of 'ReplyTo' from the request
    2. " + "
    3. 'PillarID' element corresponding to the pillars component ID
    4. " + "
    5. 'FileID' element corresponding to the supplied fileID
    6. " + - "
    7. 'FileAddress' element corresponding to the supplied FileAddress
    8. " + + "
    9. 'FileAddress' element corresponding to the supplied FileAddress
    10. " + "
    11. 'ResponseInfo.ResponseCode' element should be OPERATION_ACCEPTED_PROGRESS
    12. " + "
    "); - PutFileRequest putRequest = (PutFileRequest)createRequest(); + PutFileRequest putRequest = (PutFileRequest) createRequest(); messageBus.sendMessage(putRequest); - PutFileProgressResponse progressResponse = clientReceiver.waitForMessage(PutFileProgressResponse.class, + PutFileProgressResponse progressResponse = clientReceiver.waitForMessage(PutFileProgressResponse.class, getOperationTimeout(), TimeUnit.SECONDS); assertNotNull(progressResponse); assertEquals(progressResponse.getCorrelationID(), putRequest.getCorrelationID(), @@ -159,15 +164,15 @@ public void putFileOperationAcceptedProgressTest() { "Received unexpected 'FileID' element."); assertEquals(progressResponse.getFileAddress(), putRequest.getFileAddress(), "Received unexpected 'FileAddress' element."); - assertEquals(progressResponse.getResponseInfo().getResponseCode(), - ResponseCode.OPERATION_ACCEPTED_PROGRESS, + assertEquals(ResponseCode.OPERATION_ACCEPTED_PROGRESS, + progressResponse.getResponseInfo().getResponseCode(), "Received unexpected 'ResponseCode' element."); } @Override protected MessageRequest createRequest() { return msgFactory.createPutFileRequest(TestFileHelper.getDefaultFileChecksum(), null, - DEFAULT_DOWNLOAD_FILE_ADDRESS, NON_DEFAULT_FILE_ID, DEFAULT_FILE_SIZE); + defaultDownloadFileAddress, nonDefaultFileId, DEFAULT_FILE_SIZE); } @Override diff --git a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/replacefile/IdentifyPillarsForReplaceFileIT.java b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/replacefile/IdentifyPillarsForReplaceFileIT.java index efab1dc2d..238808f3a 100644 --- a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/replacefile/IdentifyPillarsForReplaceFileIT.java +++ b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/replacefile/IdentifyPillarsForReplaceFileIT.java @@ -5,16 +5,16 @@ * Copyright (C) 2010 - 2012 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% @@ -28,85 +28,91 @@ import org.bitrepository.bitrepositorymessages.MessageResponse; import org.bitrepository.common.utils.ChecksumUtils; import org.bitrepository.pillar.PillarTestGroups; -import org.bitrepository.pillar.integration.func.Assert; import org.bitrepository.pillar.integration.func.DefaultPillarIdentificationTest; import org.bitrepository.pillar.messagefactories.ReplaceFileMessageFactory; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + public class IdentifyPillarsForReplaceFileIT extends DefaultPillarIdentificationTest { protected ReplaceFileMessageFactory msgFactory; - @BeforeMethod(alwaysRun=true) + @BeforeEach public void initialiseReferenceTest() throws Exception { msgFactory = new ReplaceFileMessageFactory(collectionID, settingsForTestClient, getPillarID(), null); } - @Test( groups = {PillarTestGroups.FULL_PILLAR_TEST}) + @Test + @Tag(PillarTestGroups.FULL_PILLAR_TEST) public void normalIdentificationTest() { addDescription("Verifies the normal behaviour for replaceFile identification"); addStep("Sending a replaceFile identification.", - "The pillar under test should make a response with the correct elements."); + "The pillar under test should make a response with the correct elements."); IdentifyPillarsForReplaceFileRequest identifyRequest = msgFactory.createIdentifyPillarsForReplaceFileRequest( - DEFAULT_FILE_ID, DEFAULT_FILE_SIZE); + defaultFileId, DEFAULT_FILE_SIZE); messageBus.sendMessage(identifyRequest); IdentifyPillarsForReplaceFileResponse receivedIdentifyResponse = clientReceiver.waitForMessage( IdentifyPillarsForReplaceFileResponse.class); - Assert.assertEquals(receivedIdentifyResponse.getCollectionID(), identifyRequest.getCollectionID()); - Assert.assertEquals(receivedIdentifyResponse.getCorrelationID(), identifyRequest.getCorrelationID()); - Assert.assertEquals(receivedIdentifyResponse.getFrom(), getPillarID()); - Assert.assertEquals(receivedIdentifyResponse.getFileID(), DEFAULT_FILE_ID); - Assert.assertEquals(receivedIdentifyResponse.getPillarID(), getPillarID()); - Assert.assertNull(receivedIdentifyResponse.getPillarChecksumSpec()); - Assert.assertEquals(receivedIdentifyResponse.getResponseInfo().getResponseCode(), - ResponseCode.IDENTIFICATION_POSITIVE); - Assert.assertEquals(receivedIdentifyResponse.getDestination(), identifyRequest.getReplyTo()); + Assertions.assertEquals(receivedIdentifyResponse.getCollectionID(), identifyRequest.getCollectionID()); + Assertions.assertEquals(receivedIdentifyResponse.getCorrelationID(), identifyRequest.getCorrelationID()); + Assertions.assertEquals(receivedIdentifyResponse.getFrom(), getPillarID()); + Assertions.assertEquals(receivedIdentifyResponse.getFileID(), defaultFileId); + Assertions.assertEquals(receivedIdentifyResponse.getPillarID(), getPillarID()); + Assertions.assertNull(receivedIdentifyResponse.getPillarChecksumSpec()); + Assertions.assertEquals(ResponseCode.IDENTIFICATION_POSITIVE, + receivedIdentifyResponse.getResponseInfo().getResponseCode()); + Assertions.assertEquals(receivedIdentifyResponse.getDestination(), identifyRequest.getReplyTo()); } - @Test( groups = {PillarTestGroups.CHECKSUM_PILLAR_TEST}) + @Test + @Tag(PillarTestGroups.CHECKSUM_PILLAR_TEST) public void identificationTestForChecksumPillar() { addDescription("Verifies the normal behaviour for replaceFile identification for a checksum pillar"); addStep("Sending a replaceFile identification.", "The pillar under test should make a response with the correct elements. The only different from a " + - "full pillar is that the checksum pillar will respond with the default checksum spec."); + "full pillar is that the checksum pillar will respond with the default checksum spec."); IdentifyPillarsForReplaceFileRequest identifyRequest = msgFactory.createIdentifyPillarsForReplaceFileRequest( - DEFAULT_FILE_ID, DEFAULT_FILE_SIZE); + defaultFileId, DEFAULT_FILE_SIZE); messageBus.sendMessage(identifyRequest); IdentifyPillarsForReplaceFileResponse receivedIdentifyResponse = clientReceiver.waitForMessage( IdentifyPillarsForReplaceFileResponse.class); - Assert.assertEquals(receivedIdentifyResponse.getCollectionID(), identifyRequest.getCollectionID()); - Assert.assertEquals(receivedIdentifyResponse.getCorrelationID(), identifyRequest.getCorrelationID()); - Assert.assertEquals(receivedIdentifyResponse.getFrom(), getPillarID()); - Assert.assertEquals(receivedIdentifyResponse.getPillarChecksumSpec().getChecksumType(), + Assertions.assertEquals(receivedIdentifyResponse.getCollectionID(), identifyRequest.getCollectionID()); + Assertions.assertEquals(receivedIdentifyResponse.getCorrelationID(), identifyRequest.getCorrelationID()); + Assertions.assertEquals(receivedIdentifyResponse.getFrom(), getPillarID()); + Assertions.assertEquals(receivedIdentifyResponse.getPillarChecksumSpec().getChecksumType(), ChecksumUtils.getDefault(settingsForCUT).getChecksumType()); - Assert.assertEquals(receivedIdentifyResponse.getPillarID(), getPillarID()); - Assert.assertEquals(receivedIdentifyResponse.getResponseInfo().getResponseCode(), - ResponseCode.IDENTIFICATION_POSITIVE); - Assert.assertEquals(receivedIdentifyResponse.getDestination(), identifyRequest.getReplyTo()); + Assertions.assertEquals(receivedIdentifyResponse.getPillarID(), getPillarID()); + Assertions.assertEquals(ResponseCode.IDENTIFICATION_POSITIVE, + receivedIdentifyResponse.getResponseInfo().getResponseCode()); + Assertions.assertEquals(receivedIdentifyResponse.getDestination(), identifyRequest.getReplyTo()); } - @Test( groups = {PillarTestGroups.FULL_PILLAR_TEST, PillarTestGroups.CHECKSUM_PILLAR_TEST}) + @Test + @Tag(PillarTestGroups.FULL_PILLAR_TEST) + @Tag(PillarTestGroups.CHECKSUM_PILLAR_TEST) public void fileDoesNotExistsTest() { addDescription("Verifies that a request for a non-existing file is handled correctly"); addStep("Sending a replaceFile identification for a file not in the pillar.", "The pillar under test should send a FILE_NOT_FOUND_FAILURE response."); IdentifyPillarsForReplaceFileRequest identifyRequest = msgFactory.createIdentifyPillarsForReplaceFileRequest( - NON_DEFAULT_FILE_ID, 0L); + nonDefaultFileId, 0L); messageBus.sendMessage(identifyRequest); IdentifyPillarsForReplaceFileResponse receivedIdentifyResponse = clientReceiver.waitForMessage( IdentifyPillarsForReplaceFileResponse.class); - Assert.assertEquals(receivedIdentifyResponse.getResponseInfo().getResponseCode(), - ResponseCode.FILE_NOT_FOUND_FAILURE); + Assertions.assertEquals(ResponseCode.FILE_NOT_FOUND_FAILURE, + receivedIdentifyResponse.getResponseInfo().getResponseCode()); } @Override protected MessageRequest createRequest() { return msgFactory.createIdentifyPillarsForReplaceFileRequest( - DEFAULT_FILE_ID, DEFAULT_FILE_SIZE); + defaultFileId, DEFAULT_FILE_SIZE); } @Override diff --git a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/replacefile/ReplaceFileRequestIT.java b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/replacefile/ReplaceFileRequestIT.java index b11857b8c..306b1a19b 100644 --- a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/replacefile/ReplaceFileRequestIT.java +++ b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/replacefile/ReplaceFileRequestIT.java @@ -5,16 +5,16 @@ * Copyright (C) 2010 - 2012 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% @@ -33,64 +33,66 @@ import org.bitrepository.pillar.PillarTestGroups; import org.bitrepository.pillar.integration.func.DefaultPillarOperationTest; import org.bitrepository.pillar.messagefactories.ReplaceFileMessageFactory; -import org.testng.Assert; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; -import java.lang.reflect.Method; import java.util.concurrent.TimeUnit; public class ReplaceFileRequestIT extends DefaultPillarOperationTest { protected ReplaceFileMessageFactory msgFactory; private String pillarDestination; - @BeforeMethod(alwaysRun=true) - public void initialiseReferenceTest(Method method) throws Exception { + @BeforeEach + public void initialiseReferenceTest() throws Exception { pillarDestination = lookupReplaceFileDestination(); msgFactory = new ReplaceFileMessageFactory(collectionID, settingsForTestClient, getPillarID(), pillarDestination); clientProvider.getPutClient().putFile( - collectionID, DEFAULT_FILE_URL, testSpecificFileID, 10L, TestFileHelper.getDefaultFileChecksum(), + collectionID, defaultFileUrl, testSpecificFileID, 10L, TestFileHelper.getDefaultFileChecksum(), null, null, null); clientProvider.getPutClient().putFile( - nonDefaultCollectionId, DEFAULT_FILE_URL, testSpecificFileID, 10L, TestFileHelper.getDefaultFileChecksum(), + nonDefaultCollectionId, defaultFileUrl, testSpecificFileID, 10L, TestFileHelper.getDefaultFileChecksum(), null, null, null); } - @Test( groups = {PillarTestGroups.FULL_PILLAR_TEST, PillarTestGroups.CHECKSUM_PILLAR_TEST}) + @Test + @Tag(PillarTestGroups.FULL_PILLAR_TEST) + @Tag(PillarTestGroups.CHECKSUM_PILLAR_TEST) public void normalReplaceFileTest() { addDescription("Tests a normal ReplaceFile sequence"); addStep("Send a ReplaceFile request to " + testConfiguration.getPillarUnderTestID(), "The pillar should generate a OPERATION_ACCEPTED_PROGRESS progress response followed by a " + - "OPERATION_COMPLETED final response"); + "OPERATION_COMPLETED final response"); ReplaceFileRequest replaceRequest = msgFactory.createReplaceFileRequest( TestFileHelper.getDefaultFileChecksum(), TestFileHelper.getDefaultFileChecksum(), - null, null, DEFAULT_DOWNLOAD_FILE_ADDRESS, testSpecificFileID, DEFAULT_FILE_SIZE); + null, null, defaultDownloadFileAddress, testSpecificFileID, DEFAULT_FILE_SIZE); messageBus.sendMessage(replaceRequest); - ReplaceFileProgressResponse progressResponse = clientReceiver.waitForMessage(ReplaceFileProgressResponse.class, + ReplaceFileProgressResponse progressResponse = clientReceiver.waitForMessage(ReplaceFileProgressResponse.class, getOperationTimeout(), TimeUnit.SECONDS); - Assert.assertNotNull(progressResponse); - Assert.assertEquals(progressResponse.getCorrelationID(), replaceRequest.getCorrelationID()); - Assert.assertEquals(progressResponse.getFrom(), getPillarID()); - Assert.assertEquals(progressResponse.getPillarID(), getPillarID()); - Assert.assertEquals(progressResponse.getResponseInfo().getResponseCode(), - ResponseCode.OPERATION_ACCEPTED_PROGRESS); + Assertions.assertNotNull(progressResponse); + Assertions.assertEquals(progressResponse.getCorrelationID(), replaceRequest.getCorrelationID()); + Assertions.assertEquals(progressResponse.getFrom(), getPillarID()); + Assertions.assertEquals(progressResponse.getPillarID(), getPillarID()); + Assertions.assertEquals(ResponseCode.OPERATION_ACCEPTED_PROGRESS, + progressResponse.getResponseInfo().getResponseCode()); ReplaceFileFinalResponse finalResponse = (ReplaceFileFinalResponse) receiveResponse(); - Assert.assertNotNull(finalResponse); - Assert.assertEquals(finalResponse.getResponseInfo().getResponseCode(), ResponseCode.OPERATION_COMPLETED); - Assert.assertEquals(finalResponse.getCorrelationID(), replaceRequest.getCorrelationID()); - Assert.assertEquals(finalResponse.getFrom(), getPillarID()); - Assert.assertNull(finalResponse.getChecksumDataForExistingFile()); - Assert.assertNull(finalResponse.getChecksumDataForNewFile()); - Assert.assertEquals(finalResponse.getPillarID(), getPillarID()); + Assertions.assertNotNull(finalResponse); + Assertions.assertEquals(ResponseCode.OPERATION_COMPLETED, finalResponse.getResponseInfo().getResponseCode()); + Assertions.assertEquals(finalResponse.getCorrelationID(), replaceRequest.getCorrelationID()); + Assertions.assertEquals(finalResponse.getFrom(), getPillarID()); + Assertions.assertNull(finalResponse.getChecksumDataForExistingFile()); + Assertions.assertNull(finalResponse.getChecksumDataForNewFile()); + Assertions.assertEquals(finalResponse.getPillarID(), getPillarID()); } @Override protected MessageRequest createRequest() { return msgFactory.createReplaceFileRequest(TestFileHelper.getDefaultFileChecksum(), TestFileHelper.getDefaultFileChecksum(), null, null, - DEFAULT_DOWNLOAD_FILE_ADDRESS, DEFAULT_FILE_ID, DEFAULT_FILE_SIZE); + defaultDownloadFileAddress, defaultFileId, DEFAULT_FILE_SIZE); } @Override diff --git a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/perf/GetAuditTrailsFileStressIT.java b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/perf/GetAuditTrailsFileStressIT.java index a6c00a404..5b8325b29 100644 --- a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/perf/GetAuditTrailsFileStressIT.java +++ b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/perf/GetAuditTrailsFileStressIT.java @@ -25,25 +25,56 @@ import org.bitrepository.access.getaudittrails.AuditTrailClient; import org.bitrepository.access.getaudittrails.BlockingAuditTrailClient; import org.bitrepository.client.eventhandler.EventHandler; +import org.bitrepository.common.utils.TestFileHelper; +import org.bitrepository.modify.ModifyComponentFactory; +import org.bitrepository.modify.putfile.BlockingPutFileClient; +import org.bitrepository.modify.putfile.PutFileClient; import org.bitrepository.pillar.integration.perf.metrics.Metrics; import org.bitrepository.protocol.security.DummySecurityManager; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; public class GetAuditTrailsFileStressIT extends PillarPerformanceTest { protected AuditTrailClient auditTrailClient; + PutFileClient putClient; - @BeforeMethod(alwaysRun=true) + @BeforeEach public void initialiseReferenceTest() throws Exception { + putClient = ModifyComponentFactory.getInstance().retrievePutClient( + settingsForTestClient, createSecurityManager(), settingsForTestClient.getComponentID() ); auditTrailClient = AccessComponentFactory.getInstance().createAuditTrailClient( - settingsForCUT, new DummySecurityManager(), settingsForCUT.getComponentID() - ); + settingsForCUT, new DummySecurityManager(), settingsForCUT.getComponentID()); } - @Test( groups = {"pillar-stress-test"}, dependsOnGroups={"stress-test-pillar-population"}) + private void singleTreadedPut() throws Exception { + final int NUMBER_OF_FILES = 10; + final int PART_STATISTIC_INTERVAL = 2; + addDescription("Attempt to put " + NUMBER_OF_FILES + " files into the pillar, one at a time."); + BlockingPutFileClient blockingPutFileClient = new BlockingPutFileClient(putClient); + String[] fileIDs = TestFileHelper.createFileIDs(NUMBER_OF_FILES, "singleTreadedPutTest"); + Metrics metrics = new Metrics("put", NUMBER_OF_FILES, PART_STATISTIC_INTERVAL); + metrics.addAppenders(metricAppenders); + metrics.start(); + addStep("Add " + NUMBER_OF_FILES + " files", "Not errors should occur"); + for (String fileID:fileIDs) { + blockingPutFileClient.putFile(collectionID, httpServerConfiguration.getURL(TestFileHelper.DEFAULT_FILE_ID), fileID, 10L, + TestFileHelper.getDefaultFileChecksum(), null, null, "singleTreadedPut stress test file"); + metrics.mark(fileID); + } + + addStep("Check that the files are now present on the pillar(s)", "No missing files should be found."); + //ToDo assert that the files are present + } + + @Test + @Tag("pillar-stress-test") +// @Disabled public void singleTreadedGetAuditTrails() throws Exception { final int NUMBER_OF_AUDITS = 100; final int PART_STATISTIC_INTERVAL = NUMBER_OF_AUDITS/5; + singleTreadedPut(); addDescription("Attempt to request " + NUMBER_OF_AUDITS + " full audit trails one at a time."); BlockingAuditTrailClient blockingAuditTrailFileClient = new BlockingAuditTrailClient(auditTrailClient); @@ -58,7 +89,9 @@ public void singleTreadedGetAuditTrails() throws Exception { } } - @Test( groups = {"pillar-stress-test"}) + @Test + @Tag("pillar-stress-test") + @Disabled public void parallelGetAuditTrails() throws Exception { final int NUMBER_OF_AUDITS = 10; final int PART_STATISTIC_INTERVAL = NUMBER_OF_AUDITS/5; diff --git a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/perf/GetFileStressIT.java b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/perf/GetFileStressIT.java index 0b341c9ba..ddebc5b6b 100644 --- a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/perf/GetFileStressIT.java +++ b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/perf/GetFileStressIT.java @@ -6,16 +6,16 @@ * Copyright (C) 2010 - 2012 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% @@ -32,20 +32,22 @@ import org.bitrepository.pillar.integration.perf.metrics.Metrics; import org.bitrepository.pillar.messagefactories.GetFileMessageFactory; import org.bitrepository.protocol.bus.MessageReceiver; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; public class GetFileStressIT extends PillarPerformanceTest { protected GetFileClient getFileClient; - @BeforeMethod(alwaysRun=true) + @BeforeEach public void initialiseReferenceTest() throws Exception { getFileClient = AccessComponentFactory.getInstance().createGetFileClient( settingsForTestClient, createSecurityManager(), settingsForTestClient.getComponentID() ); } - @Test( groups = {"pillar-stress-test"}) + @Test + @Tag("pillar-stress-test") public void singleGetFilePerformanceTest() throws Exception { final int NUMBER_OF_FILES = 1000; final int PART_STATISTIC_INTERVAL = 100; @@ -56,15 +58,16 @@ public void singleGetFilePerformanceTest() throws Exception { metrics.addAppenders(metricAppenders); metrics.start(); addStep("Getting " + NUMBER_OF_FILES + " files", "Not errors should occur"); - for (String fileID:fileIDs) { + for (String fileID : fileIDs) { blockingGetFileClient.getFileFromSpecificPillar( - collectionID, DEFAULT_FILE_ID, null, httpServerConfiguration.getURL(NON_DEFAULT_FILE_ID), getPillarID(), null, + collectionID, defaultFileId, null, httpServerConfiguration.getURL(nonDefaultFileId), getPillarID(), null, "performing singleGetFilePerformanceTest"); metrics.mark(fileID); } } - @Test( groups = {"pillar-stress-test"}) + @Test + @Tag("pillar-stress-test") public void parallelGetFilePerformanceTest() throws Exception { final int numberOfFiles = testConfiguration.getInt("pillarintegrationtest.GetFileStressIT.parallelGet.numberOfFiles"); final int partStatisticsInterval = testConfiguration.getInt("pillarintegrationtest.GetFileStressIT.parallelGet.partStatisticsInterval"); @@ -79,9 +82,9 @@ public void parallelGetFilePerformanceTest() throws Exception { ParallelOperationLimiter getLimiter = new ParallelOperationLimiter(numberOfParallelGets); EventHandler eventHandler = new OperationEventHandlerForMetrics(metrics, getLimiter); for (int i = 1; i <= numberOfFiles; i++) { - getLimiter.addJob(DEFAULT_FILE_ID); + getLimiter.addJob(defaultFileId); getFileClient.getFileFromSpecificPillar( - collectionID, DEFAULT_FILE_ID, null, httpServerConfiguration.getURL(NON_DEFAULT_FILE_ID + "-" + i), getPillarID(), + collectionID, defaultFileId, null, httpServerConfiguration.getURL(nonDefaultFileId + "-" + i), getPillarID(), eventHandler, " performing parallelGetFilePerformance"); } @@ -89,7 +92,8 @@ public void parallelGetFilePerformanceTest() throws Exception { awaitAsynchronousCompletion(metrics, numberOfFiles); } - @Test( groups = {"pillar-stress-test"}) + @Test + @Tag("pillar-stress-test") public void noIdentfyGetFilePerformanceTest() throws Exception { final int numberOfFiles = testConfiguration.getInt("pillarintegrationtest.GetFileStressIT.parallelGet.numberOfFiles"); final int partStatisticsInterval = testConfiguration.getInt("pillarintegrationtest.GetFileStressIT.parallelGet.partStatisticsInterval"); @@ -110,8 +114,8 @@ public void noIdentfyGetFilePerformanceTest() throws Exception { getLimiter.addJob(correlationID); GetFileRequest getRequest = msgFactory.createGetFileRequest("noIdentfyGetFilePerformanceTest", correlationID, - httpServerConfiguration.getURL(NON_DEFAULT_FILE_ID + "-" + i).toExternalForm(), DEFAULT_FILE_ID, null, - getPillarID(), getPillarID(), settingsForTestClient.getReceiverDestinationID(), pillarDestination); + httpServerConfiguration.getURL(nonDefaultFileId + "-" + i).toExternalForm(), defaultFileId, null, + getPillarID(), getPillarID(), settingsForTestClient.getReceiverDestinationID(), pillarDestination); messageBus.sendMessage(getRequest); } @@ -120,11 +124,11 @@ public void noIdentfyGetFilePerformanceTest() throws Exception { public String lookupGetFileDestination() { MessageReceiver clientReceiver = new MessageReceiver(settingsForTestClient.getReceiverDestinationID(), testEventManager); - messageBus.addListener(clientReceiver.getDestination(), clientReceiver.getMessageListener());; + messageBus.addListener(clientReceiver.getDestination(), clientReceiver.getMessageListener()); GetFileMessageFactory pillarLookupmMsgFactory = new GetFileMessageFactory(collectionID, settingsForTestClient, getPillarID(), null); IdentifyPillarsForGetFileRequest identifyRequest = - pillarLookupmMsgFactory.createIdentifyPillarsForGetFileRequest(DEFAULT_FILE_ID); + pillarLookupmMsgFactory.createIdentifyPillarsForGetFileRequest(defaultFileId); messageBus.sendMessage(identifyRequest); String pillarDestination = clientReceiver.waitForMessage(IdentifyPillarsForGetFileResponse.class).getReplyTo(); messageBus.removeListener(clientReceiver.getDestination(), clientReceiver.getMessageListener()); diff --git a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/perf/PillarPerformanceTest.java b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/perf/PillarPerformanceTest.java index 4ad5af7cf..37353cc1a 100644 --- a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/perf/PillarPerformanceTest.java +++ b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/perf/PillarPerformanceTest.java @@ -37,8 +37,6 @@ import org.bitrepository.protocol.messagebus.MessageListener; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.testng.ITestContext; -import org.testng.annotations.BeforeSuite; import java.util.LinkedList; import java.util.List; @@ -50,13 +48,6 @@ public class PillarPerformanceTest extends PillarIntegrationTest { protected List metricAppenders = new LinkedList<>(); protected String[] existingFiles; - @BeforeSuite - @Override - public void initializeSuite(ITestContext testContext) { - super.initializeSuite(testContext); - defineMetricAppenders(); - } - private void defineMetricAppenders() { MetricAppender consoleAppender = new ConsoleMetricAppender(); consoleAppender.disableSingleMeasurement(true); diff --git a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/perf/PutFileStressIT.java b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/perf/PutFileStressIT.java index 76b212d9f..6c908f435 100644 --- a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/perf/PutFileStressIT.java +++ b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/perf/PutFileStressIT.java @@ -28,8 +28,9 @@ import org.bitrepository.modify.putfile.BlockingPutFileClient; import org.bitrepository.modify.putfile.PutFileClient; import org.bitrepository.pillar.integration.perf.metrics.Metrics; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; @@ -37,14 +38,17 @@ public class PutFileStressIT extends PillarPerformanceTest { protected PutFileClient putClient; - @BeforeMethod(alwaysRun=true) + @BeforeEach public void initialiseReferenceTest() throws Exception { putClient = ModifyComponentFactory.getInstance().retrievePutClient( settingsForTestClient, createSecurityManager(), settingsForTestClient.getComponentID() ); } - @Test( groups = {"pillar-stress-test", "stress-test-pillar-population"}) + @Test + @Tag("pillar-stress-test") + @Tag("stress-test-pillar-population") +// @Disabled public void singleTreadedPut() throws Exception { final int NUMBER_OF_FILES = 10; final int PART_STATISTIC_INTERVAL = 2; @@ -65,7 +69,9 @@ public void singleTreadedPut() throws Exception { //ToDo assert that the files are present } - @Test( groups = {"pillar-stress-test"}) + @Test + @Tag("pillar-stress-test") +// @Disabled public void parallelPut() throws Exception { final int numberOfFiles = testConfiguration.getInt("pillarintegrationtest.PutFileStressIT.parallelPut.numberOfFiles"); final int partStatisticsInterval = testConfiguration.getInt("pillarintegrationtest.PutFileStressIT.parallelPut.partStatisticsInterval"); diff --git a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/perf/metrics/Metrics.java b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/perf/metrics/Metrics.java index ba87a5303..1253f0319 100644 --- a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/perf/metrics/Metrics.java +++ b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/perf/metrics/Metrics.java @@ -35,7 +35,7 @@ public class Metrics { private long lastPartTime; private int lastPartCount = 0; - private List appenderList = new LinkedList<>(); + private final List appenderList = new LinkedList<>(); public Metrics(String operationName, int numberOfFiles, int partInterval) { this.operationName = operationName; diff --git a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/messagehandling/DeleteFileTest.java b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/messagehandling/DeleteFileTest.java index fa3e760c6..cc55b4751 100644 --- a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/messagehandling/DeleteFileTest.java +++ b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/messagehandling/DeleteFileTest.java @@ -1,23 +1,23 @@ /* * #%L * Bitrepository Reference Pillar - * + * * $Id: PutFileOnReferencePillarTest.java 589 2011-12-01 15:34:42Z jolf $ * $HeadURL: https://sbforge.org/svn/bitrepository/bitrepository-reference/trunk/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/PutFileOnReferencePillarTest.java $ * %% * Copyright (C) 2010 - 2011 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% @@ -35,15 +35,17 @@ import org.bitrepository.bitrepositorymessages.IdentifyPillarsForDeleteFileResponse; import org.bitrepository.pillar.MockedPillarTest; import org.bitrepository.pillar.messagefactories.DeleteFileMessageFactory; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; -import org.testng.annotations.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doAnswer; -import static org.testng.Assert.assertEquals; + /** * Tests the PutFile functionality on the ReferencePillar. @@ -58,13 +60,15 @@ public void initializeCUT() { } @SuppressWarnings("rawtypes") - @Test( groups = {"regressiontest", "pillartest"}) + @Test + @Tag("regressiontest") + @Tag("pillartest") public void goodCaseIdentification() throws Exception { addDescription("Tests the identification for a DeleteFile operation on the pillar for the successful scenario."); addStep("Set up constants and variables.", "Should not fail here!"); - final String FILE_ID = DEFAULT_FILE_ID + testMethodName; + final String FILE_ID = defaultFileId + testMethodName; - addStep("Setup for having the file and delivering pillar id", + addStep("Setup for having the file and delivering pillar id", "Should return true, when requesting file-id existence."); doAnswer(new Answer() { public Boolean answer(InvocationOnMock invocation) { @@ -86,23 +90,25 @@ public String answer(InvocationOnMock invocation) { "The pillar should make a response."); IdentifyPillarsForDeleteFileResponse receivedIdentifyResponse = clientReceiver.waitForMessage( IdentifyPillarsForDeleteFileResponse.class); - assertEquals(receivedIdentifyResponse.getResponseInfo().getResponseCode(), - ResponseCode.IDENTIFICATION_POSITIVE); + assertEquals(ResponseCode.IDENTIFICATION_POSITIVE, + receivedIdentifyResponse.getResponseInfo().getResponseCode()); assertEquals(receivedIdentifyResponse.getPillarID(), getPillarID()); assertEquals(receivedIdentifyResponse.getFileID(), FILE_ID); alarmReceiver.checkNoMessageIsReceived(AlarmMessage.class); - assertEquals(audits.getCallsForAuditEvent(), 0, "Should not deliver audits"); + assertEquals(0, audits.getCallsForAuditEvent(), "Should not deliver audits"); } @SuppressWarnings("rawtypes") - @Test( groups = {"regressiontest", "pillartest"}) + @Test + @Tag("regressiontest") + @Tag("pillartest") public void badCaseIdentification() throws Exception { addDescription("Tests the identification for a DeleteFile operation on the checksum pillar for the failure scenario, when the file is missing."); addStep("Set up constants and variables.", "Should not fail here!"); - final String FILE_ID = DEFAULT_FILE_ID + testMethodName; + final String FILE_ID = defaultFileId + testMethodName; - addStep("Setup for delivering pillar id and not having the file ", + addStep("Setup for delivering pillar id and not having the file ", "Returns false, when requesting file-id existence."); doAnswer(new Answer() { public Boolean answer(InvocationOnMock invocation) { @@ -124,23 +130,25 @@ public String answer(InvocationOnMock invocation) { "The pillar should make a response."); IdentifyPillarsForDeleteFileResponse receivedIdentifyResponse = clientReceiver.waitForMessage( IdentifyPillarsForDeleteFileResponse.class); - assertEquals(receivedIdentifyResponse.getResponseInfo().getResponseCode(), - ResponseCode.FILE_NOT_FOUND_FAILURE); + assertEquals(ResponseCode.FILE_NOT_FOUND_FAILURE, + receivedIdentifyResponse.getResponseInfo().getResponseCode()); assertEquals(receivedIdentifyResponse.getPillarID(), getPillarID()); assertEquals(receivedIdentifyResponse.getFileID(), FILE_ID); alarmReceiver.checkNoMessageIsReceived(AlarmMessage.class); - assertEquals(audits.getCallsForAuditEvent(), 0, "Should not deliver audits"); + assertEquals(0, audits.getCallsForAuditEvent(), "Should not deliver audits"); } @SuppressWarnings("rawtypes") - @Test( groups = {"regressiontest", "pillartest"}) + @Test + @Tag("regressiontest") + @Tag("pillartest") public void badCaseOperationNoFile() throws Exception { addDescription("Tests the DeleteFile functionality of the pillar for the failure scenario, where it does not have the file."); addStep("Set up constants and variables.", "Should not fail here!"); - final String FILE_ID = DEFAULT_FILE_ID + testMethodName; + final String FILE_ID = defaultFileId + testMethodName; - addStep("Setup for delivering pillar id and not having the file ", + addStep("Setup for delivering pillar id and not having the file ", "Returns false, when requesting file-id existence."); doAnswer(new Answer() { public Boolean answer(InvocationOnMock invocation) { @@ -162,22 +170,24 @@ public String answer(InvocationOnMock invocation) { addStep("Retrieve the FinalResponse for the DeleteFile request", "The final response should tell about the error, and not contain the file."); DeleteFileFinalResponse finalResponse = clientReceiver.waitForMessage(DeleteFileFinalResponse.class); - assertEquals(finalResponse.getResponseInfo().getResponseCode(), ResponseCode.FILE_NOT_FOUND_FAILURE); + assertEquals(ResponseCode.FILE_NOT_FOUND_FAILURE, finalResponse.getResponseInfo().getResponseCode()); assertEquals(finalResponse.getPillarID(), getPillarID()); assertEquals(finalResponse.getFileID(), FILE_ID); alarmReceiver.checkNoMessageIsReceived(AlarmMessage.class); - assertEquals(audits.getCallsForAuditEvent(), 0, "Should not deliver audits"); + assertEquals(0, audits.getCallsForAuditEvent(), "Should not deliver audits"); } - + @SuppressWarnings("rawtypes") - @Test( groups = {"regressiontest", "pillartest"}) + @Test + @Tag("regressiontest") + @Tag("pillartest") public void badCaseOperationMissingVerification() throws Exception { addDescription("Tests the DeleteFile functionality of the pillar for the failure scenario, where it does not have the file."); addStep("Set up constants and variables.", "Should not fail here!"); - final String FILE_ID = DEFAULT_FILE_ID + testMethodName; + final String FILE_ID = defaultFileId + testMethodName; - addStep("Setup for delivering pillar id and having the file ", + addStep("Setup for delivering pillar id and having the file ", "Returns true, when requesting file-id existence."); doAnswer(new Answer() { public Boolean answer(InvocationOnMock invocation) { @@ -199,7 +209,7 @@ public String answer(InvocationOnMock invocation) { addStep("Retrieve the FinalResponse for the DeleteFile request", "The final response should tell about the error, and not contain the file."); DeleteFileFinalResponse finalResponse = clientReceiver.waitForMessage(DeleteFileFinalResponse.class); - assertEquals(finalResponse.getResponseInfo().getResponseCode(), ResponseCode.EXISTING_FILE_CHECKSUM_FAILURE); + assertEquals(ResponseCode.EXISTING_FILE_CHECKSUM_FAILURE, finalResponse.getResponseInfo().getResponseCode()); assertEquals(finalResponse.getPillarID(), getPillarID()); assertEquals(finalResponse.getFileID(), FILE_ID); @@ -207,20 +217,21 @@ public String answer(InvocationOnMock invocation) { AlarmMessage alarm = alarmReceiver.waitForMessage(AlarmMessage.class); assertEquals(alarm.getAlarm().getFileID(), FILE_ID); assertEquals(alarm.getAlarm().getAlarmRaiser(), getPillarID()); - assertEquals(alarm.getAlarm().getAlarmCode(), AlarmCode.CHECKSUM_ALARM); - - assertEquals(audits.getCallsForAuditEvent(), 0, "Should not deliver audits"); + assertEquals(AlarmCode.CHECKSUM_ALARM, alarm.getAlarm().getAlarmCode()); + + assertEquals(0, audits.getCallsForAuditEvent(), "Should not deliver audits"); } - + @SuppressWarnings("rawtypes") - //@Test( groups = {"regressiontest", "pillartest"}) + //@Test +// @Tag("regressiontest", "pillartest"}) // FAILS, when combined with other tests... public void goodCaseOperation() throws Exception { addDescription("Tests the DeleteFile functionality of the pillar for the success scenario, where the file is uploaded."); addStep("Set up constants and variables.", "Should not fail here!"); - final String FILE_ID = DEFAULT_FILE_ID + testMethodName; + final String FILE_ID = defaultFileId + testMethodName; - addStep("Setup for delivering pillar id, having the file with expected checksum, and no errors when deleting file.", + addStep("Setup for delivering pillar id, having the file with expected checksum, and no errors when deleting file.", "Returns true, when requesting file-id existence."); doAnswer(new Answer() { public Boolean answer(InvocationOnMock invocation) { @@ -237,7 +248,7 @@ public String answer(InvocationOnMock invocation) { return DEFAULT_MD5_CHECKSUM; } }).when(model).getChecksumForFile(eq(FILE_ID), anyString(), any(ChecksumSpecTYPE.class)); - + addStep("Create and send the actual DeleteFile message to the pillar.", "Should be received and handled by the pillar."); DeleteFileRequest DeleteFileRequest = msgFactory.createDeleteFileRequest(csData, csSpec, FILE_ID); @@ -252,11 +263,11 @@ public String answer(InvocationOnMock invocation) { addStep("Retrieve the FinalResponse for the DeleteFile request", "The final response should tell about the error, and not contain the file."); DeleteFileFinalResponse finalResponse = clientReceiver.waitForMessage(DeleteFileFinalResponse.class); - assertEquals(finalResponse.getResponseInfo().getResponseCode(), ResponseCode.OPERATION_COMPLETED); + assertEquals(ResponseCode.OPERATION_COMPLETED, finalResponse.getResponseInfo().getResponseCode()); assertEquals(finalResponse.getPillarID(), getPillarID()); assertEquals(finalResponse.getFileID(), FILE_ID); alarmReceiver.checkNoMessageIsReceived(AlarmMessage.class); - assertEquals(audits.getCallsForAuditEvent(), 1, "Should create one audit trail for the DeleteFile operation"); + assertEquals(1, audits.getCallsForAuditEvent(), "Should create one audit trail for the DeleteFile operation"); } } diff --git a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/messagehandling/GeneralMessageHandlingTest.java b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/messagehandling/GeneralMessageHandlingTest.java index 53cb1068b..e6b852eeb 100644 --- a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/messagehandling/GeneralMessageHandlingTest.java +++ b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/messagehandling/GeneralMessageHandlingTest.java @@ -1,23 +1,23 @@ /* * #%L * Bitrepository Reference Pillar - * + * * $Id: PutFileOnReferencePillarTest.java 589 2011-12-01 15:34:42Z jolf $ * $HeadURL: https://sbforge.org/svn/bitrepository/bitrepository-reference/trunk/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/PutFileOnReferencePillarTest.java $ * %% * Copyright (C) 2010 - 2011 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% @@ -32,86 +32,119 @@ import org.bitrepository.pillar.store.StorageModel; import org.bitrepository.protocol.MessageContext; import org.bitrepository.service.exception.RequestHandlerException; -import org.testng.Assert; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertThrows; public class GeneralMessageHandlingTest extends MockedPillarTest { - + MockRequestHandler requestHandler; - - @BeforeMethod(alwaysRun = true) + + @BeforeEach public void setup() { this.requestHandler = new MockRequestHandler(context, model); } - - @Test( groups = {"regressiontest", "pillartest"}) + + @Test + @Tag("regressiontest") + @Tag("pillartest") public void testPillarMessageHandler() { addDescription("Test the handling of the PillarMessageHandler super-class."); addStep("Setup", "Should be OK."); - + addStep("Test the pillar ID", "Should be Ok, with the id from settings, but not with another pillar id"); requestHandler.validatePillarID(getPillarID()); try { requestHandler.validatePillarID("asdfghjklæwetyguvpbmopijå.døtphstiøyizhdfvgnayegtxtæhjmdtuilsfm,s"); - Assert.fail("Should throw an IllegalArgumentException here!"); + Assertions.fail("Should throw an IllegalArgumentException here!"); } catch (IllegalArgumentException e) { // expected } } - - @Test( groups = {"regressiontest", "pillartest"}) + + @Test + @Tag("regressiontest") + @Tag("pillartest") public void testPillarMessageHandlerValidateFileIDFormatDefaultFileId() throws Exception { addDescription("Test the validation of file id formats of the PillarMessageHandler super-class on the default file id"); - requestHandler.validateFileIDFormat(DEFAULT_FILE_ID); + requestHandler.validateFileIDFormat(defaultFileId); } - - @Test( groups = {"regressiontest", "pillartest"}) + + @Test + @Tag("regressiontest") + @Tag("pillartest") public void testPillarMessageHandlerValidateFileIDFormatFolderFileId() throws Exception { addDescription("Test the validation of file id formats of the PillarMessageHandler super-class on a file id with directory path"); - requestHandler.validateFileIDFormat("path/" + DEFAULT_FILE_ID); + requestHandler.validateFileIDFormat("path/" + defaultFileId); } - - @Test( groups = {"regressiontest", "pillartest"}, expectedExceptions = RequestHandlerException.class) + + @Test + @Tag("regressiontest") + @Tag("pillartest") public void testPillarMessageHandlerValidateFileIDFormatParentFolderFileId() throws Exception { - addDescription("Test the validation of file id formats of the PillarMessageHandler super-class on a file id containing path to a parent directory"); - requestHandler.validateFileIDFormat("../../OTHER_COLLECTION/folderDir/test.txt"); + assertThrows(RequestHandlerException.class, () -> { + addDescription("Test the validation of file id formats of the PillarMessageHandler super-class on a file id containing path to a parent directory"); + requestHandler.validateFileIDFormat("../../OTHER_COLLECTION/folderDir/test.txt"); + }); } - - @Test( groups = {"regressiontest", "pillartest"}, expectedExceptions = RequestHandlerException.class) + + @Test + @Tag("regressiontest") + @Tag("pillartest") public void testPillarMessageHandlerValidateFileIDFormatRootPathFileId() throws Exception { - addDescription("Test the validation of file id formats of the PillarMessageHandler super-class on a file id containing path from the root folder"); - requestHandler.validateFileIDFormat("/usr/local/bin/execute.sh"); + assertThrows(RequestHandlerException.class, () -> { + addDescription("Test the validation of file id formats of the PillarMessageHandler super-class on a file id containing path from the root folder"); + requestHandler.validateFileIDFormat("/usr/local/bin/execute.sh"); + }); } - - @Test( groups = {"regressiontest", "pillartest"}, expectedExceptions = RequestHandlerException.class) + + @Test + @Tag("regressiontest") + @Tag("pillartest") public void testPillarMessageHandlerValidateFileIDFormatSubFolderToParentFolderFileId() throws Exception { - addDescription("Test the validation of file id formats of the PillarMessageHandler super-class on a file id containing path to a parent directory, but starting with a sub-folder"); - requestHandler.validateFileIDFormat("OTHER_COLLECTION/../../folderDir/test.txt"); + assertThrows(RequestHandlerException.class, () -> { + addDescription("Test the validation of file id formats of the PillarMessageHandler super-class on a file id containing path to a parent directory, but starting with a sub-folder"); + requestHandler.validateFileIDFormat("OTHER_COLLECTION/../../folderDir/test.txt"); + }); } - - @Test( groups = {"regressiontest", "pillartest"}, expectedExceptions = RequestHandlerException.class) + + @Test + @Tag("regressiontest") + @Tag("pillartest") public void testPillarMessageHandlerValidateFileIDFormatEnvHomePathFileId() throws Exception { - addDescription("Test the validation of file id formats of the PillarMessageHandler super-class on a file id containing path relative paths from the environment variable home folder"); - requestHandler.validateFileIDFormat("$HOME/bin/execute.sh"); + assertThrows(RequestHandlerException.class, () -> { + addDescription("Test the validation of file id formats of the PillarMessageHandler super-class on a file id containing path relative paths from the environment variable home folder"); + requestHandler.validateFileIDFormat("$HOME/bin/execute.sh"); + }); } - - @Test( groups = {"regressiontest", "pillartest"}, expectedExceptions = RequestHandlerException.class) + + @Test + @Tag("regressiontest") + @Tag("pillartest") public void testPillarMessageHandlerValidateFileIDFormatTildeHomePathFileId() throws Exception { - addDescription("Test the validation of file id formats of the PillarMessageHandler super-class on a file id containing path relative paths from the tilde home folder"); - requestHandler.validateFileIDFormat("~/bin/execute.sh"); + assertThrows(RequestHandlerException.class, () -> { + addDescription("Test the validation of file id formats of the PillarMessageHandler super-class on a file id containing path relative paths from the tilde home folder"); + requestHandler.validateFileIDFormat("~/bin/execute.sh"); + }); } - - @Test( groups = {"regressiontest", "pillartest"}, expectedExceptions = RequestHandlerException.class) + + @Test + @Tag("regressiontest") + @Tag("pillartest") public void testPillarMessageHandlerValidateFileIDFormatTooLong() throws Exception { - addDescription("Test the validation of file id formats of the PillarMessageHandler super-class on a file id which has more characters than required"); - String fileId = ""; - for(int i = 0; i < 300; i++) { - fileId += Integer.toString(i); - } - requestHandler.validateFileIDFormat(fileId); + assertThrows(RequestHandlerException.class, () -> { + addDescription("Test the validation of file id formats of the PillarMessageHandler super-class on a file id which has more characters than required"); + String fileId = ""; + for (int i = 0; i < 300; i++) { + fileId += Integer.toString(i); + } + requestHandler.validateFileIDFormat(fileId); + }); } - + private class MockRequestHandler extends PillarMessageHandler { protected MockRequestHandler(MessageHandlerContext context, StorageModel model) { @@ -124,17 +157,18 @@ public Class getRequestClass() { } @Override - public void processRequest(MessageRequest request, MessageContext messageContext) {} - + public void processRequest(MessageRequest request, MessageContext messageContext) { + } + @Override public MessageResponse generateFailedResponse(MessageRequest request) { return null; } - + public void validatePillarID(String pillarID) { super.validatePillarID(pillarID); } - + public void validateFileIDFormat(String fileID) throws RequestHandlerException { super.validateFileIDFormat(fileID); } diff --git a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/messagehandling/GetAuditTrailsTest.java b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/messagehandling/GetAuditTrailsTest.java index 10ee4ed1d..bf1d7d209 100644 --- a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/messagehandling/GetAuditTrailsTest.java +++ b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/messagehandling/GetAuditTrailsTest.java @@ -32,15 +32,16 @@ import org.bitrepository.common.utils.CalendarUtils; import org.bitrepository.pillar.MockedPillarTest; import org.bitrepository.pillar.messagefactories.GetAuditTrailsMessageFactory; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; import javax.xml.datatype.XMLGregorianCalendar; import java.math.BigInteger; import java.util.Date; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; public class GetAuditTrailsTest extends MockedPillarTest { private GetAuditTrailsMessageFactory msgFactory; @@ -51,7 +52,9 @@ public void initializeCUT() { msgFactory = new GetAuditTrailsMessageFactory(collectionID, settingsForTestClient); } - @Test( groups = {"regressiontest", "pillartest"}) + @Test + @Tag("regressiontest") + @Tag("pillartest") public void checksumPillarGetAuditTrailsSuccessful() { addDescription("Tests the GetAuditTrails functionality of the pillar for the successful scenario, " + "where all audit trails are requested."); @@ -71,8 +74,8 @@ public void checksumPillarGetAuditTrailsSuccessful() { assertEquals(receivedIdentifyResponse.getCorrelationID(), identifyRequest.getCorrelationID()); assertEquals(receivedIdentifyResponse.getFrom(), settingsForCUT.getComponentID()); assertEquals(receivedIdentifyResponse.getDestination(), identifyRequest.getReplyTo()); - assertEquals(receivedIdentifyResponse.getResponseInfo().getResponseCode(), - ResponseCode.IDENTIFICATION_POSITIVE); + assertEquals(ResponseCode.IDENTIFICATION_POSITIVE, + receivedIdentifyResponse.getResponseInfo().getResponseCode()); addStep("Make and send the request for the actual GetAuditTrails operation", "Should be caught and handled by the pillar."); @@ -87,8 +90,8 @@ public void checksumPillarGetAuditTrailsSuccessful() { assertEquals(progressResponse.getCorrelationID(), identifyRequest.getCorrelationID()); assertEquals(progressResponse.getFrom(), settingsForCUT.getComponentID()); assertEquals(receivedIdentifyResponse.getDestination(), identifyRequest.getReplyTo()); - assertEquals(progressResponse.getResponseInfo().getResponseCode(), - ResponseCode.OPERATION_ACCEPTED_PROGRESS); + assertEquals(ResponseCode.OPERATION_ACCEPTED_PROGRESS, + progressResponse.getResponseInfo().getResponseCode()); addStep("Receive and validate the final response", "Should be sent by the pillar."); GetAuditTrailsFinalResponse finalResponse = clientReceiver.waitForMessage(GetAuditTrailsFinalResponse.class); @@ -96,11 +99,13 @@ public void checksumPillarGetAuditTrailsSuccessful() { assertEquals(receivedIdentifyResponse.getCorrelationID(), identifyRequest.getCorrelationID()); assertEquals(receivedIdentifyResponse.getFrom(), settingsForCUT.getComponentID()); assertEquals(receivedIdentifyResponse.getDestination(), identifyRequest.getReplyTo()); - assertEquals(finalResponse.getResponseInfo().getResponseCode(), ResponseCode.OPERATION_COMPLETED); - assertEquals(finalResponse.getResultingAuditTrails().getAuditTrailEvents().getAuditTrailEvent().size(), 1); + assertEquals(ResponseCode.OPERATION_COMPLETED, finalResponse.getResponseInfo().getResponseCode()); + assertEquals(1, finalResponse.getResultingAuditTrails().getAuditTrailEvents().getAuditTrailEvent().size()); } - @Test( groups = {"regressiontest", "pillartest"}) + @Test + @Tag("regressiontest") + @Tag("pillartest") public void checksumPillarGetAuditTrailsSpecificRequests() { addDescription("Tests the GetAuditTrails functionality of the pillar for the successful scenario, " + "where a specific audit trail are requested."); @@ -128,8 +133,8 @@ public void checksumPillarGetAuditTrailsSpecificRequests() { addStep("Retrieve and validate the response.", "Should be a positive response."); IdentifyContributorsForGetAuditTrailsResponse identifyResponse = clientReceiver.waitForMessage( IdentifyContributorsForGetAuditTrailsResponse.class); - assertEquals(identifyResponse.getResponseInfo().getResponseCode(), - ResponseCode.IDENTIFICATION_POSITIVE); + assertEquals(ResponseCode.IDENTIFICATION_POSITIVE, + identifyResponse.getResponseInfo().getResponseCode()); addStep("Make and send the request for the actual GetAuditTrails operation", "Should be caught and handled by the pillar."); @@ -140,19 +145,19 @@ public void checksumPillarGetAuditTrailsSpecificRequests() { addStep("Receive and validate the progress response.", "Should be sent by the pillar."); GetAuditTrailsProgressResponse progressResponse = clientReceiver.waitForMessage(GetAuditTrailsProgressResponse.class); - assertEquals(progressResponse.getResponseInfo().getResponseCode(), - ResponseCode.OPERATION_ACCEPTED_PROGRESS); + assertEquals(ResponseCode.OPERATION_ACCEPTED_PROGRESS, + progressResponse.getResponseInfo().getResponseCode()); addStep("Receive and validate the final response", "Should be sent by the pillar."); GetAuditTrailsFinalResponse finalResponse = clientReceiver.waitForMessage(GetAuditTrailsFinalResponse.class); - assertEquals(finalResponse.getResponseInfo().getResponseCode(), ResponseCode.OPERATION_COMPLETED); - assertEquals(finalResponse.getResultingAuditTrails().getAuditTrailEvents().getAuditTrailEvent().size(), 1); + assertEquals(ResponseCode.OPERATION_COMPLETED, finalResponse.getResponseInfo().getResponseCode()); + assertEquals(1, finalResponse.getResultingAuditTrails().getAuditTrailEvents().getAuditTrailEvent().size()); AuditTrailEvent event = finalResponse.getResultingAuditTrails().getAuditTrailEvents().getAuditTrailEvent().get(0); - assertEquals(event.getActorOnFile(), ACTOR); - assertEquals(event.getAuditTrailInformation(), AUDITTRAIL); + assertEquals(ACTOR, event.getActorOnFile()); + assertEquals(AUDITTRAIL, event.getAuditTrailInformation()); assertEquals(event.getFileID(), FILE_ID); - assertEquals(event.getInfo(), INFO); - assertEquals(event.getSequenceNumber(), BigInteger.ONE); + assertEquals(INFO, event.getInfo()); + assertEquals(BigInteger.ONE, event.getSequenceNumber()); addStep("Make another request, where both ingested audit trails is requested", "Should be handled by the pillar."); @@ -162,17 +167,19 @@ public void checksumPillarGetAuditTrailsSpecificRequests() { addStep("Receive and validate the progress response.", "Should be sent by the pillar."); progressResponse = clientReceiver.waitForMessage(GetAuditTrailsProgressResponse.class); - assertEquals(progressResponse.getResponseInfo().getResponseCode(), - ResponseCode.OPERATION_ACCEPTED_PROGRESS); + assertEquals(ResponseCode.OPERATION_ACCEPTED_PROGRESS, + progressResponse.getResponseInfo().getResponseCode()); addStep("Receive and validate the final response", "Should be sent by the pillar."); finalResponse = clientReceiver.waitForMessage(GetAuditTrailsFinalResponse.class); - assertEquals(finalResponse.getResponseInfo().getResponseCode(), ResponseCode.OPERATION_COMPLETED); - assertEquals(finalResponse.getResultingAuditTrails().getAuditTrailEvents().getAuditTrailEvent().size(), 2); + assertEquals(ResponseCode.OPERATION_COMPLETED, finalResponse.getResponseInfo().getResponseCode()); + assertEquals(2, finalResponse.getResultingAuditTrails().getAuditTrailEvents().getAuditTrailEvent().size()); assertFalse(finalResponse.isPartialResult()); } - @Test( groups = {"regressiontest", "pillartest"}) + @Test + @Tag("regressiontest") + @Tag("pillartest") public void checksumPillarGetAuditTrailsMaximumNumberOfResults() { addDescription("Tests the GetAuditTrails functionality of the pillar for the successful scenario, " + "where a limited number of audit trails are requested."); @@ -219,13 +226,13 @@ public void checksumPillarGetAuditTrailsMaximumNumberOfResults() { GetAuditTrailsProgressResponse progressResponse = clientReceiver.waitForMessage(GetAuditTrailsProgressResponse.class); assertEquals(progressResponse.getCollectionID(), collectionID); - assertEquals(progressResponse.getResponseInfo().getResponseCode(), ResponseCode.OPERATION_ACCEPTED_PROGRESS); + assertEquals(ResponseCode.OPERATION_ACCEPTED_PROGRESS, progressResponse.getResponseInfo().getResponseCode()); addStep("Validate the final response", "Contains OPERATION_COMPLETE, with only the requested amount of audits, " + "and acknowledges that it is only a partial result set."); GetAuditTrailsFinalResponse finalResponse = clientReceiver.waitForMessage(GetAuditTrailsFinalResponse.class); - assertEquals(finalResponse.getResponseInfo().getResponseCode(), ResponseCode.OPERATION_COMPLETED); - assertEquals(finalResponse.getResultingAuditTrails().getAuditTrailEvents().getAuditTrailEvent().size(), maxNumberOfResults); + assertEquals(ResponseCode.OPERATION_COMPLETED, finalResponse.getResponseInfo().getResponseCode()); + assertEquals(maxNumberOfResults, finalResponse.getResultingAuditTrails().getAuditTrailEvents().getAuditTrailEvent().size()); assertTrue(finalResponse.isSetPartialResult()); } } diff --git a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/messagehandling/GetChecksumsTest.java b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/messagehandling/GetChecksumsTest.java index 3625ecb76..6882dc577 100644 --- a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/messagehandling/GetChecksumsTest.java +++ b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/messagehandling/GetChecksumsTest.java @@ -1,23 +1,23 @@ /* * #%L * Bitrepository Reference Pillar - * + * * $Id: PutFileOnReferencePillarTest.java 589 2011-12-01 15:34:42Z jolf $ * $HeadURL: https://sbforge.org/svn/bitrepository/bitrepository-reference/trunk/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/PutFileOnReferencePillarTest.java $ * %% * Copyright (C) 2010 - 2011 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% @@ -39,19 +39,20 @@ import org.bitrepository.pillar.messagefactories.GetChecksumsMessageFactory; import org.bitrepository.pillar.store.checksumdatabase.ChecksumEntry; import org.bitrepository.pillar.store.checksumdatabase.ExtractedChecksumResultSet; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; -import org.testng.annotations.Test; import javax.xml.datatype.XMLGregorianCalendar; import java.util.Date; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doAnswer; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertNull; /** * Tests the PutFile functionality on the ReferencePillar. @@ -67,14 +68,16 @@ public void initializeCUT() { } @SuppressWarnings("rawtypes") - @Test( groups = {"regressiontest", "pillartest"}) + @Test + @Tag("regressiontest") + @Tag("pillartest") public void goodCaseIdentification() throws Exception { addDescription("Tests the identification for a GetChecksums operation on the pillar for the successful scenario."); addStep("Set up constants and variables.", "Should not fail here!"); - final String FILE_ID = DEFAULT_FILE_ID + testMethodName; + final String FILE_ID = defaultFileId + testMethodName; FileIDs fileids = FileIDsUtils.getSpecificFileIDs(FILE_ID); - - addStep("Setup for having the file and delivering pillar id", + + addStep("Setup for having the file and delivering pillar id", "Should return true, when requesting file-id existence."); doAnswer(new Answer() { public Boolean answer(InvocationOnMock invocation) { @@ -91,29 +94,31 @@ public String answer(InvocationOnMock invocation) { "Should be received and handled by the pillar."); IdentifyPillarsForGetChecksumsRequest identifyRequest = msgFactory.createIdentifyPillarsForGetChecksumsRequest(csSpec, fileids); messageBus.sendMessage(identifyRequest); - + addStep("Retrieve and validate the response getPillarID() the pillar.", "The pillar should make a response."); IdentifyPillarsForGetChecksumsResponse receivedIdentifyResponse = clientReceiver.waitForMessage( IdentifyPillarsForGetChecksumsResponse.class); - assertEquals(receivedIdentifyResponse.getResponseInfo().getResponseCode(), - ResponseCode.IDENTIFICATION_POSITIVE); + assertEquals(ResponseCode.IDENTIFICATION_POSITIVE, + receivedIdentifyResponse.getResponseInfo().getResponseCode()); assertEquals(receivedIdentifyResponse.getPillarID(), getPillarID()); assertEquals(receivedIdentifyResponse.getFileIDs(), fileids); - + alarmReceiver.checkNoMessageIsReceived(AlarmMessage.class); - assertEquals(audits.getCallsForAuditEvent(), 0, "Should not deliver audits"); + assertEquals(0, audits.getCallsForAuditEvent(), "Should not deliver audits"); } - + @SuppressWarnings("rawtypes") - @Test( groups = {"regressiontest", "pillartest"}) + @Test + @Tag("regressiontest") + @Tag("pillartest") public void badCaseIdentification() throws Exception { addDescription("Tests the identification for a GetChecksums operation on the pillar for the failure scenario, when the file is missing."); addStep("Set up constants and variables.", "Should not fail here!"); - final String FILE_ID = DEFAULT_FILE_ID + testMethodName; + final String FILE_ID = defaultFileId + testMethodName; FileIDs fileids = FileIDsUtils.getSpecificFileIDs(FILE_ID); - - addStep("Setup for delivering pillar id and not having the file ", + + addStep("Setup for delivering pillar id and not having the file ", "Should return false, when requesting file-id existence."); doAnswer(new Answer() { public Boolean answer(InvocationOnMock invocation) { @@ -135,21 +140,23 @@ public String answer(InvocationOnMock invocation) { "The pillar should make a response."); IdentifyPillarsForGetChecksumsResponse receivedIdentifyResponse = clientReceiver.waitForMessage( IdentifyPillarsForGetChecksumsResponse.class); - assertEquals(receivedIdentifyResponse.getResponseInfo().getResponseCode(), - ResponseCode.FILE_NOT_FOUND_FAILURE); + assertEquals(ResponseCode.FILE_NOT_FOUND_FAILURE, + receivedIdentifyResponse.getResponseInfo().getResponseCode()); assertEquals(receivedIdentifyResponse.getPillarID(), getPillarID()); assertEquals(receivedIdentifyResponse.getFileIDs(), fileids); - + alarmReceiver.checkNoMessageIsReceived(AlarmMessage.class); - assertEquals(audits.getCallsForAuditEvent(), 0, "Should not deliver audits"); + assertEquals(0, audits.getCallsForAuditEvent(), "Should not deliver audits"); } - + @SuppressWarnings("rawtypes") - @Test( groups = {"regressiontest", "pillartest"}) + @Test + @Tag("regressiontest") + @Tag("pillartest") public void goodCaseOperationSingleFile() throws Exception { addDescription("Tests the GetChecksums operation on the pillar for the successful scenario when requesting one specific file."); addStep("Set up constants and variables.", "Should not fail here!"); - final String FILE_ID = DEFAULT_FILE_ID + testMethodName; + final String FILE_ID = defaultFileId + testMethodName; FileIDs fileids = FileIDsUtils.getSpecificFileIDs(FILE_ID); addStep("Setup for having the file and delivering result-set", "No failure here"); doAnswer(new Answer() { @@ -167,38 +174,40 @@ public ExtractedChecksumResultSet answer(InvocationOnMock invocation) { ExtractedChecksumResultSet res = new ExtractedChecksumResultSet(); res.insertChecksumEntry(new ChecksumEntry(FILE_ID, DEFAULT_MD5_CHECKSUM, new Date())); return res; - + } }).when(model).getSingleChecksumResultSet(eq(FILE_ID), anyString(), any(), any(), any(ChecksumSpecTYPE.class)); - + addStep("Create and send the actual GetChecksums message to the pillar.", "Should be received and handled by the pillar."); GetChecksumsRequest getChecksumsRequest = msgFactory.createGetChecksumsRequest(csSpec, fileids, null); messageBus.sendMessage(getChecksumsRequest); - + addStep("Retrieve the ProgressResponse for the GetChecksums request", "The GetChecksums progress response should be sent by the pillar."); GetChecksumsProgressResponse progressResponse = clientReceiver.waitForMessage(GetChecksumsProgressResponse.class); assertEquals(progressResponse.getFileIDs(), fileids); assertEquals(progressResponse.getPillarID(), getPillarID()); assertNull(progressResponse.getResultAddress()); - + addStep("Retrieve the FinalResponse for the GetChecksums request", "The final response should say 'operation_complete', and give the requested data."); GetChecksumsFinalResponse finalResponse = clientReceiver.waitForMessage(GetChecksumsFinalResponse.class); - assertEquals(finalResponse.getResponseInfo().getResponseCode(), ResponseCode.OPERATION_COMPLETED); + assertEquals(ResponseCode.OPERATION_COMPLETED, finalResponse.getResponseInfo().getResponseCode()); assertEquals(finalResponse.getPillarID(), getPillarID()); - assertEquals(finalResponse.getResultingChecksums().getChecksumDataItems().size(), 1); + assertEquals(1, finalResponse.getResultingChecksums().getChecksumDataItems().size()); assertEquals(finalResponse.getResultingChecksums().getChecksumDataItems().get(0).getFileID(), FILE_ID); } - + @SuppressWarnings("rawtypes") - @Test( groups = {"regressiontest", "pillartest"}) + @Test + @Tag("regressiontest") + @Tag("pillartest") public void goodCaseOperationAllFiles() throws Exception { addDescription("Tests the GetChecksums operation on the pillar for the successful scenario, when requesting all files."); addStep("Set up constants and variables.", "Should not fail here!"); FileIDs fileids = FileIDsUtils.getAllFileIDs(); - + addStep("Setup for having the file and delivering result-set", "No failure here"); doAnswer(new Answer() { public String answer(InvocationOnMock invocation) { @@ -208,40 +217,42 @@ public String answer(InvocationOnMock invocation) { doAnswer(new Answer() { public ExtractedChecksumResultSet answer(InvocationOnMock invocation) { ExtractedChecksumResultSet res = new ExtractedChecksumResultSet(); - res.insertChecksumEntry(new ChecksumEntry(DEFAULT_FILE_ID, DEFAULT_MD5_CHECKSUM, new Date())); - res.insertChecksumEntry(new ChecksumEntry(NON_DEFAULT_FILE_ID, NON_DEFAULT_MD5_CHECKSUM, new Date(0))); + res.insertChecksumEntry(new ChecksumEntry(defaultFileId, DEFAULT_MD5_CHECKSUM, new Date())); + res.insertChecksumEntry(new ChecksumEntry(nonDefaultFileId, NON_DEFAULT_MD5_CHECKSUM, new Date(0))); return res; } }).when(model).getChecksumResultSet(any(), any(), any(), anyString(), any(ChecksumSpecTYPE.class)); - + addStep("Create and send the actual GetChecksums message to the pillar.", "Should be received and handled by the pillar."); GetChecksumsRequest getChecksumsRequest = msgFactory.createGetChecksumsRequest(csSpec, fileids, null); messageBus.sendMessage(getChecksumsRequest); - + addStep("Retrieve the ProgressResponse for the GetChecksums request", "The GetChecksums progress response should be sent by the pillar."); GetChecksumsProgressResponse progressResponse = clientReceiver.waitForMessage(GetChecksumsProgressResponse.class); assertEquals(progressResponse.getFileIDs(), fileids); assertEquals(progressResponse.getPillarID(), getPillarID()); assertNull(progressResponse.getResultAddress()); - + addStep("Retrieve the FinalResponse for the GetChecksums request", "The final response should say 'operation_complete', and give the requested data."); GetChecksumsFinalResponse finalResponse = clientReceiver.waitForMessage(GetChecksumsFinalResponse.class); - assertEquals(finalResponse.getResponseInfo().getResponseCode(), ResponseCode.OPERATION_COMPLETED); + assertEquals(ResponseCode.OPERATION_COMPLETED, finalResponse.getResponseInfo().getResponseCode()); assertEquals(finalResponse.getPillarID(), getPillarID()); - assertEquals(finalResponse.getResultingChecksums().getChecksumDataItems().size(), 2); + assertEquals(2, finalResponse.getResultingChecksums().getChecksumDataItems().size()); } - + @SuppressWarnings("rawtypes") - @Test( groups = {"regressiontest", "pillartest"}) + @Test + @Tag("regressiontest") + @Tag("pillartest") public void badCaseOperationNoFile() throws Exception { addDescription("Tests the GetChecksums functionality of the pillar for the failure scenario, where it does not have the file."); addStep("Set up constants and variables.", "Should not fail here!"); - final String FILE_ID = DEFAULT_FILE_ID + testMethodName; + final String FILE_ID = defaultFileId + testMethodName; FileIDs fileids = FileIDsUtils.getSpecificFileIDs(FILE_ID); - + addStep("Setup for not having the file", "Should cause the FILE_NOT_FOUND_FAILURE later."); doAnswer(new Answer() { public Boolean answer(InvocationOnMock invocation) { @@ -258,21 +269,23 @@ public String answer(InvocationOnMock invocation) { "Should be received and handled by the pillar."); GetChecksumsRequest getChecksumsRequest = msgFactory.createGetChecksumsRequest(csSpec, fileids, null); messageBus.sendMessage(getChecksumsRequest); - + // No response, since failure addStep("Retrieve the FinalResponse for the GetChecksums request", "The final response should tell about the error, and not contain the file."); GetChecksumsFinalResponse finalResponse = clientReceiver.waitForMessage(GetChecksumsFinalResponse.class); - assertEquals(finalResponse.getResponseInfo().getResponseCode(), ResponseCode.FILE_NOT_FOUND_FAILURE); + assertEquals(ResponseCode.FILE_NOT_FOUND_FAILURE, finalResponse.getResponseInfo().getResponseCode()); assertEquals(finalResponse.getPillarID(), getPillarID()); assertNull(finalResponse.getResultingChecksums()); - + alarmReceiver.checkNoMessageIsReceived(AlarmMessage.class); - assertEquals(audits.getCallsForAuditEvent(), 0, "Should not deliver audits"); + assertEquals(0, audits.getCallsForAuditEvent(), "Should not deliver audits"); } @SuppressWarnings("rawtypes") - @Test( groups = {"regressiontest", "pillartest"}) + @Test + @Tag("regressiontest") + @Tag("pillartest") public void testRestrictions() throws Exception { addDescription("Tests that the restrictions are correctly passed on to the cache."); @@ -292,7 +305,7 @@ public String answer(InvocationOnMock invocation) { doAnswer(new Answer() { public ExtractedChecksumResultSet answer(InvocationOnMock invocation) { ExtractedChecksumResultSet res = new ExtractedChecksumResultSet(); - res.insertChecksumEntry(new ChecksumEntry(DEFAULT_FILE_ID, DEFAULT_MD5_CHECKSUM, new Date())); + res.insertChecksumEntry(new ChecksumEntry(defaultFileId, DEFAULT_MD5_CHECKSUM, new Date())); return res; } }).when(model).getChecksumResultSet(eq(MIN_DATE), eq(MAX_DATE), eq(MAX_RESULTS), eq(collectionID), eq(csSpec)); @@ -312,9 +325,9 @@ public ExtractedChecksumResultSet answer(InvocationOnMock invocation) { addStep("Retrieve the FinalResponse for the GetChecksums request", "The final response should say 'operation_complete', and give the requested data."); GetChecksumsFinalResponse finalResponse = clientReceiver.waitForMessage(GetChecksumsFinalResponse.class); - assertEquals(finalResponse.getResponseInfo().getResponseCode(), ResponseCode.OPERATION_COMPLETED); + assertEquals(ResponseCode.OPERATION_COMPLETED, finalResponse.getResponseInfo().getResponseCode()); assertEquals(finalResponse.getPillarID(), getPillarID()); - assertEquals(finalResponse.getResultingChecksums().getChecksumDataItems().size(), 1); - assertEquals(finalResponse.getResultingChecksums().getChecksumDataItems().get(0).getFileID(), DEFAULT_FILE_ID); + assertEquals(1, finalResponse.getResultingChecksums().getChecksumDataItems().size()); + assertEquals(finalResponse.getResultingChecksums().getChecksumDataItems().get(0).getFileID(), defaultFileId); } } diff --git a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/messagehandling/GetFileIDsTest.java b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/messagehandling/GetFileIDsTest.java index 2d1c5e0c9..f004dcdf4 100644 --- a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/messagehandling/GetFileIDsTest.java +++ b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/messagehandling/GetFileIDsTest.java @@ -1,23 +1,23 @@ /* * #%L * Bitrepository Reference Pillar - * + * * $Id: PutFileOnReferencePillarTest.java 589 2011-12-01 15:34:42Z jolf $ * $HeadURL: https://sbforge.org/svn/bitrepository/bitrepository-reference/trunk/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/PutFileOnReferencePillarTest.java $ * %% * Copyright (C) 2010 - 2011 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% @@ -37,21 +37,23 @@ import org.bitrepository.pillar.MockedPillarTest; import org.bitrepository.pillar.messagefactories.GetFileIDsMessageFactory; import org.bitrepository.pillar.store.checksumdatabase.ExtractedFileIDsResultSet; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; -import org.testng.annotations.Test; import javax.xml.datatype.XMLGregorianCalendar; import java.util.Date; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.isNull; import static org.mockito.Mockito.doAnswer; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertNull; + /** * Tests the PutFile functionality on the ReferencePillar. @@ -67,14 +69,16 @@ public void initializeCUT() { } @SuppressWarnings("rawtypes") - @Test( groups = {"regressiontest", "pillartest"}) + @Test + @Tag("regressiontest") + @Tag("pillartest") public void goodCaseIdentification() throws Exception { addDescription("Tests the identification for a GetFileIDs operation on the pillar for the successful scenario."); addStep("Set up constants and variables.", "Should not fail here!"); - String FILE_ID = DEFAULT_FILE_ID + testMethodName; + String FILE_ID = defaultFileId + testMethodName; FileIDs fileids = FileIDsUtils.getSpecificFileIDs(FILE_ID); - - addStep("Setup for having the file and delivering pillar id", + + addStep("Setup for having the file and delivering pillar id", "Should return true, when requesting file-id existence."); doAnswer(new Answer() { public Boolean answer(InvocationOnMock invocation) { @@ -91,29 +95,31 @@ public String answer(InvocationOnMock invocation) { "Should be received and handled by the pillar."); IdentifyPillarsForGetFileIDsRequest identifyRequest = msgFactory.createIdentifyPillarsForGetFileIDsRequest(fileids); messageBus.sendMessage(identifyRequest); - + addStep("Retrieve and validate the response getPillarID() the pillar.", "The pillar should make a response."); IdentifyPillarsForGetFileIDsResponse receivedIdentifyResponse = clientReceiver.waitForMessage( IdentifyPillarsForGetFileIDsResponse.class); - assertEquals(receivedIdentifyResponse.getResponseInfo().getResponseCode(), - ResponseCode.IDENTIFICATION_POSITIVE); + assertEquals(ResponseCode.IDENTIFICATION_POSITIVE, + receivedIdentifyResponse.getResponseInfo().getResponseCode()); assertEquals(receivedIdentifyResponse.getPillarID(), getPillarID()); assertEquals(receivedIdentifyResponse.getFileIDs(), fileids); - + alarmReceiver.checkNoMessageIsReceived(AlarmMessage.class); - assertEquals(audits.getCallsForAuditEvent(), 0, "Should not deliver audits"); + assertEquals(0, audits.getCallsForAuditEvent(), "Should not deliver audits"); } - + @SuppressWarnings("rawtypes") - @Test( groups = {"regressiontest", "pillartest"}) + @Test + @Tag("regressiontest") + @Tag("pillartest") public void badCaseIdentification() throws Exception { addDescription("Tests the identification for a GetFileIDs operation on the pillar for the failure scenario, when the file is missing."); addStep("Set up constants and variables.", "Should not fail here!"); - String FILE_ID = DEFAULT_FILE_ID + testMethodName; + String FILE_ID = defaultFileId + testMethodName; FileIDs fileids = FileIDsUtils.getSpecificFileIDs(FILE_ID); - - addStep("Setup for delivering pillar id and not having the file ", + + addStep("Setup for delivering pillar id and not having the file ", "Should return false, when requesting file-id existence."); doAnswer(new Answer() { public Boolean answer(InvocationOnMock invocation) { @@ -135,22 +141,23 @@ public String answer(InvocationOnMock invocation) { "The pillar should make a response."); IdentifyPillarsForGetFileIDsResponse receivedIdentifyResponse = clientReceiver.waitForMessage( IdentifyPillarsForGetFileIDsResponse.class); - assertEquals(receivedIdentifyResponse.getResponseInfo().getResponseCode(), - ResponseCode.FILE_NOT_FOUND_FAILURE); + assertEquals(ResponseCode.FILE_NOT_FOUND_FAILURE, + receivedIdentifyResponse.getResponseInfo().getResponseCode()); assertEquals(receivedIdentifyResponse.getPillarID(), getPillarID()); assertEquals(receivedIdentifyResponse.getFileIDs(), fileids); - + alarmReceiver.checkNoMessageIsReceived(AlarmMessage.class); - assertEquals(audits.getCallsForAuditEvent(), 0, "Should not deliver audits"); + assertEquals(0, audits.getCallsForAuditEvent(), "Should not deliver audits"); } - + @SuppressWarnings("rawtypes") - //@Test( groups = {"regressiontest", "pillartest"}) + //@Test +// @Tag("regressiontest", "pillartest"}) // FAILS, when combined with other tests... public void goodCaseOperationSingleFile() throws Exception { addDescription("Tests the GetFileIDs operation on the pillar for the successful scenario when requesting one specific file."); addStep("Set up constants and variables.", "Should not fail here!"); - final String FILE_ID = DEFAULT_FILE_ID + testMethodName; + final String FILE_ID = defaultFileId + testMethodName; FileIDs fileids = FileIDsUtils.getSpecificFileIDs(FILE_ID); addStep("Setup for having the file and delivering result-set", "No failure here"); doAnswer(new Answer() { @@ -170,38 +177,39 @@ public ExtractedFileIDsResultSet answer(InvocationOnMock invocation) { return res; } }).when(model).getFileIDsResultSet(anyString(), any(XMLGregorianCalendar.class), any(XMLGregorianCalendar.class), anyLong(), anyString()); - + addStep("Create and send the actual GetFileIDs message to the pillar.", "Should be received and handled by the pillar."); GetFileIDsRequest getFileIDsRequest = msgFactory.createGetFileIDsRequest(fileids, null); messageBus.sendMessage(getFileIDsRequest); - + addStep("Retrieve the ProgressResponse for the GetFileIDs request", "The GetFileIDs progress response should be sent by the pillar."); GetFileIDsProgressResponse progressResponse = clientReceiver.waitForMessage(GetFileIDsProgressResponse.class); assertEquals(progressResponse.getFileIDs(), fileids); assertEquals(progressResponse.getPillarID(), getPillarID()); assertNull(progressResponse.getResultAddress()); - + addStep("Retrieve the FinalResponse for the GetFileIDs request", "The final response should say 'operation_complete', and give the requested data."); GetFileIDsFinalResponse finalResponse = clientReceiver.waitForMessage(GetFileIDsFinalResponse.class); - assertEquals(finalResponse.getResponseInfo().getResponseCode(), ResponseCode.OPERATION_COMPLETED); + assertEquals(ResponseCode.OPERATION_COMPLETED, finalResponse.getResponseInfo().getResponseCode()); assertEquals(finalResponse.getPillarID(), getPillarID()); assertEquals(finalResponse.getFileIDs().getFileID(), FILE_ID); - assertEquals(finalResponse.getResultingFileIDs().getFileIDsData().getFileIDsDataItems().getFileIDsDataItem().size(), 1); + assertEquals(1, finalResponse.getResultingFileIDs().getFileIDsData().getFileIDsDataItems().getFileIDsDataItem().size()); assertEquals(finalResponse.getResultingFileIDs().getFileIDsData().getFileIDsDataItems().getFileIDsDataItem().get(0).getFileID(), FILE_ID); } - + @SuppressWarnings("rawtypes") - //@Test( groups = {"regressiontest", "pillartest"}) + //@Test +// @Tag("regressiontest", "pillartest"}) // FAILS, when combined with other tests... public void goodCaseOperationAllFiles() throws Exception { addDescription("Tests the GetFileIDs operation on the pillar for the successful scenario, when requesting all files."); addStep("Set up constants and variables.", "Should not fail here!"); - String FILE_ID = DEFAULT_FILE_ID + testMethodName; + String FILE_ID = defaultFileId + testMethodName; FileIDs fileids = FileIDsUtils.getAllFileIDs(); - + addStep("Setup for having the file and delivering result-set", "No failure here"); doAnswer(new Answer() { public Boolean answer(InvocationOnMock invocation) { @@ -216,41 +224,43 @@ public String answer(InvocationOnMock invocation) { doAnswer(new Answer() { public ExtractedFileIDsResultSet answer(InvocationOnMock invocation) { ExtractedFileIDsResultSet res = new ExtractedFileIDsResultSet(); - res.insertFileID(DEFAULT_FILE_ID, new Date(0)); - res.insertFileID(NON_DEFAULT_FILE_ID, new Date()); + res.insertFileID(defaultFileId, new Date(0)); + res.insertFileID(nonDefaultFileId, new Date()); return res; } }).when(model).getFileIDsResultSet(isNull(), any(XMLGregorianCalendar.class), any(XMLGregorianCalendar.class), anyLong(), anyString()); - + addStep("Create and send the actual GetFileIDs message to the pillar.", "Should be received and handled by the pillar."); GetFileIDsRequest getFileIDsRequest = msgFactory.createGetFileIDsRequest(fileids, null); messageBus.sendMessage(getFileIDsRequest); - + addStep("Retrieve the ProgressResponse for the GetFileIDs request", "The GetFileIDs progress response should be sent by the pillar."); GetFileIDsProgressResponse progressResponse = clientReceiver.waitForMessage(GetFileIDsProgressResponse.class); assertEquals(progressResponse.getFileIDs(), fileids); assertEquals(progressResponse.getPillarID(), getPillarID()); assertNull(progressResponse.getResultAddress()); - + addStep("Retrieve the FinalResponse for the GetFileIDs request", "The final response should say 'operation_complete', and give the requested data."); GetFileIDsFinalResponse finalResponse = clientReceiver.waitForMessage(GetFileIDsFinalResponse.class); - assertEquals(finalResponse.getResponseInfo().getResponseCode(), ResponseCode.OPERATION_COMPLETED); + assertEquals(ResponseCode.OPERATION_COMPLETED, finalResponse.getResponseInfo().getResponseCode()); assertEquals(finalResponse.getPillarID(), getPillarID()); assertNull(finalResponse.getFileIDs().getFileID()); - assertEquals(finalResponse.getResultingFileIDs().getFileIDsData().getFileIDsDataItems().getFileIDsDataItem().size(), 2); + assertEquals(2, finalResponse.getResultingFileIDs().getFileIDsData().getFileIDsDataItems().getFileIDsDataItem().size()); } - + @SuppressWarnings("rawtypes") - @Test( groups = {"regressiontest", "pillartest"}) + @Test + @Tag("regressiontest") + @Tag("pillartest") public void badCaseOperationNoFile() throws Exception { addDescription("Tests the GetFileIDs functionality of the pillar for the failure scenario, where it does not have the file."); addStep("Set up constants and variables.", "Should not fail here!"); - String FILE_ID = DEFAULT_FILE_ID + testMethodName; + String FILE_ID = defaultFileId + testMethodName; FileIDs fileids = FileIDsUtils.getSpecificFileIDs(FILE_ID); - + addStep("Setup for not having the file", "Should cause the FILE_NOT_FOUND_FAILURE later."); doAnswer(new Answer() { public Boolean answer(InvocationOnMock invocation) { @@ -267,28 +277,29 @@ public String answer(InvocationOnMock invocation) { "Should be received and handled by the pillar."); GetFileIDsRequest getFileIDsRequest = msgFactory.createGetFileIDsRequest(fileids, null); messageBus.sendMessage(getFileIDsRequest); - + // No response, since failure addStep("Retrieve the FinalResponse for the GetFileIDs request", "The final response should tell about the error, and not contain the file."); GetFileIDsFinalResponse finalResponse = clientReceiver.waitForMessage(GetFileIDsFinalResponse.class); - assertEquals(finalResponse.getResponseInfo().getResponseCode(), ResponseCode.FILE_NOT_FOUND_FAILURE); + assertEquals(ResponseCode.FILE_NOT_FOUND_FAILURE, finalResponse.getResponseInfo().getResponseCode()); assertEquals(finalResponse.getPillarID(), getPillarID()); assertEquals(finalResponse.getFileIDs().getFileID(), FILE_ID); assertNull(finalResponse.getResultingFileIDs()); - + alarmReceiver.checkNoMessageIsReceived(AlarmMessage.class); - assertEquals(audits.getCallsForAuditEvent(), 0, "Should not deliver audits"); + assertEquals(0, audits.getCallsForAuditEvent(), "Should not deliver audits"); } @SuppressWarnings("rawtypes") - //@Test( groups = {"regressiontest", "pillartest"}) + //@Test +// @Tag("regressiontest", "pillartest"}) // FAILS, when combined with other tests... public void testRestrictions() throws Exception { addDescription("Tests that the restrictions are correctly passed on to the cache."); addStep("Set up constants and variables.", "Should not fail here!"); - final String FILE_ID = DEFAULT_FILE_ID + testMethodName; + final String FILE_ID = defaultFileId + testMethodName; FileIDs fileids = FileIDsUtils.getAllFileIDs(); final XMLGregorianCalendar MIN_DATE = CalendarUtils.getXmlGregorianCalendar(new Date(12345)); @@ -310,7 +321,7 @@ public String answer(InvocationOnMock invocation) { public ExtractedFileIDsResultSet answer(InvocationOnMock invocation) { ExtractedFileIDsResultSet res = new ExtractedFileIDsResultSet(); res.insertFileID(FILE_ID, new Date(1234567890)); - return res; + return res; } }).when(model).getFileIDsResultSet(isNull(), eq(MIN_DATE), eq(MAX_DATE), eq(MAX_RESULTS), eq(collectionID)); @@ -329,10 +340,10 @@ public ExtractedFileIDsResultSet answer(InvocationOnMock invocation) { addStep("Retrieve the FinalResponse for the GetFileIDs request", "The final response should say 'operation_complete', and give the requested data."); GetFileIDsFinalResponse finalResponse = clientReceiver.waitForMessage(GetFileIDsFinalResponse.class); - assertEquals(finalResponse.getResponseInfo().getResponseCode(), ResponseCode.OPERATION_COMPLETED); + assertEquals(ResponseCode.OPERATION_COMPLETED, finalResponse.getResponseInfo().getResponseCode()); assertEquals(finalResponse.getPillarID(), getPillarID()); assertNull(finalResponse.getFileIDs().getFileID()); - assertEquals(finalResponse.getResultingFileIDs().getFileIDsData().getFileIDsDataItems().getFileIDsDataItem().size(), 1); + assertEquals(1, finalResponse.getResultingFileIDs().getFileIDsData().getFileIDsDataItems().getFileIDsDataItem().size()); assertEquals(finalResponse.getResultingFileIDs().getFileIDsData().getFileIDsDataItems().getFileIDsDataItem().get(0).getFileID(), FILE_ID); } } diff --git a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/messagehandling/GetFileTest.java b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/messagehandling/GetFileTest.java index 7b511a005..f1dfa62b5 100644 --- a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/messagehandling/GetFileTest.java +++ b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/messagehandling/GetFileTest.java @@ -1,23 +1,23 @@ /* * #%L * Bitrepository Reference Pillar - * + * * $Id: PutFileOnReferencePillarTest.java 589 2011-12-01 15:34:42Z jolf $ * $HeadURL: https://sbforge.org/svn/bitrepository/bitrepository-reference/trunk/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/PutFileOnReferencePillarTest.java $ * %% * Copyright (C) 2010 - 2011 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% @@ -38,16 +38,18 @@ import org.bitrepository.service.exception.IdentifyContributorException; import org.bitrepository.service.exception.InvalidMessageException; import org.bitrepository.service.exception.RequestHandlerException; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; -import org.testng.annotations.Test; import java.io.ByteArrayInputStream; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doAnswer; -import static org.testng.Assert.assertEquals; + /** * Tests the PutFile functionality on the ReferencePillar. @@ -62,13 +64,15 @@ public void initializeCUT() { } @SuppressWarnings("rawtypes") - @Test( groups = {"regressiontest", "pillartest"}) + @Test + @Tag("regressiontest") + @Tag("pillartest") public void goodCaseIdentification() throws Exception { addDescription("Tests the identification for a GetFile operation on the pillar for the successful scenario."); addStep("Set up constants and variables.", "Should not fail here!"); - final String FILE_ID = DEFAULT_FILE_ID + testMethodName; + final String FILE_ID = defaultFileId + testMethodName; - addStep("Setup for having the file and delivering pillar id", + addStep("Setup for having the file and delivering pillar id", "Not throw an exception when calling the verifyFileExists method."); doAnswer(new Answer() { public String answer(InvocationOnMock invocation) { @@ -85,23 +89,25 @@ public String answer(InvocationOnMock invocation) { "The pillar should make a response."); IdentifyPillarsForGetFileResponse receivedIdentifyResponse = clientReceiver.waitForMessage( IdentifyPillarsForGetFileResponse.class); - assertEquals(receivedIdentifyResponse.getResponseInfo().getResponseCode(), - ResponseCode.IDENTIFICATION_POSITIVE); + assertEquals(ResponseCode.IDENTIFICATION_POSITIVE, + receivedIdentifyResponse.getResponseInfo().getResponseCode()); assertEquals(receivedIdentifyResponse.getPillarID(), getPillarID()); assertEquals(receivedIdentifyResponse.getFileID(), FILE_ID); alarmReceiver.checkNoMessageIsReceived(AlarmMessage.class); - assertEquals(audits.getCallsForAuditEvent(), 0, "Should not deliver audits"); + assertEquals(0, audits.getCallsForAuditEvent(), "Should not deliver audits"); } @SuppressWarnings("rawtypes") - @Test( groups = {"regressiontest", "pillartest"}) + @Test + @Tag("regressiontest") + @Tag("pillartest") public void badCaseIdentification() throws Exception { addDescription("Tests the identification for a GetFile operation on the checksum pillar for the failure scenario, when the file is missing."); addStep("Set up constants and variables.", "Should not fail here!"); - final String FILE_ID = DEFAULT_FILE_ID + testMethodName; + final String FILE_ID = defaultFileId + testMethodName; - addStep("Setup for throwing an exception when asked to verify file existence", + addStep("Setup for throwing an exception when asked to verify file existence", "Should cause the FILE_NOT_FOUND_FAILURE later."); doAnswer(new Answer() { public Void answer(InvocationOnMock invocation) throws RequestHandlerException { @@ -123,24 +129,25 @@ public String answer(InvocationOnMock invocation) { "The pillar should make a response."); IdentifyPillarsForGetFileResponse receivedIdentifyResponse = clientReceiver.waitForMessage( IdentifyPillarsForGetFileResponse.class); - assertEquals(receivedIdentifyResponse.getResponseInfo().getResponseCode(), - ResponseCode.FILE_NOT_FOUND_FAILURE); + assertEquals(ResponseCode.FILE_NOT_FOUND_FAILURE, + receivedIdentifyResponse.getResponseInfo().getResponseCode()); assertEquals(receivedIdentifyResponse.getPillarID(), getPillarID()); assertEquals(receivedIdentifyResponse.getFileID(), FILE_ID); alarmReceiver.checkNoMessageIsReceived(AlarmMessage.class); - assertEquals(audits.getCallsForAuditEvent(), 0, "Should not deliver audits"); + assertEquals(0, audits.getCallsForAuditEvent(), "Should not deliver audits"); } @SuppressWarnings("rawtypes") - //@Test( groups = {"regressiontest", "pillartest"}) + //@Test +// @Tag("regressiontest", "pillartest"}) // FAILS, when combined with other tests... public void badCaseOperationNoFile() throws Exception { addDescription("Tests the GetFile functionality of the pillar for the failure scenario, where it does not have the file."); addStep("Set up constants and variables.", "Should not fail here!"); - final String FILE_ID = DEFAULT_FILE_ID + testMethodName; + final String FILE_ID = defaultFileId + testMethodName; - addStep("Setup for throwing an exception when asked to verify file existence", + addStep("Setup for throwing an exception when asked to verify file existence", "Should cause the FILE_NOT_FOUND_FAILURE later."); doAnswer(new Answer() { public Void answer(InvocationOnMock invocation) throws RequestHandlerException { @@ -155,30 +162,31 @@ public String answer(InvocationOnMock invocation) { addStep("Create and send the actual GetFile message to the pillar.", "Should be received and handled by the pillar."); - GetFileRequest getFileRequest = msgFactory.createGetFileRequest(DEFAULT_DOWNLOAD_FILE_ADDRESS, FILE_ID); + GetFileRequest getFileRequest = msgFactory.createGetFileRequest(defaultDownloadFileAddress, FILE_ID); messageBus.sendMessage(getFileRequest); // No response, since failure addStep("Retrieve the FinalResponse for the GetFile request", "The final response should tell about the error, and not contain the file."); GetFileFinalResponse finalResponse = clientReceiver.waitForMessage(GetFileFinalResponse.class); - assertEquals(finalResponse.getResponseInfo().getResponseCode(), ResponseCode.FILE_NOT_FOUND_FAILURE); + assertEquals(ResponseCode.FILE_NOT_FOUND_FAILURE, finalResponse.getResponseInfo().getResponseCode()); assertEquals(finalResponse.getPillarID(), getPillarID()); assertEquals(finalResponse.getFileID(), FILE_ID); alarmReceiver.checkNoMessageIsReceived(AlarmMessage.class); - assertEquals(audits.getCallsForAuditEvent(), 0, "Should not deliver audits"); + assertEquals(0, audits.getCallsForAuditEvent(), "Should not deliver audits"); } @SuppressWarnings("rawtypes") - //@Test( groups = {"regressiontest", "pillartest"}) + //@Test +// @Tag("regressiontest", "pillartest"}) // FAILS, when combined with other tests... public void goodCaseOperation() throws Exception { addDescription("Tests the GetFile functionality of the pillar for the success scenario, where the file is uploaded."); addStep("Set up constants and variables.", "Should not fail here!"); - final String FILE_ID = DEFAULT_FILE_ID + testMethodName; + final String FILE_ID = defaultFileId + testMethodName; - addStep("Setup for having the file and delevering a mock file.", + addStep("Setup for having the file and delevering a mock file.", "Should make it possible to perform the whole operation without any exceptions."); doAnswer(new Answer() { public FileInfo answer(InvocationOnMock invocation) throws InvalidMessageException { @@ -194,7 +202,7 @@ public String answer(InvocationOnMock invocation) { addStep("Create and send the actual GetFile message to the pillar.", "Should be received and handled by the pillar."); - GetFileRequest getFileRequest = msgFactory.createGetFileRequest(DEFAULT_DOWNLOAD_FILE_ADDRESS, FILE_ID); + GetFileRequest getFileRequest = msgFactory.createGetFileRequest(defaultDownloadFileAddress, FILE_ID); messageBus.sendMessage(getFileRequest); addStep("Retrieve the ProgressResponse for the GetFile request", @@ -202,16 +210,16 @@ public String answer(InvocationOnMock invocation) { GetFileProgressResponse progressResponse = clientReceiver.waitForMessage(GetFileProgressResponse.class); assertEquals(progressResponse.getFileID(), FILE_ID); assertEquals(progressResponse.getPillarID(), getPillarID()); - assertEquals(progressResponse.getFileSize().longValue(), 0L); + assertEquals(0L, progressResponse.getFileSize().longValue()); addStep("Retrieve the FinalResponse for the GetFile request", "The final response should tell about the error, and not contain the file."); GetFileFinalResponse finalResponse = clientReceiver.waitForMessage(GetFileFinalResponse.class); - assertEquals(finalResponse.getResponseInfo().getResponseCode(), ResponseCode.OPERATION_COMPLETED); + assertEquals(ResponseCode.OPERATION_COMPLETED, finalResponse.getResponseInfo().getResponseCode()); assertEquals(finalResponse.getPillarID(), getPillarID()); assertEquals(finalResponse.getFileID(), FILE_ID); alarmReceiver.checkNoMessageIsReceived(AlarmMessage.class); - assertEquals(audits.getCallsForAuditEvent(), 1, "Should create one audit trail for the GetFile operation"); + assertEquals(1, audits.getCallsForAuditEvent(), "Should create one audit trail for the GetFile operation"); } } diff --git a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/messagehandling/PutFileTest.java b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/messagehandling/PutFileTest.java index a14b096f3..ec64381f0 100644 --- a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/messagehandling/PutFileTest.java +++ b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/messagehandling/PutFileTest.java @@ -1,23 +1,23 @@ /* * #%L * Bitrepository Reference Pillar - * + * * $Id: PutFileOnReferencePillarTest.java 589 2011-12-01 15:34:42Z jolf $ * $HeadURL: https://sbforge.org/svn/bitrepository/bitrepository-reference/trunk/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/PutFileOnReferencePillarTest.java $ * %% * Copyright (C) 2010 - 2011 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% @@ -38,18 +38,20 @@ import org.bitrepository.common.utils.CalendarUtils; import org.bitrepository.pillar.MockedPillarTest; import org.bitrepository.pillar.messagefactories.PutFileMessageFactory; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; -import org.testng.annotations.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.when; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertNotNull; -import static org.testng.Assert.assertNull; + /** * Tests the PutFile functionality on the ReferencePillar. @@ -64,15 +66,17 @@ public void initializeCUT() { msgFactory = new PutFileMessageFactory(collectionID, settingsForTestClient, getPillarID(), pillarDestinationId); } - + @SuppressWarnings("rawtypes") - @Test( groups = {"regressiontest", "pillartest"}) + @Test + @Tag("regressiontest") + @Tag("pillartest") public void goodCaseIdentification() throws Exception { addDescription("Tests the identification for a PutFile operation on the pillar for the successful scenario."); addStep("Set up constants and variables.", "Should not fail here!"); - String FILE_ID = DEFAULT_FILE_ID + testMethodName; + String FILE_ID = defaultFileId + testMethodName; - addStep("Setup for not already having the file and delivering pillar id", + addStep("Setup for not already having the file and delivering pillar id", "Should return false, when requesting file-id existence."); doAnswer(new Answer() { @Override @@ -96,23 +100,25 @@ public Object answer(InvocationOnMock invocation) throws Throwable { "The pillar should make a response."); IdentifyPillarsForPutFileResponse receivedIdentifyResponse = clientReceiver.waitForMessage( IdentifyPillarsForPutFileResponse.class); - assertEquals(receivedIdentifyResponse.getResponseInfo().getResponseCode(), - ResponseCode.IDENTIFICATION_POSITIVE); + assertEquals(ResponseCode.IDENTIFICATION_POSITIVE, + receivedIdentifyResponse.getResponseInfo().getResponseCode()); assertEquals(receivedIdentifyResponse.getPillarID(), getPillarID()); assertEquals(receivedIdentifyResponse.getFileID(), FILE_ID); alarmReceiver.checkNoMessageIsReceived(AlarmMessage.class); - assertEquals(audits.getCallsForAuditEvent(), 0, "Should not deliver audits"); + assertEquals(0, audits.getCallsForAuditEvent(), "Should not deliver audits"); } @SuppressWarnings("rawtypes") - @Test( groups = {"regressiontest", "pillartest"}) + @Test + @Tag("regressiontest") + @Tag("pillartest") public void badCaseIdentification() throws Exception { addDescription("Tests the identification for a PutFile operation on the pillar for the failure scenario, when the file already exists."); addStep("Set up constants and variables.", "Should not fail here!"); - String FILE_ID = DEFAULT_FILE_ID + testMethodName; + String FILE_ID = defaultFileId + testMethodName; - addStep("Setup for already having the file and delivering pillar id", + addStep("Setup for already having the file and delivering pillar id", "Should return true, when requesting file-id existence."); doAnswer(new Answer() { public Boolean answer(InvocationOnMock invocation) { @@ -134,23 +140,25 @@ public String answer(InvocationOnMock invocation) { "The pillar should make a response."); IdentifyPillarsForPutFileResponse receivedIdentifyResponse = clientReceiver.waitForMessage( IdentifyPillarsForPutFileResponse.class); - assertEquals(receivedIdentifyResponse.getResponseInfo().getResponseCode(), - ResponseCode.DUPLICATE_FILE_FAILURE); + assertEquals(ResponseCode.DUPLICATE_FILE_FAILURE, + receivedIdentifyResponse.getResponseInfo().getResponseCode()); assertEquals(receivedIdentifyResponse.getPillarID(), getPillarID()); assertEquals(receivedIdentifyResponse.getFileID(), FILE_ID); alarmReceiver.checkNoMessageIsReceived(AlarmMessage.class); - assertEquals(audits.getCallsForAuditEvent(), 0, "Should not deliver audits"); + assertEquals(0, audits.getCallsForAuditEvent(), "Should not deliver audits"); } @SuppressWarnings("rawtypes") - @Test( groups = {"regressiontest", "pillartest"}) + @Test + @Tag("regressiontest") + @Tag("pillartest") public void badCaseOperationFileAlreadyExists() throws Exception { addDescription("Tests the PutFile operation on the pillar for the failure scenario, when the file already exists."); addStep("Set up constants and variables.", "Should not fail here!"); - String FILE_ID = DEFAULT_FILE_ID + testMethodName; + String FILE_ID = defaultFileId + testMethodName; - addStep("Setup for already having the file and delivering pillar id", + addStep("Setup for already having the file and delivering pillar id", "Should return true, when requesting file-id existence."); doAnswer(new Answer() { public Boolean answer(InvocationOnMock invocation) { @@ -165,31 +173,33 @@ public String answer(InvocationOnMock invocation) { addStep("Create and send the identify request message.", "Should be received and handled by the pillar."); - PutFileRequest request = msgFactory.createPutFileRequest(csData, null, DEFAULT_DOWNLOAD_FILE_ADDRESS, FILE_ID, FILE_SIZE); + PutFileRequest request = msgFactory.createPutFileRequest(csData, null, defaultDownloadFileAddress, FILE_ID, FILE_SIZE); messageBus.sendMessage(request); // Does not send a progress response. - + addStep("Retrieve the FinalResponse for the PutFile request", "The final response should say 'operation_complete', and give the requested data."); PutFileFinalResponse finalResponse = clientReceiver.waitForMessage(PutFileFinalResponse.class); - assertEquals(finalResponse.getResponseInfo().getResponseCode(), ResponseCode.DUPLICATE_FILE_FAILURE); + assertEquals(ResponseCode.DUPLICATE_FILE_FAILURE, finalResponse.getResponseInfo().getResponseCode()); assertEquals(finalResponse.getPillarID(), getPillarID()); assertEquals(finalResponse.getFileID(), FILE_ID); - + alarmReceiver.checkNoMessageIsReceived(AlarmMessage.class); - assertEquals(audits.getCallsForAuditEvent(), 0, "Should not deliver audits"); + assertEquals(0, audits.getCallsForAuditEvent(), "Should not deliver audits"); } - + @SuppressWarnings("rawtypes") - @Test( groups = {"regressiontest", "pillartest"}) + @Test + @Tag("regressiontest") + @Tag("pillartest") public void badCasePutOperationNoValidationChecksum() throws Exception { addDescription("Tests the PutFile operation on the pillar for the failure scenario, when no validation checksum is given but required."); addStep("Set up constants and variables.", "Should not fail here!"); - String FILE_ID = DEFAULT_FILE_ID + testMethodName; + String FILE_ID = defaultFileId + testMethodName; settingsForCUT.getRepositorySettings().getProtocolSettings().setRequireChecksumForNewFileRequests(true); - addStep("Setup for not already having the file and delivering pillar id", + addStep("Setup for not already having the file and delivering pillar id", "Should return false, when requesting file-id existence."); doAnswer(new Answer() { public Boolean answer(InvocationOnMock invocation) { @@ -204,32 +214,33 @@ public String answer(InvocationOnMock invocation) { addStep("Create and send the identify request message.", "Should be received and handled by the pillar."); - PutFileRequest request = msgFactory.createPutFileRequest(null, null, DEFAULT_DOWNLOAD_FILE_ADDRESS, FILE_ID, FILE_SIZE); + PutFileRequest request = msgFactory.createPutFileRequest(null, null, defaultDownloadFileAddress, FILE_ID, FILE_SIZE); messageBus.sendMessage(request); addStep("Retrieve the FinalResponse for the PutFile request", "The final response should say 'operation_complete', and give the requested data."); PutFileFinalResponse finalResponse = clientReceiver.waitForMessage(PutFileFinalResponse.class); - assertEquals(finalResponse.getResponseInfo().getResponseCode(), ResponseCode.NEW_FILE_CHECKSUM_FAILURE); + assertEquals(ResponseCode.NEW_FILE_CHECKSUM_FAILURE, finalResponse.getResponseInfo().getResponseCode()); assertEquals(finalResponse.getPillarID(), getPillarID()); assertEquals(finalResponse.getFileID(), FILE_ID); - + addStep("Pillar should have sent an alarm", "Alarm contains information about the missing verification checksum"); AlarmMessage alarm = alarmReceiver.waitForMessage(AlarmMessage.class); assertEquals(alarm.getAlarm().getFileID(), FILE_ID); assertEquals(alarm.getAlarm().getAlarmRaiser(), getPillarID()); - assertEquals(alarm.getAlarm().getAlarmCode(), AlarmCode.CHECKSUM_ALARM); + assertEquals(AlarmCode.CHECKSUM_ALARM, alarm.getAlarm().getAlarmCode()); } - + @SuppressWarnings("rawtypes") - //@Test( groups = {"regressiontest", "pillartest"}) + //@Test +// @Tag("regressiontest", "pillartest"}) // FAILS, when combined with other tests... public void goodCaseOperation() throws Exception { addDescription("Tests the PutFile operation on the pillar for the success scenario."); addStep("Set up constants and variables.", "Should not fail here!"); - String FILE_ID = DEFAULT_FILE_ID + testMethodName; + String FILE_ID = defaultFileId + testMethodName; - addStep("Setup for not already having the file and delivering pillar id", + addStep("Setup for not already having the file and delivering pillar id", "Should return false, when requesting file-id existence."); doAnswer(new Answer() { public Boolean answer(InvocationOnMock invocation) { @@ -244,7 +255,7 @@ public String answer(InvocationOnMock invocation) { addStep("Create and send the identify request message.", "Should be received and handled by the pillar."); - PutFileRequest request = msgFactory.createPutFileRequest(csData, null, DEFAULT_DOWNLOAD_FILE_ADDRESS, FILE_ID, FILE_SIZE); + PutFileRequest request = msgFactory.createPutFileRequest(csData, null, defaultDownloadFileAddress, FILE_ID, FILE_SIZE); messageBus.sendMessage(request); addStep("Retrieve the ProgressResponse for the GetFileIDs request", @@ -252,29 +263,31 @@ public String answer(InvocationOnMock invocation) { PutFileProgressResponse progressResponse = clientReceiver.waitForMessage(PutFileProgressResponse.class); assertEquals(progressResponse.getFileID(), FILE_ID); assertEquals(progressResponse.getPillarID(), getPillarID()); - + addStep("Retrieve the FinalResponse for the PutFile request", "The final response should say 'operation_complete', and give the requested data."); PutFileFinalResponse finalResponse = clientReceiver.waitForMessage(PutFileFinalResponse.class); - assertEquals(finalResponse.getResponseInfo().getResponseCode(), ResponseCode.OPERATION_COMPLETED); + assertEquals(ResponseCode.OPERATION_COMPLETED, finalResponse.getResponseInfo().getResponseCode()); assertEquals(finalResponse.getPillarID(), getPillarID()); assertEquals(finalResponse.getFileID(), FILE_ID); assertNull(finalResponse.getChecksumDataForNewFile()); assertNull(finalResponse.getChecksumDataForExistingFile()); - + alarmReceiver.checkNoMessageIsReceived(AlarmMessage.class); - assertEquals(audits.getCallsForAuditEvent(), 1, "Should make 1 put-file audit trail"); + assertEquals(1, audits.getCallsForAuditEvent(), "Should make 1 put-file audit trail"); } - - + + @SuppressWarnings("rawtypes") - @Test( groups = {"regressiontest", "pillartest"}) + @Test + @Tag("regressiontest") + @Tag("pillartest") public void goodCaseOperationWithChecksumReturn() throws Exception { addDescription("Tests the PutFile operation on the pillar for the success scenario, when requesting the cheksum of the file returned."); addStep("Set up constants and variables.", "Should not fail here!"); - String FILE_ID = DEFAULT_FILE_ID + testMethodName; + String FILE_ID = defaultFileId + testMethodName; - addStep("Setup for not already having the file and delivering pillar id, and delivering an answer for the checksum request", + addStep("Setup for not already having the file and delivering pillar id, and delivering an answer for the checksum request", "Should return false, when requesting file-id existence."); when(model.hasFileID(eq(FILE_ID), anyString())).thenReturn(false); when(model.getPillarID()).thenReturn(settingsForCUT.getComponentID()); @@ -288,7 +301,7 @@ public void goodCaseOperationWithChecksumReturn() throws Exception { addStep("Create and send the identify request message.", "Should be received and handled by the pillar."); - PutFileRequest request = msgFactory.createPutFileRequest(csData, csSpec, DEFAULT_DOWNLOAD_FILE_ADDRESS, FILE_ID, FILE_SIZE); + PutFileRequest request = msgFactory.createPutFileRequest(csData, csSpec, defaultDownloadFileAddress, FILE_ID, FILE_SIZE); messageBus.sendMessage(request); addStep("Retrieve the ProgressResponse for the GetFileIDs request", @@ -296,17 +309,17 @@ public void goodCaseOperationWithChecksumReturn() throws Exception { PutFileProgressResponse progressResponse = clientReceiver.waitForMessage(PutFileProgressResponse.class); assertEquals(progressResponse.getFileID(), FILE_ID); assertEquals(progressResponse.getPillarID(), getPillarID()); - + addStep("Retrieve the FinalResponse for the PutFile request", "The final response should say 'operation_complete', and give the requested data."); PutFileFinalResponse finalResponse = clientReceiver.waitForMessage(PutFileFinalResponse.class); - assertEquals(finalResponse.getResponseInfo().getResponseCode(), ResponseCode.OPERATION_COMPLETED); + assertEquals(ResponseCode.OPERATION_COMPLETED, finalResponse.getResponseInfo().getResponseCode()); assertEquals(finalResponse.getPillarID(), getPillarID()); assertEquals(finalResponse.getFileID(), FILE_ID); assertNotNull(finalResponse.getChecksumDataForNewFile()); assertEquals(finalResponse.getChecksumDataForNewFile().getChecksumSpec(), csSpec); alarmReceiver.checkNoMessageIsReceived(AlarmMessage.class); - assertEquals(audits.getCallsForAuditEvent(), 1, "Should make 1 put-file audit trail"); + assertEquals(1, audits.getCallsForAuditEvent(), "Should make 1 put-file audit trail"); } } diff --git a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/messagehandling/ReplaceFileTest.java b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/messagehandling/ReplaceFileTest.java index fca9c2e9f..407239ccd 100644 --- a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/messagehandling/ReplaceFileTest.java +++ b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/messagehandling/ReplaceFileTest.java @@ -1,23 +1,23 @@ /* * #%L * Bitrepository Reference Pillar - * + * * $Id: ReplaceFileOnReferencePillarTest.java 589 2011-12-01 15:34:42Z jolf $ * $HeadURL: https://sbforge.org/svn/bitrepository/bitrepository-reference/trunk/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/ReplaceFileOnReferencePillarTest.java $ * %% * Copyright (C) 2010 - 2011 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% @@ -39,17 +39,19 @@ import org.bitrepository.common.utils.CalendarUtils; import org.bitrepository.pillar.MockedPillarTest; import org.bitrepository.pillar.messagefactories.ReplaceFileMessageFactory; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; -import org.testng.annotations.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doAnswer; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertNotNull; -import static org.testng.Assert.assertNull; + /** * Tests the ReplaceFile functionality on the ReferencePillar. @@ -66,13 +68,15 @@ public void initializeCUT() { } @SuppressWarnings("rawtypes") - @Test( groups = {"regressiontest", "pillartest"}) + @Test + @Tag("regressiontest") + @Tag("pillartest") public void goodCaseIdentification() { addDescription("Tests the identification for a ReplaceFile operation on the pillar for the successful scenario."); addStep("Set up constants and variables.", "Should not fail here!"); - String FILE_ID = DEFAULT_FILE_ID; + String FILE_ID = defaultFileId; - addStep("Setup for having the file and delivering pillar id", + addStep("Setup for having the file and delivering pillar id", "Should return true, when requesting file-id existence."); doAnswer(invocation -> true).when(model).hasFileID(eq(FILE_ID), anyString()); doAnswer(invocation -> settingsForCUT.getComponentID()).when(model).getPillarID(); @@ -86,23 +90,25 @@ public void goodCaseIdentification() { "The pillar should make a response."); IdentifyPillarsForReplaceFileResponse receivedIdentifyResponse = clientReceiver.waitForMessage( IdentifyPillarsForReplaceFileResponse.class); - assertEquals(receivedIdentifyResponse.getResponseInfo().getResponseCode(), - ResponseCode.IDENTIFICATION_POSITIVE); + assertEquals(ResponseCode.IDENTIFICATION_POSITIVE, + receivedIdentifyResponse.getResponseInfo().getResponseCode()); assertEquals(receivedIdentifyResponse.getPillarID(), getPillarID()); assertEquals(receivedIdentifyResponse.getFileID(), FILE_ID); alarmReceiver.checkNoMessageIsReceived(AlarmMessage.class); - assertEquals(audits.getCallsForAuditEvent(), 0, "Should not deliver audits"); + assertEquals(0, audits.getCallsForAuditEvent(), "Should not deliver audits"); } @SuppressWarnings("rawtypes") - @Test( groups = {"regressiontest", "pillartest"}) + @Test + @Tag("regressiontest") + @Tag("pillartest") public void badCaseIdentification() { addDescription("Tests the identification for a ReplaceFile operation on the pillar for the failure scenario, when the file does not exist."); addStep("Set up constants and variables.", "Should not fail here!"); - String FILE_ID = DEFAULT_FILE_ID; + String FILE_ID = defaultFileId; - addStep("Setup for not having the file and delivering pillar id", + addStep("Setup for not having the file and delivering pillar id", "Should return false, when requesting file-id existence."); doAnswer(invocation -> false).when(model).hasFileID(eq(FILE_ID), anyString()); doAnswer(invocation -> settingsForCUT.getComponentID()).when(model).getPillarID(); @@ -116,23 +122,25 @@ public void badCaseIdentification() { "The pillar should make a response."); IdentifyPillarsForReplaceFileResponse receivedIdentifyResponse = clientReceiver.waitForMessage( IdentifyPillarsForReplaceFileResponse.class); - assertEquals(receivedIdentifyResponse.getResponseInfo().getResponseCode(), - ResponseCode.FILE_NOT_FOUND_FAILURE); + assertEquals(ResponseCode.FILE_NOT_FOUND_FAILURE, + receivedIdentifyResponse.getResponseInfo().getResponseCode()); assertEquals(receivedIdentifyResponse.getPillarID(), getPillarID()); assertEquals(receivedIdentifyResponse.getFileID(), FILE_ID); alarmReceiver.checkNoMessageIsReceived(AlarmMessage.class); - assertEquals(audits.getCallsForAuditEvent(), 0, "Should not deliver audits"); + assertEquals(0, audits.getCallsForAuditEvent(), "Should not deliver audits"); } @SuppressWarnings("rawtypes") - @Test( groups = {"regressiontest", "pillartest"}) + @Test + @Tag("regressiontest") + @Tag("pillartest") public void badCaseOperationMissingFile() { addDescription("Tests the ReplaceFile operation on the pillar for the failure scenario, when the file is missing."); addStep("Set up constants and variables.", "Should not fail here!"); - String FILE_ID = DEFAULT_FILE_ID; + String FILE_ID = defaultFileId; - addStep("Setup for not having the file and delivering pillar id", + addStep("Setup for not having the file and delivering pillar id", "Should return false, when requesting file-id existence."); doAnswer(invocation -> false).when(model).hasFileID(eq(FILE_ID), anyString()); doAnswer(new Answer() { @@ -143,43 +151,45 @@ public String answer(InvocationOnMock invocation) { addStep("Create and send the identify request message.", "Should be received and handled by the pillar."); - ReplaceFileRequest request = msgFactory.createReplaceFileRequest(csData, csData, null, null, DEFAULT_DOWNLOAD_FILE_ADDRESS, FILE_ID, FILE_SIZE); + ReplaceFileRequest request = msgFactory.createReplaceFileRequest(csData, csData, null, null, defaultDownloadFileAddress, FILE_ID, FILE_SIZE); messageBus.sendMessage(request); addStep("Retrieve the FinalResponse for the ReplaceFile request", "The final response should give file not found failure."); ReplaceFileFinalResponse finalResponse = clientReceiver.waitForMessage(ReplaceFileFinalResponse.class); - assertEquals(finalResponse.getResponseInfo().getResponseCode(), ResponseCode.FILE_NOT_FOUND_FAILURE); + assertEquals(ResponseCode.FILE_NOT_FOUND_FAILURE, finalResponse.getResponseInfo().getResponseCode()); assertEquals(finalResponse.getPillarID(), getPillarID()); assertEquals(finalResponse.getFileID(), FILE_ID); alarmReceiver.checkNoMessageIsReceived(AlarmMessage.class); - assertEquals(audits.getCallsForAuditEvent(), 0, "Should not deliver audits"); + assertEquals(0, audits.getCallsForAuditEvent(), "Should not deliver audits"); } @SuppressWarnings("rawtypes") - @Test( groups = {"regressiontest", "pillartest"}) + @Test + @Tag("regressiontest") + @Tag("pillartest") public void badCaseOperationNoDestructiveChecksum() { addDescription("Tests the ReplaceFile operation on the pillar for the failure scenario, when no validation " + "checksum is given for the destructive action, but though is required."); addStep("Set up constants and variables.", "Should not fail here!"); - String FILE_ID = DEFAULT_FILE_ID; + String FILE_ID = defaultFileId; settingsForCUT.getRepositorySettings().getProtocolSettings().setRequireChecksumForDestructiveRequests(true); - addStep("Setup for having the file and delivering pillar id", + addStep("Setup for having the file and delivering pillar id", "Should return true, when requesting file-id existence."); doAnswer(invocation -> true).when(model).hasFileID(eq(FILE_ID), anyString()); doAnswer(invocation -> settingsForCUT.getComponentID()).when(model).getPillarID(); addStep("Create and send the identify request message.", "Should be received and handled by the pillar."); - ReplaceFileRequest request = msgFactory.createReplaceFileRequest(null, csData, null, null, DEFAULT_DOWNLOAD_FILE_ADDRESS, FILE_ID, FILE_SIZE); + ReplaceFileRequest request = msgFactory.createReplaceFileRequest(null, csData, null, null, defaultDownloadFileAddress, FILE_ID, FILE_SIZE); messageBus.sendMessage(request); addStep("Retrieve the FinalResponse for the ReplaceFile request", "The final response should give existing checksum failure."); ReplaceFileFinalResponse finalResponse = clientReceiver.waitForMessage(ReplaceFileFinalResponse.class); - assertEquals(finalResponse.getResponseInfo().getResponseCode(), ResponseCode.EXISTING_FILE_CHECKSUM_FAILURE); + assertEquals(ResponseCode.EXISTING_FILE_CHECKSUM_FAILURE, finalResponse.getResponseInfo().getResponseCode()); assertEquals(finalResponse.getPillarID(), getPillarID()); assertEquals(finalResponse.getFileID(), FILE_ID); @@ -187,32 +197,34 @@ public void badCaseOperationNoDestructiveChecksum() { AlarmMessage alarm = alarmReceiver.waitForMessage(AlarmMessage.class); assertEquals(alarm.getAlarm().getFileID(), FILE_ID); assertEquals(alarm.getAlarm().getAlarmRaiser(), getPillarID()); - assertEquals(alarm.getAlarm().getAlarmCode(), AlarmCode.CHECKSUM_ALARM); + assertEquals(AlarmCode.CHECKSUM_ALARM, alarm.getAlarm().getAlarmCode()); } @SuppressWarnings("rawtypes") - @Test( groups = {"regressiontest", "pillartest"}) + @Test + @Tag("regressiontest") + @Tag("pillartest") public void badCaseOperationNoValidationChecksum() { addDescription("Tests the ReplaceFile operation on the pillar for the failure scenario, when no validation " + "checksum is given for the new file, but though is required."); addStep("Set up constants and variables.", "Should not fail here!"); - String FILE_ID = DEFAULT_FILE_ID; + String FILE_ID = defaultFileId; settingsForCUT.getRepositorySettings().getProtocolSettings().setRequireChecksumForNewFileRequests(true); - addStep("Setup for having the file and delivering pillar id", + addStep("Setup for having the file and delivering pillar id", "Should return true, when requesting file-id existence."); doAnswer(invocation -> true).when(model).hasFileID(eq(FILE_ID), anyString()); doAnswer(invocation -> settingsForCUT.getComponentID()).when(model).getPillarID(); addStep("Create and send the identify request message.", "Should be received and handled by the pillar."); - ReplaceFileRequest request = msgFactory.createReplaceFileRequest(csData, null, null, null, DEFAULT_DOWNLOAD_FILE_ADDRESS, FILE_ID, FILE_SIZE); + ReplaceFileRequest request = msgFactory.createReplaceFileRequest(csData, null, null, null, defaultDownloadFileAddress, FILE_ID, FILE_SIZE); messageBus.sendMessage(request); addStep("Retrieve the FinalResponse for the ReplaceFile request", "The final response should give new file checksum failure."); ReplaceFileFinalResponse finalResponse = clientReceiver.waitForMessage(ReplaceFileFinalResponse.class); - assertEquals(finalResponse.getResponseInfo().getResponseCode(), ResponseCode.NEW_FILE_CHECKSUM_FAILURE); + assertEquals(ResponseCode.NEW_FILE_CHECKSUM_FAILURE, finalResponse.getResponseInfo().getResponseCode()); assertEquals(finalResponse.getPillarID(), getPillarID()); assertEquals(finalResponse.getFileID(), FILE_ID); @@ -220,18 +232,20 @@ public void badCaseOperationNoValidationChecksum() { AlarmMessage alarm = alarmReceiver.waitForMessage(AlarmMessage.class); assertEquals(alarm.getAlarm().getFileID(), FILE_ID); assertEquals(alarm.getAlarm().getAlarmRaiser(), getPillarID()); - assertEquals(alarm.getAlarm().getAlarmCode(), AlarmCode.CHECKSUM_ALARM); + assertEquals(AlarmCode.CHECKSUM_ALARM, alarm.getAlarm().getAlarmCode()); } @SuppressWarnings("rawtypes") - @Test( groups = {"regressiontest", "pillartest"}) + @Test + @Tag("regressiontest") + @Tag("pillartest") public void badCaseOperationWrongDestructiveChecksum() throws Exception { addDescription("Tests the ReplaceFile operation on the pillar for the failure scenario, when the checksum for " - +"the destructive action is different from the one in the cache."); + + "the destructive action is different from the one in the cache."); addStep("Set up constants and variables.", "Should not fail here!"); - String FILE_ID = DEFAULT_FILE_ID; + String FILE_ID = defaultFileId; - addStep("Setup for having the file and delivering pillar id", + addStep("Setup for having the file and delivering pillar id", "Should return true, when requesting file-id existence."); doAnswer(invocation -> true).when(model).hasFileID(eq(FILE_ID), anyString()); doAnswer(invocation -> settingsForCUT.getComponentID()).when(model).getPillarID(); @@ -239,13 +253,13 @@ public void badCaseOperationWrongDestructiveChecksum() throws Exception { addStep("Create and send the identify request message.", "Should be received and handled by the pillar."); - ReplaceFileRequest request = msgFactory.createReplaceFileRequest(csData, csData, null, null, DEFAULT_DOWNLOAD_FILE_ADDRESS, FILE_ID, FILE_SIZE); + ReplaceFileRequest request = msgFactory.createReplaceFileRequest(csData, csData, null, null, defaultDownloadFileAddress, FILE_ID, FILE_SIZE); messageBus.sendMessage(request); addStep("Retrieve the FinalResponse for the ReplaceFile request", "The final response should give existing file checksum failure."); ReplaceFileFinalResponse finalResponse = clientReceiver.waitForMessage(ReplaceFileFinalResponse.class); - assertEquals(finalResponse.getResponseInfo().getResponseCode(), ResponseCode.EXISTING_FILE_CHECKSUM_FAILURE); + assertEquals(ResponseCode.EXISTING_FILE_CHECKSUM_FAILURE, finalResponse.getResponseInfo().getResponseCode()); assertEquals(finalResponse.getPillarID(), getPillarID()); assertEquals(finalResponse.getFileID(), FILE_ID); @@ -253,17 +267,19 @@ public void badCaseOperationWrongDestructiveChecksum() throws Exception { AlarmMessage alarm = alarmReceiver.waitForMessage(AlarmMessage.class); assertEquals(alarm.getAlarm().getFileID(), FILE_ID); assertEquals(alarm.getAlarm().getAlarmRaiser(), getPillarID()); - assertEquals(alarm.getAlarm().getAlarmCode(), AlarmCode.CHECKSUM_ALARM); + assertEquals(AlarmCode.CHECKSUM_ALARM, alarm.getAlarm().getAlarmCode()); } @SuppressWarnings("rawtypes") - @Test( groups = {"regressiontest", "pillartest"}) + @Test + @Tag("regressiontest") + @Tag("pillartest") public void goodCaseOperation() throws Exception { addDescription("Tests the ReplaceFile operation on the pillar for the success scenario."); addStep("Set up constants and variables.", "Should not fail here!"); - String FILE_ID = DEFAULT_FILE_ID; + String FILE_ID = defaultFileId; - addStep("Setup for already having the file and delivering pillar id", + addStep("Setup for already having the file and delivering pillar id", "Should return true, when requesting file-id existence."); doAnswer(invocation -> true).when(model).hasFileID(eq(FILE_ID), anyString()); doAnswer(invocation -> settingsForCUT.getComponentID()).when(model).getPillarID(); @@ -271,7 +287,7 @@ public void goodCaseOperation() throws Exception { addStep("Create and send the identify request message.", "Should be received and handled by the pillar."); - ReplaceFileRequest request = msgFactory.createReplaceFileRequest(csData, csData, null, null, DEFAULT_DOWNLOAD_FILE_ADDRESS, FILE_ID, FILE_SIZE); + ReplaceFileRequest request = msgFactory.createReplaceFileRequest(csData, csData, null, null, defaultDownloadFileAddress, FILE_ID, FILE_SIZE); messageBus.sendMessage(request); addStep("Retrieve the ProgressResponse for the GetFileIDs request", @@ -283,27 +299,29 @@ public void goodCaseOperation() throws Exception { addStep("Retrieve the FinalResponse for the ReplaceFile request", "The final response should say 'operation_complete', and give the requested data."); ReplaceFileFinalResponse finalResponse = clientReceiver.waitForMessage(ReplaceFileFinalResponse.class); - assertEquals(finalResponse.getResponseInfo().getResponseCode(), ResponseCode.OPERATION_COMPLETED); + assertEquals(ResponseCode.OPERATION_COMPLETED, finalResponse.getResponseInfo().getResponseCode()); assertEquals(finalResponse.getPillarID(), getPillarID()); assertEquals(finalResponse.getFileID(), FILE_ID); assertNull(finalResponse.getChecksumDataForNewFile()); assertNull(finalResponse.getChecksumDataForExistingFile()); alarmReceiver.checkNoMessageIsReceived(AlarmMessage.class); - assertEquals(audits.getCallsForAuditEvent(), 1, "Should make 1 put-file audit trail"); + assertEquals(1, audits.getCallsForAuditEvent(), "Should make 1 put-file audit trail"); } @SuppressWarnings("rawtypes") - @Test( groups = {"regressiontest", "pillartest"}) + @Test + @Tag("regressiontest") + @Tag("pillartest") public void goodCaseOperationWithChecksumsReturn() throws Exception { addDescription("Tests the ReplaceFile operation on the pillar for the success scenario, when requesting both the cheksums of the file returned."); addStep("Set up constants and variables.", "Should not fail here!"); - String FILE_ID = DEFAULT_FILE_ID; + String FILE_ID = defaultFileId; ChecksumSpecTYPE existingRequestChecksumSpec = otherCsSpec; ChecksumSpecTYPE newRequestChecksumSpec = csSpec; - addStep("Setup for already having the file and delivering pillar id", + addStep("Setup for already having the file and delivering pillar id", "Should return true, when requesting file-id existence."); doAnswer(invocation -> true).when(model).hasFileID(eq(FILE_ID), anyString()); doAnswer(invocation -> settingsForCUT.getComponentID()).when(model).getPillarID(); @@ -329,7 +347,7 @@ public void goodCaseOperationWithChecksumsReturn() throws Exception { addStep("Create and send the identify request message.", "Should be received and handled by the pillar."); - ReplaceFileRequest request = msgFactory.createReplaceFileRequest(csData, csData, existingRequestChecksumSpec, newRequestChecksumSpec, DEFAULT_DOWNLOAD_FILE_ADDRESS, FILE_ID, FILE_SIZE); + ReplaceFileRequest request = msgFactory.createReplaceFileRequest(csData, csData, existingRequestChecksumSpec, newRequestChecksumSpec, defaultDownloadFileAddress, FILE_ID, FILE_SIZE); messageBus.sendMessage(request); addStep("Retrieve the ProgressResponse for the GetFileIDs request", @@ -341,7 +359,7 @@ public void goodCaseOperationWithChecksumsReturn() throws Exception { addStep("Retrieve the FinalResponse for the ReplaceFile request", "The final response should say 'operation_complete', and give the requested data."); ReplaceFileFinalResponse finalResponse = clientReceiver.waitForMessage(ReplaceFileFinalResponse.class); - assertEquals(finalResponse.getResponseInfo().getResponseCode(), ResponseCode.OPERATION_COMPLETED); + assertEquals(ResponseCode.OPERATION_COMPLETED, finalResponse.getResponseInfo().getResponseCode()); assertEquals(finalResponse.getPillarID(), getPillarID()); assertEquals(finalResponse.getFileID(), FILE_ID); assertNotNull(finalResponse.getChecksumDataForNewFile()); @@ -350,6 +368,6 @@ public void goodCaseOperationWithChecksumsReturn() throws Exception { assertEquals(finalResponse.getChecksumDataForExistingFile().getChecksumSpec(), existingRequestChecksumSpec); alarmReceiver.checkNoMessageIsReceived(AlarmMessage.class); - assertEquals(audits.getCallsForAuditEvent(), 1, "Should make 1 put-file audit trail"); + assertEquals(1, audits.getCallsForAuditEvent(), "Should make 1 put-file audit trail"); } } diff --git a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/schedulablejobs/RecalculateChecksumWorkflowTest.java b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/schedulablejobs/RecalculateChecksumWorkflowTest.java index c9c76bfbf..f37330af5 100644 --- a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/schedulablejobs/RecalculateChecksumWorkflowTest.java +++ b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/schedulablejobs/RecalculateChecksumWorkflowTest.java @@ -6,16 +6,16 @@ * Copyright (C) 2010 - 2012 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% @@ -23,9 +23,10 @@ import org.bitrepository.pillar.DefaultPillarTest; import org.bitrepository.service.workflow.SchedulableJob; -import org.testng.Assert; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; import javax.xml.datatype.DatatypeConfigurationException; import javax.xml.datatype.DatatypeFactory; @@ -35,52 +36,56 @@ public class RecalculateChecksumWorkflowTest extends DefaultPillarTest { DatatypeFactory factory; - @BeforeMethod(alwaysRun = true) + @BeforeEach public void setUpFactory() throws DatatypeConfigurationException { factory = DatatypeFactory.newInstance(); } - @Test( groups = {"regressiontest", "pillartest"}) + @Test + @Tag("regressiontest") + @Tag("pillartest") public void testWorkflowRecalculatesChecksum() throws Exception { addDescription("Test that the workflow recalculates the workflows, when the maximum age has been met."); - Date beforeWorkflowDate = csCache.getCalculationDate(DEFAULT_FILE_ID, collectionID); - Assert.assertEquals(csCache.getAllFileIDs(collectionID).size(), 1); - Assert.assertEquals(archives.getAllFileIds(collectionID).size(), 1); + Date beforeWorkflowDate = csCache.getCalculationDate(defaultFileId, collectionID); + Assertions.assertEquals(1, csCache.getAllFileIDs(collectionID).size()); + Assertions.assertEquals(1, archives.getAllFileIds(collectionID).size()); settingsForCUT.getReferenceSettings().getPillarSettings().setMaxAgeForChecksums(factory.newDuration(0)); - - synchronized(this) { + + synchronized (this) { wait(100); } - + addStep("Create and run workflow", "The checksum"); SchedulableJob workflow = new RecalculateChecksumJob(collectionID, model); workflow.start(); - Date afterWorkflowDate = csCache.getCalculationDate(DEFAULT_FILE_ID, collectionID); - - Assert.assertTrue(beforeWorkflowDate.getTime() < afterWorkflowDate.getTime(), - beforeWorkflowDate.getTime() + " < "+ afterWorkflowDate.getTime()); + Date afterWorkflowDate = csCache.getCalculationDate(defaultFileId, collectionID); + + Assertions.assertTrue(beforeWorkflowDate.getTime() < afterWorkflowDate.getTime(), + beforeWorkflowDate.getTime() + " < " + afterWorkflowDate.getTime()); } - - @Test( groups = {"regressiontest", "pillartest"}) + + @Test + @Tag("regressiontest") + @Tag("pillartest") public void testWorkflowDoesNotRecalculateWhenNotNeeded() throws Exception { addDescription("Test that the workflow does not recalculates the workflows, when the maximum age has " + "not yet been met."); - Date beforeWorkflowDate = csCache.getCalculationDate(DEFAULT_FILE_ID, collectionID); - Assert.assertEquals(csCache.getAllFileIDs(collectionID).size(), 1); - Assert.assertEquals(archives.getAllFileIds(collectionID).size(), 1); + Date beforeWorkflowDate = csCache.getCalculationDate(defaultFileId, collectionID); + Assertions.assertEquals(1, csCache.getAllFileIDs(collectionID).size()); + Assertions.assertEquals(1, archives.getAllFileIds(collectionID).size()); settingsForCUT.getReferenceSettings().getPillarSettings() .setMaxAgeForChecksums(factory.newDuration(Long.MAX_VALUE)); - - synchronized(this) { + + synchronized (this) { wait(100); } - + addStep("Create and run workflow", "The checksum"); SchedulableJob workflow = new RecalculateChecksumJob(collectionID, model); workflow.start(); - Date afterWorkflowDate = csCache.getCalculationDate(DEFAULT_FILE_ID, collectionID); - - Assert.assertEquals(beforeWorkflowDate.getTime(), afterWorkflowDate.getTime(), - beforeWorkflowDate.getTime() + " == "+ afterWorkflowDate.getTime()); + Date afterWorkflowDate = csCache.getCalculationDate(defaultFileId, collectionID); + + Assertions.assertEquals(beforeWorkflowDate.getTime(), afterWorkflowDate.getTime(), + beforeWorkflowDate.getTime() + " == " + afterWorkflowDate.getTime()); } } diff --git a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/store/ChecksumPillarModelTest.java b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/store/ChecksumPillarModelTest.java index 14ff080f2..0ceb244d8 100644 --- a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/store/ChecksumPillarModelTest.java +++ b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/store/ChecksumPillarModelTest.java @@ -8,12 +8,12 @@ * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * + * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . @@ -29,15 +29,17 @@ import org.bitrepository.pillar.store.checksumdatabase.ChecksumStore; import org.bitrepository.service.AlarmDispatcher; import org.bitrepository.settings.referencesettings.ChecksumPillarFileDownload; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; import java.util.Date; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertNotNull; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + public class ChecksumPillarModelTest extends DefaultFixturePillarTest { ChecksumStorageModel pillarModel; @@ -45,7 +47,7 @@ public class ChecksumPillarModelTest extends DefaultFixturePillarTest { protected AlarmDispatcher alarmDispatcher; ChecksumSpecTYPE defaultCsType; ChecksumSpecTYPE nonDefaultCsType; - + protected static final String EMPTY_MD5_CHECKSUM = "d41d8cd98f00b204e9800998ecf8427e"; @Override @@ -53,67 +55,71 @@ protected void initializeCUT() { cache = new MemoryCacheMock(); alarmDispatcher = new AlarmDispatcher(settingsForCUT, messageBus); pillarModel = new ChecksumStorageModel(cache, alarmDispatcher, settingsForCUT); - + defaultCsType = ChecksumUtils.getDefault(settingsForCUT); - + nonDefaultCsType = new ChecksumSpecTYPE(); nonDefaultCsType.setChecksumType(ChecksumType.HMAC_SHA384); nonDefaultCsType.setChecksumSalt(new byte[]{'a', 'z'}); } - - @Test( groups = {"regressiontest", "pillartest"}) + + @Test + @Tag("regressiontest") + @Tag("pillartest") public void testPillarModelBasicFunctionality() { addDescription("Test the basic functions of the full reference pillar model."); addStep("Check the pillar id in the pillar model", "Identical to the one from the test."); assertEquals(pillarModel.getPillarID(), getPillarID()); - - addStep("Ask whether it can handle a file of size 0", + + addStep("Ask whether it can handle a file of size 0", "Should not throw an exception"); pillarModel.verifyEnoughFreeSpaceLeftForFile(0L, collectionID); - + addStep("Ask whether it can handle a file of maximum size", "Should not be a problem for the checksum pillar."); pillarModel.verifyEnoughFreeSpaceLeftForFile(Long.MAX_VALUE, collectionID); - - addStep("Check the ChecksumPillarSpec", + + addStep("Check the ChecksumPillarSpec", "Must be the default checksum spec from settings"); assertEquals(pillarModel.getChecksumPillarSpec(), defaultCsType); - - addStep("Checkum whether the checksum pillar should download", + + addStep("Checkum whether the checksum pillar should download", "It should say as it is in settings, or return default"); settingsForCUT.getReferenceSettings().getPillarSettings().setChecksumPillarFileDownload( ChecksumPillarFileDownload.ALWAYS_DOWNLOAD); - assertEquals(pillarModel.getChecksumPillarFileDownload(), - ChecksumPillarFileDownload.ALWAYS_DOWNLOAD); + assertEquals(ChecksumPillarFileDownload.ALWAYS_DOWNLOAD, + pillarModel.getChecksumPillarFileDownload()); settingsForCUT.getReferenceSettings().getPillarSettings().setChecksumPillarFileDownload( ChecksumPillarFileDownload.NEVER_DOWNLOAD); - assertEquals(pillarModel.getChecksumPillarFileDownload(), - ChecksumPillarFileDownload.NEVER_DOWNLOAD); + assertEquals(ChecksumPillarFileDownload.NEVER_DOWNLOAD, + pillarModel.getChecksumPillarFileDownload()); settingsForCUT.getReferenceSettings().getPillarSettings().setChecksumPillarFileDownload(null); - assertEquals(pillarModel.getChecksumPillarFileDownload(), - ChecksumPillarFileDownload.DOWNLOAD_WHEN_MISSING_FROM_MESSAGE); + assertEquals(ChecksumPillarFileDownload.DOWNLOAD_WHEN_MISSING_FROM_MESSAGE, + pillarModel.getChecksumPillarFileDownload()); } - - @Test( groups = {"regressiontest", "pillartest"}) + + @Test + @Tag("regressiontest") + @Tag("pillartest") public void testPillarModelHasFile() throws Exception { addDescription("Test that the file exists, when placed in the archive and cache"); addStep("Setup", "Should place the 'existing file' in the directory."); initializeWithDefaultFile(); - - addStep("Check whether file exists and retrieve it.", + + addStep("Check whether file exists and retrieve it.", "Should have the file ID, but throw an exception when asked for the actual file."); - assertTrue(pillarModel.hasFileID(DEFAULT_FILE_ID, collectionID)); + assertTrue(pillarModel.hasFileID(defaultFileId, collectionID)); try { - pillarModel.getFileInfoForActualFile(DEFAULT_FILE_ID, collectionID); + pillarModel.getFileInfoForActualFile(defaultFileId, collectionID); fail("Must throw an exception here!"); } catch (Exception e) { // expected } - + addStep("Check whether file exists.", "Should not exist."); try { - pillarModel.verifyFileExists(DEFAULT_FILE_ID, collectionID); + pillarModel.verifyFileExists(defaultFileId, collectionID); fail("Must throw an exception here"); } catch (Exception e) { // expected @@ -121,9 +127,9 @@ public void testPillarModelHasFile() throws Exception { addStep("Ask for the checksum data for the file with different checksum specs", "Should fail, unless asked for the default checksum spec."); - assertNotNull(pillarModel.getChecksumDataForFile(DEFAULT_FILE_ID, collectionID, defaultCsType)); + assertNotNull(pillarModel.getChecksumDataForFile(defaultFileId, collectionID, defaultCsType)); try { - pillarModel.getChecksumDataForFile(DEFAULT_FILE_ID, collectionID, nonDefaultCsType); + pillarModel.getChecksumDataForFile(defaultFileId, collectionID, nonDefaultCsType); fail("Must throw an exception here"); } catch (Exception e) { // expected @@ -131,25 +137,25 @@ public void testPillarModelHasFile() throws Exception { addStep("Ask for the checksum entry for the file with different checksum specs", "Should fail, unless asked for the default checksum spec."); - assertNotNull(pillarModel.getChecksumEntryForFile(DEFAULT_FILE_ID, collectionID, defaultCsType)); + assertNotNull(pillarModel.getChecksumEntryForFile(defaultFileId, collectionID, defaultCsType)); try { - pillarModel.getChecksumEntryForFile(DEFAULT_FILE_ID, collectionID, nonDefaultCsType); + pillarModel.getChecksumEntryForFile(defaultFileId, collectionID, nonDefaultCsType); fail("Must throw an exception here"); } catch (Exception e) { // expected } - + addStep("Ask for the checksum for the file with different checksum specs", "Should fail, unless asked for the default checksum spec."); - assertNotNull(pillarModel.getChecksumForFile(DEFAULT_FILE_ID, collectionID, defaultCsType)); + assertNotNull(pillarModel.getChecksumForFile(defaultFileId, collectionID, defaultCsType)); try { - pillarModel.getChecksumForFile(DEFAULT_FILE_ID, collectionID, nonDefaultCsType); + pillarModel.getChecksumForFile(defaultFileId, collectionID, nonDefaultCsType); fail("Must throw an exception here"); } catch (Exception e) { // expected } - - addStep("Check extraction of checksum result set", + + addStep("Check extraction of checksum result set", "Should deliver non-null object when called with default checksum spec, otherwise throw exception."); assertNotNull(pillarModel.getChecksumResultSet(null, null, null, collectionID, defaultCsType)); try { @@ -158,10 +164,10 @@ public void testPillarModelHasFile() throws Exception { } catch (Exception e) { // exptected } - + addStep("Check retrieval of non-default checksum", ""); try { - pillarModel.getNonDefaultChecksum(DEFAULT_FILE_ID, collectionID, defaultCsType); + pillarModel.getNonDefaultChecksum(defaultFileId, collectionID, defaultCsType); fail("Must throw an exception here"); } catch (Exception e) { // expected @@ -177,40 +183,42 @@ public void testPillarModelHasFile() throws Exception { addStep("Test retrieval of single checksum result set", "Should return non-null object, unless asked for non-default checksum spec which must raise exception."); - pillarModel.getSingleChecksumResultSet(DEFAULT_FILE_ID, collectionID, null, null, defaultCsType); + pillarModel.getSingleChecksumResultSet(defaultFileId, collectionID, null, null, defaultCsType); try { - pillarModel.getSingleChecksumResultSet(DEFAULT_FILE_ID, collectionID, null, null, nonDefaultCsType); + pillarModel.getSingleChecksumResultSet(defaultFileId, collectionID, null, null, nonDefaultCsType); fail("Must throw an exception here"); } catch (Exception e) { // expected } } - - @Test( groups = {"regressiontest", "pillartest"}) + + @Test + @Tag("regressiontest") + @Tag("pillartest") public void testPillarModelNoFile() { addDescription("Test that the file exists, when placed in the archive and cache"); addStep("Setup", "Should place the 'existing file' in the directory."); - - addStep("Check whether file exists and try to retrieve it.", + + addStep("Check whether file exists and try to retrieve it.", "Should say no, and throw exception when attempted to be retrieved."); - assertFalse(pillarModel.hasFileID(DEFAULT_FILE_ID, collectionID)); + assertFalse(pillarModel.hasFileID(defaultFileId, collectionID)); try { - pillarModel.getFileInfoForActualFile(DEFAULT_FILE_ID, collectionID); + pillarModel.getFileInfoForActualFile(defaultFileId, collectionID); fail("Must throw an exception, when asked for a file it does not have."); } catch (Exception e) { // expected } - + addStep("Verify that anexceptions are thrown when verifying file existance.", "Should not exist."); try { - pillarModel.verifyFileExists(DEFAULT_FILE_ID, collectionID); + pillarModel.verifyFileExists(defaultFileId, collectionID); fail("Must throw an exception here!"); } catch (Exception e) { // expected } } - + private void initializeWithDefaultFile() { - cache.insertChecksumCalculation(DEFAULT_FILE_ID, collectionID, EMPTY_MD5_CHECKSUM, new Date()); + cache.insertChecksumCalculation(defaultFileId, collectionID, EMPTY_MD5_CHECKSUM, new Date()); } } diff --git a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/store/FullPillarModelTest.java b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/store/FullPillarModelTest.java index 206293b33..19495facc 100644 --- a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/store/FullPillarModelTest.java +++ b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/store/FullPillarModelTest.java @@ -8,12 +8,12 @@ * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * + * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . @@ -32,16 +32,17 @@ import org.bitrepository.pillar.store.filearchive.CollectionArchiveManager; import org.bitrepository.service.AlarmDispatcher; import org.bitrepository.service.exception.RequestHandlerException; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; import java.io.ByteArrayInputStream; import java.io.IOException; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertNull; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; public class FullPillarModelTest extends DefaultFixturePillarTest { FileStorageModel pillarModel; @@ -50,7 +51,7 @@ public class FullPillarModelTest extends DefaultFixturePillarTest { protected AlarmDispatcher alarmDispatcher; ChecksumSpecTYPE defaultCsType; ChecksumSpecTYPE nonDefaultCsType; - + protected static final String EMPTY_HMAC_SHA385_CHECKSUM = "3e7012b39d4f6c503b2a4846fff3f4d0d61fb1a58b81035765f283cfa5f1b93e57ded9e0a946447ff24e5c9be39c8573"; protected static final String EMPTY_MD5_CHECKSUM = "d41d8cd98f00b204e9800998ecf8427e"; @@ -60,24 +61,26 @@ protected void initializeCUT() { archives = new CollectionArchiveManager(settingsForCUT); alarmDispatcher = new AlarmDispatcher(settingsForCUT, messageBus); pillarModel = new FileStorageModel(archives, cache, alarmDispatcher, settingsForCUT); - + defaultCsType = ChecksumUtils.getDefault(settingsForCUT); - + nonDefaultCsType = new ChecksumSpecTYPE(); nonDefaultCsType.setChecksumType(ChecksumType.HMAC_SHA384); nonDefaultCsType.setChecksumSalt(new byte[]{'a', 'z'}); } - - @Test( groups = {"regressiontest", "pillartest"}) + + @Test + @Tag("regressiontest") + @Tag("pillartest") public void testPillarModelBasicFunctionality() throws Exception { addDescription("Test the basic functions of the full reference pillar model."); addStep("Check the pillar id in the pillar model", "Identical to the one from the test."); assertEquals(pillarModel.getPillarID(), getPillarID()); - - addStep("Ask whether it can handle a file of size 0", + + addStep("Ask whether it can handle a file of size 0", "Should not throw an exception"); pillarModel.verifyEnoughFreeSpaceLeftForFile(0L, collectionID); - + addStep("Ask whether it can handle a file of maximum size", "Should throw an exception"); try { @@ -86,71 +89,75 @@ public void testPillarModelBasicFunctionality() throws Exception { } catch (RequestHandlerException e) { // expected. } - - addStep("Check the ChecksumPillarSpec", + + addStep("Check the ChecksumPillarSpec", "Must be null, since it is full reference pillar and not a checksums pillar"); assertNull(pillarModel.getChecksumPillarSpec()); } - - @Test( groups = {"regressiontest", "pillartest"}) + + @Test + @Tag("regressiontest") + @Tag("pillartest") public void testPillarModelHasFile() throws Exception { addDescription("Test that the file exists, when placed in the archive and cache"); addStep("Setup", "Should place the 'existing file' in the directory."); initializeWithDefaultFile(); - + addStep("Check whether file exists and retrieve it.", "Should be the empty file."); - assertTrue(pillarModel.hasFileID(DEFAULT_FILE_ID, collectionID)); - FileInfo fileInfo = pillarModel.getFileInfoForActualFile(DEFAULT_FILE_ID, collectionID); - assertEquals(fileInfo.getSize(), 0L); - assertEquals(fileInfo.getFileID(), DEFAULT_FILE_ID); - + assertTrue(pillarModel.hasFileID(defaultFileId, collectionID)); + FileInfo fileInfo = pillarModel.getFileInfoForActualFile(defaultFileId, collectionID); + assertEquals(0L, fileInfo.getSize()); + assertEquals(fileInfo.getFileID(), defaultFileId); + addStep("Verify that no exceptions are thrown when verifying file existance.", "Should exist."); - pillarModel.verifyFileExists(DEFAULT_FILE_ID, collectionID); - + pillarModel.verifyFileExists(defaultFileId, collectionID); + addStep("Check retrieval of non-default checksum", ""); - String md5Checksum = pillarModel.getNonDefaultChecksum(DEFAULT_FILE_ID, collectionID, defaultCsType); - assertEquals(EMPTY_MD5_CHECKSUM, md5Checksum); - String otherChecksum = pillarModel.getNonDefaultChecksum(DEFAULT_FILE_ID, collectionID, nonDefaultCsType); + String md5Checksum = pillarModel.getNonDefaultChecksum(defaultFileId, collectionID, defaultCsType); + assertEquals(EMPTY_MD5_CHECKSUM, md5Checksum); + String otherChecksum = pillarModel.getNonDefaultChecksum(defaultFileId, collectionID, nonDefaultCsType); assertEquals(EMPTY_HMAC_SHA385_CHECKSUM, otherChecksum); } - - @Test( groups = {"regressiontest", "pillartest"}) + + @Test + @Tag("regressiontest") + @Tag("pillartest") public void testPillarModelNoFile() throws Exception { addDescription("Test that the file exists, when placed in the archive and cache"); addStep("Setup", "Should place the 'existing file' in the directory."); emptyArchive(); - - addStep("Check whether file exists and try to retrieve it.", + + addStep("Check whether file exists and try to retrieve it.", "Should say no, and throw exception when attempted to be retrieved."); - assertFalse(pillarModel.hasFileID(DEFAULT_FILE_ID, collectionID)); + assertFalse(pillarModel.hasFileID(defaultFileId, collectionID)); try { - pillarModel.getFileInfoForActualFile(DEFAULT_FILE_ID, collectionID); + pillarModel.getFileInfoForActualFile(defaultFileId, collectionID); fail("Must throw an exception, when asked for a file it does not have."); } catch (Exception e) { // expected } - + addStep("Verify that anexceptions are thrown when verifying file existance.", "Should not exist."); try { - pillarModel.verifyFileExists(DEFAULT_FILE_ID, collectionID); + pillarModel.verifyFileExists(defaultFileId, collectionID); fail("Must throw an exception here!"); } catch (Exception e) { // expected } } - + private void emptyArchive() { - if (archives.hasFile(DEFAULT_FILE_ID, collectionID)) { - archives.deleteFile(DEFAULT_FILE_ID, collectionID); + if (archives.hasFile(defaultFileId, collectionID)) { + archives.deleteFile(defaultFileId, collectionID); } - archives.ensureFileNotInTmpDir(DEFAULT_FILE_ID, collectionID); + archives.ensureFileNotInTmpDir(defaultFileId, collectionID); } - + private void initializeWithDefaultFile() throws IOException { emptyArchive(); - - archives.downloadFileForValidation(DEFAULT_FILE_ID, collectionID, new ByteArrayInputStream(new byte[0])); - archives.moveToArchive(DEFAULT_FILE_ID, collectionID); - pillarModel.recalculateChecksum(DEFAULT_FILE_ID, collectionID); + + archives.downloadFileForValidation(defaultFileId, collectionID, new ByteArrayInputStream(new byte[0])); + archives.moveToArchive(defaultFileId, collectionID); + pillarModel.recalculateChecksum(defaultFileId, collectionID); } } diff --git a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/store/PillarSettingsProviderTest.java b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/store/PillarSettingsProviderTest.java index 0ca34e496..e540645d5 100644 --- a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/store/PillarSettingsProviderTest.java +++ b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/store/PillarSettingsProviderTest.java @@ -25,20 +25,23 @@ import org.bitrepository.common.settings.SettingsProvider; import org.bitrepository.common.settings.XMLFileSettingsLoader; import org.bitrepository.pillar.PillarSettingsProvider; -import org.testng.Assert; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + public class PillarSettingsProviderTest { private static final String PATH_TO_TEST_SETTINGS = "settings/xml/bitrepository-devel"; - @Test(groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public void componentIDTest() { SettingsProvider settingsLoader = new PillarSettingsProvider(new XMLFileSettingsLoader(PATH_TO_TEST_SETTINGS), null); Settings settings = settingsLoader.getSettings(); - Assert.assertEquals( + Assertions.assertEquals( settings.getReferenceSettings().getPillarSettings().getPillarID(), settings.getComponentID()); String componentID = "testPillarID"; @@ -46,7 +49,7 @@ public void componentIDTest() { new PillarSettingsProvider(new XMLFileSettingsLoader(PATH_TO_TEST_SETTINGS), "testPillarID"); settings = settingsLoader.getSettings(); - Assert.assertEquals( + Assertions.assertEquals( componentID, settings.getComponentID()); } } diff --git a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/store/archive/ArchiveDirectoryTest.java b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/store/archive/ArchiveDirectoryTest.java index 97d62b8ea..e580a9eed 100644 --- a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/store/archive/ArchiveDirectoryTest.java +++ b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/store/archive/ArchiveDirectoryTest.java @@ -25,27 +25,27 @@ import org.bitrepository.common.utils.TestFileHelper; import org.bitrepository.pillar.store.filearchive.ArchiveDirectory; import org.jaccept.structure.ExtendedTestCase; -import org.testng.Assert; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; import java.io.File; import java.io.FileOutputStream; import java.io.OutputStreamWriter; import java.nio.charset.StandardCharsets; -import java.util.Arrays; import java.util.Collections; import java.util.List; public class ArchiveDirectoryTest extends ExtendedTestCase { - private static String DIR_NAME = "archive-directory"; - private static String FILE_DIR_NAME = DIR_NAME + "/fileDir"; - private static String FOLDER_DIR_NAME = DIR_NAME + "/" + ArchiveDirectory.FOLDER_DIR; + private static final String DIR_NAME = "archive-directory"; + private static final String FILE_DIR_NAME = DIR_NAME + "/fileDir"; + private static final String FOLDER_DIR_NAME = DIR_NAME + "/" + ArchiveDirectory.FOLDER_DIR; - private static String FILE_ID = "file1"; - private static String FOLDER_FILE_ID = "folder1/folder2/file1"; + private static final String FILE_ID = "file1"; + private static final String FOLDER_FILE_ID = "folder1/folder2/file1"; - @AfterMethod (alwaysRun=true) + @AfterEach public void shutdownTests() throws Exception { File dir = new File(DIR_NAME); if(dir.exists()) { @@ -53,7 +53,9 @@ public void shutdownTests() throws Exception { } } - @Test( groups = {"regressiontest", "pillartest"}) + @Test + @Tag("regressiontest") + @Tag("pillartest") public void testArchiveDirectoryExistingFile() throws Exception { addDescription("Test the ArchiveDirectory when the file exists"); addStep("Setup", "Should place the 'existing file' in the directory."); @@ -62,17 +64,19 @@ public void testArchiveDirectoryExistingFile() throws Exception { createExistingFile(); addStep("Validate the existence of the file", "Should exist and be retrievable."); - Assert.assertTrue(directory.hasFile(FILE_ID)); - Assert.assertNotNull(directory.retrieveFile(FILE_ID)); - Assert.assertEquals(directory.getFileIds(), Arrays.asList(FILE_ID)); + Assertions.assertTrue(directory.hasFile(FILE_ID)); + Assertions.assertNotNull(directory.retrieveFile(FILE_ID)); + Assertions.assertEquals(directory.getFileIds(), Collections.singletonList(FILE_ID)); addStep("Delete the file.", "Should not be extractable."); directory.removeFileFromArchive(FILE_ID); - Assert.assertFalse(directory.hasFile(FILE_ID)); - Assert.assertNull(directory.retrieveFile(FILE_ID)); + Assertions.assertFalse(directory.hasFile(FILE_ID)); + Assertions.assertNull(directory.retrieveFile(FILE_ID)); } - @Test( groups = {"regressiontest", "pillartest"}) + @Test + @Tag("regressiontest") + @Tag("pillartest") public void testArchiveDirectoryMissingFile() throws Exception { addDescription("Test the ArchiveDirectory when the file is missing."); addStep("Setup", "No file added to the directory."); @@ -80,20 +84,22 @@ public void testArchiveDirectoryMissingFile() throws Exception { ArchiveDirectory directory = new ArchiveDirectory(DIR_NAME); addStep("Validate the existence of the file", "Should exist and be retrievable."); - Assert.assertFalse(directory.hasFile(FILE_ID)); - Assert.assertNull(directory.retrieveFile(FILE_ID)); - Assert.assertEquals(directory.getFileIds(), Arrays.asList()); + Assertions.assertFalse(directory.hasFile(FILE_ID)); + Assertions.assertNull(directory.retrieveFile(FILE_ID)); + Assertions.assertEquals(directory.getFileIds(), List.of()); addStep("Delete the file.", "exception since the file does not exist."); try { directory.removeFileFromArchive(FILE_ID); - Assert.fail("Should not be possible to remove a non-existing file."); + Assertions.fail("Should not be possible to remove a non-existing file."); } catch (IllegalStateException e) { // exptected } } - @Test( groups = {"regressiontest", "pillartest"}) + @Test + @Tag("regressiontest") + @Tag("pillartest") public void testArchiveDirectoryNewFile() throws Exception { addDescription("Testing the ArchiveDirectory handling of a new file."); addStep("Setup", "No file added to the directory."); @@ -102,35 +108,37 @@ public void testArchiveDirectoryNewFile() throws Exception { addStep("Retrieve tmp file", "Exception since files does not exist."); try { directory.getFileInTempDir(FILE_ID); - Assert.fail("Should throw exception since the file does not exist."); + Assertions.fail("Should throw exception since the file does not exist."); } catch (IllegalStateException e) { // exptected } addStep("Request a new file for the tmp dir", "Should be received and creatable."); File newFile = directory.getNewFileInTempDir(FILE_ID); - Assert.assertTrue(newFile.createNewFile()); + Assertions.assertTrue(newFile.createNewFile()); addStep("Retrieve tmp file", "Should be the newly created file."); File tmpFile = directory.getFileInTempDir(FILE_ID); - Assert.assertNotNull(tmpFile); - Assert.assertEquals(tmpFile.getAbsolutePath(), newFile.getAbsolutePath()); + Assertions.assertNotNull(tmpFile); + Assertions.assertEquals(tmpFile.getAbsolutePath(), newFile.getAbsolutePath()); addStep("Request another new file with the same name", "Should throw exception, since it already exists."); try { directory.getNewFileInTempDir(FILE_ID); - Assert.fail("Should throw exception, since the file already exists."); + Assertions.fail("Should throw exception, since the file already exists."); } catch (IllegalStateException e) { // expected } addStep("Move the file from tmp to archive", "Should exist in archive but not in tmp."); directory.moveFromTmpToArchive(FILE_ID); - Assert.assertTrue(directory.hasFile(FILE_ID)); - Assert.assertFalse(directory.hasFileInTempDir(FILE_ID)); + Assertions.assertTrue(directory.hasFile(FILE_ID)); + Assertions.assertFalse(directory.hasFileInTempDir(FILE_ID)); } - @Test( groups = {"regressiontest", "pillartest"}) + @Test + @Tag("regressiontest") + @Tag("pillartest") public void testArchiveDirectoryMoveFileToArchive() throws Exception { addDescription("Testing the error scenarios when moving a file from tmp to archive for the ArchiveDirectory."); addStep("Setup", "No file added to the directory."); @@ -139,7 +147,7 @@ public void testArchiveDirectoryMoveFileToArchive() throws Exception { addStep("Moving file from tmp to archive", "Exception since it does not exist in the tmp-dir"); try { directory.moveFromTmpToArchive(FILE_ID); - Assert.fail("Should throw exception since the file does not exist."); + Assertions.fail("Should throw exception since the file does not exist."); } catch (IllegalStateException e) { // exptected } @@ -147,28 +155,30 @@ public void testArchiveDirectoryMoveFileToArchive() throws Exception { addStep("Create file in both tmp and archive.", ""); createExistingFile(); File newFile = directory.getNewFileInTempDir(FILE_ID); - Assert.assertTrue(newFile.createNewFile()); + Assertions.assertTrue(newFile.createNewFile()); addStep("Moving file from tmp to archive", "Exception since the file already exists within the archive."); try { directory.moveFromTmpToArchive(FILE_ID); - Assert.fail("Should throw exception since the file in archive already exists."); + Assertions.fail("Should throw exception since the file in archive already exists."); } catch (IllegalStateException e) { // exptected } addStep("Remove the file from archive and try again", "File in tmp moved to archive."); - Assert.assertTrue(directory.hasFile(FILE_ID)); - Assert.assertTrue(directory.hasFileInTempDir(FILE_ID)); + Assertions.assertTrue(directory.hasFile(FILE_ID)); + Assertions.assertTrue(directory.hasFileInTempDir(FILE_ID)); directory.removeFileFromArchive(FILE_ID); - Assert.assertFalse(directory.hasFile(FILE_ID)); - Assert.assertTrue(directory.hasFileInTempDir(FILE_ID)); + Assertions.assertFalse(directory.hasFile(FILE_ID)); + Assertions.assertTrue(directory.hasFileInTempDir(FILE_ID)); directory.moveFromTmpToArchive(FILE_ID); - Assert.assertTrue(directory.hasFile(FILE_ID)); - Assert.assertFalse(directory.hasFileInTempDir(FILE_ID)); + Assertions.assertTrue(directory.hasFile(FILE_ID)); + Assertions.assertFalse(directory.hasFileInTempDir(FILE_ID)); } - @Test( groups = {"regressiontest", "pillartest"}) + @Test + @Tag("regressiontest") + @Tag("pillartest") public void testArchiveDirectoryRemoveFile() throws Exception { addDescription("Testing the error scenarios when removing files from the archive."); addStep("Setup", "No file added to the directory."); @@ -178,7 +188,7 @@ public void testArchiveDirectoryRemoveFile() throws Exception { addStep("Remove nonexisting file from archive", "Exception since it does not exist"); try { directory.removeFileFromArchive(FILE_ID); - Assert.fail("Should throw exception since the file does not exist."); + Assertions.fail("Should throw exception since the file does not exist."); } catch (IllegalStateException e) { // exptected } @@ -186,7 +196,7 @@ public void testArchiveDirectoryRemoveFile() throws Exception { addStep("Remove nonexisting file from tmp", "Exception since it does not exist"); try { directory.removeFileFromTmp(FILE_ID); - Assert.fail("Should throw exception since the file does not exist."); + Assertions.fail("Should throw exception since the file does not exist."); } catch (IllegalStateException e) { // exptected } @@ -194,18 +204,20 @@ public void testArchiveDirectoryRemoveFile() throws Exception { addStep("Create file in both tmp, archive and retain directories.", ""); createExistingFile(); File tmpFile = directory.getNewFileInTempDir(FILE_ID); - Assert.assertTrue(tmpFile.createNewFile()); + Assertions.assertTrue(tmpFile.createNewFile()); File retainFile = new File(retainDir, FILE_ID); - Assert.assertTrue(retainFile.createNewFile()); - Assert.assertEquals(retainDir.list().length, 1); + Assertions.assertTrue(retainFile.createNewFile()); + Assertions.assertEquals(1, retainDir.list().length); addStep("Remove the file from archive and tmp", "all 3 files in retain dir."); directory.removeFileFromArchive(FILE_ID); directory.removeFileFromTmp(FILE_ID); - Assert.assertEquals(retainDir.list().length, 3); + Assertions.assertEquals(3, retainDir.list().length); } - @Test( groups = {"regressiontest", "pillartest"}) + @Test + @Tag("regressiontest") + @Tag("pillartest") public void testArchiveDirectoryExistingFolderFile() throws Exception { addDescription("Test the ArchiveDirectory when the file exists"); addStep("Setup", "Should place the 'existing file' in the directory."); @@ -214,17 +226,19 @@ public void testArchiveDirectoryExistingFolderFile() throws Exception { createExistingFolderFile(); addStep("Validate the existence of the file", "Should exist and be retrievable."); - Assert.assertTrue(directory.hasFile(FOLDER_FILE_ID)); - Assert.assertNotNull(directory.retrieveFile(FOLDER_FILE_ID)); - Assert.assertEquals(directory.getFileIds(), Arrays.asList(FOLDER_FILE_ID)); + Assertions.assertTrue(directory.hasFile(FOLDER_FILE_ID)); + Assertions.assertNotNull(directory.retrieveFile(FOLDER_FILE_ID)); + Assertions.assertEquals(directory.getFileIds(), Collections.singletonList(FOLDER_FILE_ID)); addStep("Delete the file.", "Should not be retrievable."); directory.removeFileFromArchive(FOLDER_FILE_ID); - Assert.assertFalse(directory.hasFile(FOLDER_FILE_ID)); - Assert.assertNull(directory.retrieveFile(FOLDER_FILE_ID)); + Assertions.assertFalse(directory.hasFile(FOLDER_FILE_ID)); + Assertions.assertNull(directory.retrieveFile(FOLDER_FILE_ID)); } - @Test( groups = {"regressiontest", "pillartest"}) + @Test + @Tag("regressiontest") + @Tag("pillartest") public void testArchiveDirectoryMissingFolderFile() throws Exception { addDescription("Test the ArchiveDirectory when the file is missing."); addStep("Setup", "No file added to the directory."); @@ -232,20 +246,22 @@ public void testArchiveDirectoryMissingFolderFile() throws Exception { ArchiveDirectory directory = new ArchiveDirectory(DIR_NAME); addStep("Validate the existence of the file", "Should neither exist nor be retrievable."); - Assert.assertFalse(directory.hasFile(FOLDER_FILE_ID)); - Assert.assertNull(directory.retrieveFile(FOLDER_FILE_ID)); - Assert.assertEquals(directory.getFileIds(), Collections.EMPTY_LIST); + Assertions.assertFalse(directory.hasFile(FOLDER_FILE_ID)); + Assertions.assertNull(directory.retrieveFile(FOLDER_FILE_ID)); + Assertions.assertEquals(Collections.EMPTY_LIST, directory.getFileIds()); addStep("Delete the file.", "exception since the file does not exist."); try { directory.removeFileFromArchive(FOLDER_FILE_ID); - Assert.fail("Should not be possible to remove a non-existing file."); + Assertions.fail("Should not be possible to remove a non-existing file."); } catch (IllegalStateException e) { // exptected } } - @Test( groups = {"regressiontest", "pillartest"}) + @Test + @Tag("regressiontest") + @Tag("pillartest") public void testArchiveDirectoryNewFolderFile() throws Exception { addDescription("Testing the ArchiveDirectory handling of a new file."); addStep("Setup", "No file added to the directory."); @@ -254,35 +270,37 @@ public void testArchiveDirectoryNewFolderFile() throws Exception { addStep("Retrieve tmp file", "Exception since files does not exist."); try { directory.getFileInTempDir(FOLDER_FILE_ID); - Assert.fail("Should throw exception since the file does not exist."); + Assertions.fail("Should throw exception since the file does not exist."); } catch (IllegalStateException e) { // exptected } addStep("Request a new file for the tmp dir", "Should be received and creatable."); File newFile = directory.getNewFileInTempDir(FOLDER_FILE_ID); - Assert.assertTrue(newFile.createNewFile()); + Assertions.assertTrue(newFile.createNewFile()); addStep("Retrieve tmp file", "Should be the newly created file."); File tmpFile = directory.getFileInTempDir(FOLDER_FILE_ID); - Assert.assertNotNull(tmpFile); - Assert.assertEquals(tmpFile.getAbsolutePath(), newFile.getAbsolutePath()); + Assertions.assertNotNull(tmpFile); + Assertions.assertEquals(tmpFile.getAbsolutePath(), newFile.getAbsolutePath()); addStep("Request another new file with the same name", "Should throw exception, since it already exists."); try { directory.getNewFileInTempDir(FOLDER_FILE_ID); - Assert.fail("Should throw exception, since the file already exists."); + Assertions.fail("Should throw exception, since the file already exists."); } catch (IllegalStateException e) { // expected } addStep("Move the file from tmp to archive", "Should exist in archive but not in tmp."); directory.moveFromTmpToArchive(FOLDER_FILE_ID); - Assert.assertTrue(directory.hasFile(FOLDER_FILE_ID)); - Assert.assertFalse(directory.hasFileInTempDir(FOLDER_FILE_ID)); + Assertions.assertTrue(directory.hasFile(FOLDER_FILE_ID)); + Assertions.assertFalse(directory.hasFileInTempDir(FOLDER_FILE_ID)); } - @Test( groups = {"regressiontest", "pillartest"}) + @Test + @Tag("regressiontest") + @Tag("pillartest") public void testArchiveDirectoryMoveFolderFileToArchive() throws Exception { addDescription("Testing the error scenarios when moving a file from tmp to archive for the ArchiveDirectory."); addStep("Setup", "No file added to the directory."); @@ -291,7 +309,7 @@ public void testArchiveDirectoryMoveFolderFileToArchive() throws Exception { addStep("Moving file from tmp to archive", "Exception since it does not exist in the tmp-dir"); try { directory.moveFromTmpToArchive(FOLDER_FILE_ID); - Assert.fail("Should throw exception since the file does not exist."); + Assertions.fail("Should throw exception since the file does not exist."); } catch (IllegalStateException e) { // exptected } @@ -299,30 +317,32 @@ public void testArchiveDirectoryMoveFolderFileToArchive() throws Exception { addStep("Create file in both tmp and archive.", ""); createExistingFolderFile(); File newFile = directory.getNewFileInTempDir(FOLDER_FILE_ID); - Assert.assertTrue(newFile.createNewFile()); + Assertions.assertTrue(newFile.createNewFile()); addStep("Moving file from tmp to archive", "Exception since the file already exists within the archive."); try { directory.moveFromTmpToArchive(FOLDER_FILE_ID); - Assert.fail("Should throw exception since the file in archive already exists."); + Assertions.fail("Should throw exception since the file in archive already exists."); } catch (IllegalStateException e) { // exptected } addStep("Remove the file from archive and try again", "File in tmp moved to archive."); - Assert.assertTrue(directory.hasFile(FOLDER_FILE_ID)); - Assert.assertTrue(directory.hasFileInTempDir(FOLDER_FILE_ID)); + Assertions.assertTrue(directory.hasFile(FOLDER_FILE_ID)); + Assertions.assertTrue(directory.hasFileInTempDir(FOLDER_FILE_ID)); directory.removeFileFromArchive(FOLDER_FILE_ID); - Assert.assertFalse(directory.hasFile(FOLDER_FILE_ID)); - Assert.assertTrue(directory.hasFileInTempDir(FOLDER_FILE_ID)); + Assertions.assertFalse(directory.hasFile(FOLDER_FILE_ID)); + Assertions.assertTrue(directory.hasFileInTempDir(FOLDER_FILE_ID)); directory.moveFromTmpToArchive(FOLDER_FILE_ID); - Assert.assertTrue(directory.hasFile(FOLDER_FILE_ID)); - Assert.assertFalse(directory.hasFileInTempDir(FOLDER_FILE_ID)); + Assertions.assertTrue(directory.hasFile(FOLDER_FILE_ID)); + Assertions.assertFalse(directory.hasFileInTempDir(FOLDER_FILE_ID)); } - @Test( groups = {"regressiontest", "pillartest"}) + @Test + @Tag("regressiontest") + @Tag("pillartest") public void testArchiveDirectoryRemoveFolderFile() throws Exception { addDescription("Testing the error scenarios when removing files from the archive."); addStep("Setup", "No file added to the directory."); @@ -332,7 +352,7 @@ public void testArchiveDirectoryRemoveFolderFile() throws Exception { addStep("Remove nonexisting file from archive", "Exception since it does not exist"); try { directory.removeFileFromArchive(FOLDER_FILE_ID); - Assert.fail("Should throw exception since the file does not exist."); + Assertions.fail("Should throw exception since the file does not exist."); } catch (IllegalStateException e) { // exptected } @@ -340,7 +360,7 @@ public void testArchiveDirectoryRemoveFolderFile() throws Exception { addStep("Remove nonexisting file from tmp", "Exception since it does not exist"); try { directory.removeFileFromTmp(FOLDER_FILE_ID); - Assert.fail("Should throw exception since the file does not exist."); + Assertions.fail("Should throw exception since the file does not exist."); } catch (IllegalStateException e) { // exptected } @@ -348,19 +368,19 @@ public void testArchiveDirectoryRemoveFolderFile() throws Exception { addStep("Create file in both tmp, archive and retain directories.", ""); createExistingFolderFile(); File tmpFile = directory.getNewFileInTempDir(FOLDER_FILE_ID); - Assert.assertTrue(tmpFile.createNewFile()); + Assertions.assertTrue(tmpFile.createNewFile()); File retainFile = new File(retainDir, FOLDER_FILE_ID); if(!retainFile.getParentFile().isDirectory()) { - Assert.assertTrue(retainFile.getParentFile().mkdirs()); + Assertions.assertTrue(retainFile.getParentFile().mkdirs()); } - Assert.assertTrue(retainFile.createNewFile()); - Assert.assertEquals(retainDir.list().length, 1); + Assertions.assertTrue(retainFile.createNewFile()); + Assertions.assertEquals(1, retainDir.list().length); addStep("Remove the file from archive and tmp", "all 3 files in retain dir."); directory.removeFileFromArchive(FOLDER_FILE_ID); directory.removeFileFromTmp(FOLDER_FILE_ID); List retainFiles = TestFileHelper.getAllFilesFromSubDirs(retainDir); - Assert.assertEquals(retainFiles.size(), 3); + Assertions.assertEquals(3, retainFiles.size()); } private void createExistingFile() throws Exception { diff --git a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/store/archive/ReferenceArchiveTest.java b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/store/archive/ReferenceArchiveTest.java index 892446721..e28e8d993 100644 --- a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/store/archive/ReferenceArchiveTest.java +++ b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/store/archive/ReferenceArchiveTest.java @@ -31,8 +31,9 @@ import org.bitrepository.pillar.messagehandler.PillarMediator; import org.bitrepository.pillar.store.filearchive.ReferenceArchive; import org.bitrepository.service.audit.MockAuditManager; -import org.testng.Assert; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; import java.io.File; import java.io.FileInputStream; @@ -47,11 +48,11 @@ public class ReferenceArchiveTest extends DefaultPillarTest { protected MockAuditManager audits; protected MessageHandlerContext context; - private static String DIR_NAME = "archive-directory"; - private static String FILE_DIR_NAME = DIR_NAME + "/fileDir"; + private static final String DIR_NAME = "archive-directory"; + private static final String FILE_DIR_NAME = DIR_NAME + "/fileDir"; - private static String EXISTING_FILE = "file1"; - private static String MISSING_FILE = "Missing-filE"; + private static final String EXISTING_FILE = "file1"; + private static final String MISSING_FILE = "Missing-filE"; @Override protected void shutdownCUT() { @@ -62,7 +63,9 @@ protected void shutdownCUT() { super.shutdownCUT(); } - @Test(groups = {"regressiontest", "pillartest"}) + @Test + @Tag("regressiontest") + @Tag("pillartest") public void testReferenceArchive() throws Exception { addDescription("Test the ReferenceArchive."); addStep("Setup", "Should be OK."); @@ -71,27 +74,27 @@ public void testReferenceArchive() throws Exception { createExistingFile(); addStep("test 'hasFile'", "Should be true for the existing one and false for the missing one."); - Assert.assertTrue(archive.hasFile(EXISTING_FILE)); - Assert.assertFalse(archive.hasFile(MISSING_FILE)); + Assertions.assertTrue(archive.hasFile(EXISTING_FILE)); + Assertions.assertFalse(archive.hasFile(MISSING_FILE)); addStep("Test 'getFile'", "Should be ok for the existing file and throw an exception on the missing"); archive.getFile(EXISTING_FILE); try { archive.getFile(MISSING_FILE); - Assert.fail("Should throw an exception when getting a missing file."); + Assertions.fail("Should throw an exception when getting a missing file."); } catch (Exception e) { // expected } addStep("Test getAllFileIDs", "Should only deliver the existing file"); - Assert.assertEquals(archive.getAllFileIds(), List.of(EXISTING_FILE)); + Assertions.assertEquals(archive.getAllFileIds(), List.of(EXISTING_FILE)); addStep("Test 'getFileAsInputStream'", "Should only be able to deliver the existing file."); FileInputStream fileAsInputStream = archive.getFileAsInputStream(EXISTING_FILE); assert fileAsInputStream != null; try { archive.getFileAsInputStream(MISSING_FILE); - Assert.fail("Should throw an exception when getting a missing file."); + Assertions.fail("Should throw an exception when getting a missing file."); } catch (Exception e) { // expected } @@ -101,12 +104,12 @@ public void testReferenceArchive() throws Exception { createExistingFile(); archive.deleteFile(EXISTING_FILE); createExistingFile(); - Assert.assertTrue(new File(DIR_NAME + "/retainDir/" + EXISTING_FILE + ".old").isFile()); + Assertions.assertTrue(new File(DIR_NAME + "/retainDir/" + EXISTING_FILE + ".old").isFile()); addStep("Try to delete missing file.", "Should throw an exception"); try { archive.deleteFile(MISSING_FILE); - Assert.fail("Should throw an exception here."); + Assertions.fail("Should throw an exception here."); } catch (IllegalStateException e) { // Expected. } @@ -114,7 +117,7 @@ public void testReferenceArchive() throws Exception { addStep("Replace a file, which does not exist in the filedir.", "Should throw an exception"); try { archive.replaceFile(MISSING_FILE); - Assert.fail("Should throw an exception here."); + Assertions.fail("Should throw an exception here."); } catch (IllegalStateException e) { // Expected. } @@ -124,13 +127,13 @@ public void testReferenceArchive() throws Exception { FileUtils.copyFile(new File(DIR_NAME + "/retainDir/" + EXISTING_FILE), new File(DIR_NAME + "/tmpDir/" + EXISTING_FILE)); archive.replaceFile(EXISTING_FILE); - Assert.assertFalse(new File(DIR_NAME + "/tmpDir/" + EXISTING_FILE).isFile()); - Assert.assertTrue(new File(DIR_NAME + "/retainDir/" + EXISTING_FILE + ".old.old").isFile()); + Assertions.assertFalse(new File(DIR_NAME + "/tmpDir/" + EXISTING_FILE).isFile()); + Assertions.assertTrue(new File(DIR_NAME + "/retainDir/" + EXISTING_FILE + ".old.old").isFile()); addStep("Try performing the replace, when the file in the tempdir has been removed.", "Should throw an exception"); try { archive.replaceFile(EXISTING_FILE); - Assert.fail("Should throw an exception here."); + Assertions.fail("Should throw an exception here."); } catch (IllegalStateException e) { // Expected. } diff --git a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/store/checksumcache/ChecksumDatabaseMigrationTest.java b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/store/checksumcache/ChecksumDatabaseMigrationTest.java index 04ec51809..982942963 100644 --- a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/store/checksumcache/ChecksumDatabaseMigrationTest.java +++ b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/store/checksumcache/ChecksumDatabaseMigrationTest.java @@ -5,16 +5,16 @@ * Copyright (C) 2010 - 2013 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% @@ -30,10 +30,11 @@ import org.bitrepository.service.database.DerbyDatabaseDestroyer; import org.bitrepository.settings.referencesettings.DatabaseSpecifics; import org.jaccept.structure.ExtendedTestCase; -import org.testng.Assert; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; import java.io.File; import java.util.Calendar; @@ -49,20 +50,20 @@ public class ChecksumDatabaseMigrationTest extends ExtendedTestCase { protected Settings settings; - + static final String PATH_TO_DATABASE_UNPACKED = "target/test/referencepillar/checksumdb-for-migration"; static final String PATH_TO_DATABASE_V1_JAR_FILE = "src/test/resources/checksumdb-version1.jar"; static final String PATH_TO_DATABASE_V3_JAR_FILE = "src/test/resources/checksumdb-version3.jar"; - + static final String FILE_ID = "default-file-id"; static final String CHECKSUM = "default-checksum"; - + static DBConnector connector = null; - @BeforeMethod (alwaysRun = true) + @BeforeEach public void setup() throws Exception { settings = TestSettingsProvider.reloadSettings("ReferencePillarTest"); - + settings.getReferenceSettings().getPillarSettings().getChecksumDatabase().setDatabaseURL( "jdbc:derby:" + PATH_TO_DATABASE_UNPACKED + "/checksumdb"); @@ -70,89 +71,93 @@ public void setup() throws Exception { settings.getReferenceSettings().getPillarSettings().getChecksumDatabase(); DerbyDatabaseDestroyer.deleteDatabase(checksumDB); } - - @AfterMethod (alwaysRun = true) + + @AfterEach public void cleanup() throws Exception { FileUtils.deleteDirIfExists(new File(PATH_TO_DATABASE_UNPACKED)); - if(connector != null && !connector.getConnection().isClosed()) { + if (connector != null && !connector.getConnection().isClosed()) { connector.getConnection().close(); connector.destroy(); connector = null; } } - -// @Test( groups = {"regressiontest", "pillartest"}) + + // @Test +// @Tag("regressiontest) +// @Tag("pillartest") public void testMigratingChecksumDatabaseFromV1ToV2() throws Exception { addDescription("Tests that the checksums table can be migrated from version 1 to 2, e.g. getting the column " + "collectionid, which should be set to the default in settings."); addStep("Unzipping and connecting to checksum database version 1", ""); FileUtils.unzip(new File(PATH_TO_DATABASE_V1_JAR_FILE), FileUtils.retrieveDirectory(PATH_TO_DATABASE_UNPACKED)); - + connector = new DBConnector( settings.getReferenceSettings().getPillarSettings().getChecksumDatabase()); addStep("Validate setup", "Checksums table has version 1"); String extractVersionSql = "SELECT version FROM tableversions WHERE tablename = ?"; int versionBefore = DatabaseUtils.selectIntValue(connector, extractVersionSql, CHECKSUM_TABLE); - Assert.assertEquals(versionBefore, 1, "Table version before migration"); - + Assertions.assertEquals(1, versionBefore, "Table version before migration"); + addStep("Ingest a entry to the database without the collection id", "works only in version 1."); - String insertSql = "INSERT INTO " + CHECKSUM_TABLE + " ( " + CS_FILE_ID + " , " + CS_CHECKSUM + " , " + CS_DATE + String insertSql = "INSERT INTO " + CHECKSUM_TABLE + " ( " + CS_FILE_ID + " , " + CS_CHECKSUM + " , " + CS_DATE + " ) VALUES ( ? , ? , ? )"; DatabaseUtils.executeStatement(connector, insertSql, FILE_ID, CHECKSUM, new Date()); - + addStep("Perform migration", "Checksums table has version 3"); ChecksumDBMigrator migrator = new ChecksumDBMigrator(connector, settings); migrator.migrate(); int versionAfter = DatabaseUtils.selectIntValue(connector, extractVersionSql, CHECKSUM_TABLE); - Assert.assertEquals(versionAfter, 4, "Table version after migration"); - + Assertions.assertEquals(4, versionAfter, "Table version after migration"); + addStep("Validate the entry", "The collection id has been set to the default collection id"); - String retrieveCollectionIdSql = "SELECT " + CS_COLLECTION_ID + " FROM " + CHECKSUM_TABLE + " WHERE " + String retrieveCollectionIdSql = "SELECT " + CS_COLLECTION_ID + " FROM " + CHECKSUM_TABLE + " WHERE " + CS_FILE_ID + " = ?"; String collectionID = DatabaseUtils.selectStringValue(connector, retrieveCollectionIdSql, FILE_ID); - Assert.assertEquals(collectionID, settings.getCollections().get(0).getID()); + Assertions.assertEquals(collectionID, settings.getCollections().get(0).getID()); } - - @Test( groups = {"regressiontest", "pillartest"}) + + @Test + @Tag("regressiontest") + @Tag("pillartest") public void testMigratingChecksumDatabaseFromV3ToV4() throws Exception { addDescription("Tests that the checksums table can be migrated from version 3 to 4, e.g. changing the column " + "calculatedchecksumdate from timestamp to bigint."); addStep("Ensure cleanup", ""); cleanup(); - + addStep("Unzipping and connecting to checksum database version 3", ""); FileUtils.unzip(new File(PATH_TO_DATABASE_V3_JAR_FILE), FileUtils.retrieveDirectory(PATH_TO_DATABASE_UNPACKED)); - + connector = new DBConnector( settings.getReferenceSettings().getPillarSettings().getChecksumDatabase()); Date testDate = new Date(1453984303527L); - Assert.assertFalse(connector.getConnection().isClosed()); - + Assertions.assertFalse(connector.getConnection().isClosed()); + addStep("Validate setup", "Checksums table has version 3"); String extractVersionSql = "SELECT version FROM tableversions WHERE tablename = ?"; int versionBefore = DatabaseUtils.selectIntValue(connector, extractVersionSql, CHECKSUM_TABLE); - Assert.assertEquals(versionBefore, 3, "Table version before migration"); - + Assertions.assertEquals(3, versionBefore, "Table version before migration"); + addStep("Ingest a entry to the database with a date for the calculationdate", "works in version 3."); String insertSql = "INSERT INTO " + CHECKSUM_TABLE + " ( " + CS_FILE_ID + " , " + CS_CHECKSUM + " , " + CS_DATE + " , " + CS_COLLECTION_ID + " ) VALUES ( ? , ? , ? , ? )"; DatabaseUtils.executeStatement(connector, insertSql, FILE_ID, CHECKSUM, testDate, settings.getCollections().get(0).getID()); - + addStep("Perform migration", "Checksums table has version 4"); ChecksumDBMigrator migrator = new ChecksumDBMigrator(connector, settings); migrator.migrate(); int versionAfter = DatabaseUtils.selectIntValue(connector, extractVersionSql, CHECKSUM_TABLE); - Assert.assertEquals(versionAfter, 4, "Table version after migration"); - + Assertions.assertEquals(4, versionAfter, "Table version after migration"); + addStep("Validate the migration", "The timestamp is now the millis from epoch"); - String retrieveCollectionIdSql = "SELECT " + CS_DATE + " FROM " + CHECKSUM_TABLE + " WHERE " + String retrieveCollectionIdSql = "SELECT " + CS_DATE + " FROM " + CHECKSUM_TABLE + " WHERE " + CS_FILE_ID + " = ?"; Long extractedDate = DatabaseUtils.selectFirstLongValue(connector, retrieveCollectionIdSql, FILE_ID); - + Date testDateAtTimeZone = new Date(testDate.getTime() + Calendar.getInstance(TimeZone.getDefault(), Locale.ROOT).getTimeZone().getRawOffset()); - - Assert.assertEquals(extractedDate.longValue(), testDateAtTimeZone.getTime()); + + Assertions.assertEquals(extractedDate.longValue(), testDateAtTimeZone.getTime()); } } diff --git a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/store/checksumcache/ChecksumDatabaseTest.java b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/store/checksumcache/ChecksumDatabaseTest.java index fba4c1698..4a471c4e4 100644 --- a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/store/checksumcache/ChecksumDatabaseTest.java +++ b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/store/checksumcache/ChecksumDatabaseTest.java @@ -5,16 +5,16 @@ * Copyright (C) 2010 - 2012 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% @@ -36,9 +36,10 @@ import org.bitrepository.settings.referencesettings.DatabaseSpecifics; import org.bitrepository.settings.repositorysettings.PillarIDs; import org.jaccept.structure.ExtendedTestCase; -import org.testng.Assert; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; import java.time.Instant; import java.util.Date; @@ -51,8 +52,8 @@ public class ChecksumDatabaseTest extends ExtendedTestCase { private static final String DEFAULT_FILE_ID = "TEST-FILE"; private static final String DEFAULT_CHECKSUM = "abcdef0110fedcba"; private static final Date DEFAULT_DATE = new Date(); - - @BeforeMethod (alwaysRun = true) + + @BeforeEach public void setup() throws Exception { loadSettings(); collectionID = settings.getCollections().get(0).getID(); @@ -65,56 +66,62 @@ public void setup() throws Exception { checksumDatabaseCreator.createChecksumDatabase(settings, null); } - @Test( groups = {"regressiontest", "pillartest"}) + @Test + @Tag("regressiontest") + @Tag("pillartest") public void testChecksumDatabaseExtraction() { addDescription("Test the extraction of data from the checksum database."); ChecksumDAO cache = getCacheWithData(); - + addStep("Check whether the default entry exists.", "It does!"); - Assert.assertTrue(cache.hasFile(DEFAULT_FILE_ID, collectionID)); + Assertions.assertTrue(cache.hasFile(DEFAULT_FILE_ID, collectionID)); addStep("Extract calculation date", "Should be identical to the default date."); - Assert.assertEquals(cache.getCalculationDate(DEFAULT_FILE_ID, collectionID), DEFAULT_DATE); + Assertions.assertEquals(DEFAULT_DATE, cache.getCalculationDate(DEFAULT_FILE_ID, collectionID)); addStep("Extract the checksum", "Should be identical to the default checksum"); - Assert.assertEquals(cache.getChecksum(DEFAULT_FILE_ID, collectionID), DEFAULT_CHECKSUM); + Assertions.assertEquals(DEFAULT_CHECKSUM, cache.getChecksum(DEFAULT_FILE_ID, collectionID)); addStep("Extract the whole entry", "Should have the default values."); ChecksumEntry entry = cache.getEntry(DEFAULT_FILE_ID, collectionID); - Assert.assertEquals(entry.getFileId(), DEFAULT_FILE_ID); - Assert.assertEquals(entry.getChecksum(), DEFAULT_CHECKSUM); - Assert.assertEquals(entry.getCalculationDate(), DEFAULT_DATE); + Assertions.assertEquals(DEFAULT_FILE_ID, entry.getFileId()); + Assertions.assertEquals(DEFAULT_CHECKSUM, entry.getChecksum()); + Assertions.assertEquals(DEFAULT_DATE, entry.getCalculationDate()); addStep("Extract all entries", "Should only be the one default."); List entries = cache.getChecksumResults(null, null, null, collectionID).getEntries(); - Assert.assertEquals(entries.size(), 1); - Assert.assertEquals(entries.get(0).getFileID(), DEFAULT_FILE_ID); - Assert.assertEquals(Base16Utils.decodeBase16(entries.get(0).getChecksumValue()), DEFAULT_CHECKSUM); - Assert.assertEquals(CalendarUtils.convertFromXMLGregorianCalendar(entries.get(0).getCalculationTimestamp()), - DEFAULT_DATE); + Assertions.assertEquals(1, entries.size()); + Assertions.assertEquals(DEFAULT_FILE_ID, entries.get(0).getFileID()); + Assertions.assertEquals(DEFAULT_CHECKSUM, Base16Utils.decodeBase16(entries.get(0).getChecksumValue())); + Assertions.assertEquals(DEFAULT_DATE, + CalendarUtils.convertFromXMLGregorianCalendar(entries.get(0).getCalculationTimestamp())); } - @Test( groups = {"regressiontest", "pillartest"}) + @Test + @Tag("regressiontest") + @Tag("pillartest") public void testDeletion() { addDescription("Test that data can be deleted from the database."); ChecksumDAO cache = getCacheWithData(); addStep("Check whether the default entry exists.", "It does!"); - Assert.assertTrue(cache.hasFile(DEFAULT_FILE_ID, collectionID)); + Assertions.assertTrue(cache.hasFile(DEFAULT_FILE_ID, collectionID)); ExtractedFileIDsResultSet res = cache.getFileIDs(null, null, null, null, collectionID); - Assert.assertEquals(res.getEntries().getFileIDsDataItems().getFileIDsDataItem().size(), 1); - Assert.assertEquals(res.getEntries().getFileIDsDataItems().getFileIDsDataItem().get(0).getFileID(), - DEFAULT_FILE_ID); + Assertions.assertEquals(1, res.getEntries().getFileIDsDataItems().getFileIDsDataItem().size()); + Assertions.assertEquals(DEFAULT_FILE_ID, + res.getEntries().getFileIDsDataItems().getFileIDsDataItem().get(0).getFileID()); addStep("Remove the default entry", "Should no longer exist"); cache.deleteEntry(DEFAULT_FILE_ID, collectionID); - Assert.assertFalse(cache.hasFile(DEFAULT_FILE_ID, collectionID)); + Assertions.assertFalse(cache.hasFile(DEFAULT_FILE_ID, collectionID)); res = cache.getFileIDs(null, null, null, null, collectionID); - Assert.assertEquals(res.getEntries().getFileIDsDataItems().getFileIDsDataItem().size(), 0); + Assertions.assertEquals(0, res.getEntries().getFileIDsDataItems().getFileIDsDataItem().size()); } - @Test( groups = {"regressiontest", "pillartest"}) + @Test + @Tag("regressiontest") + @Tag("pillartest") public void testReplacingExistingEntry() { addDescription("Test that an entry can be replaced by another in the database."); ChecksumDAO cache = getCacheWithData(); @@ -123,23 +130,25 @@ public void testReplacingExistingEntry() { Date newDate = new Date(System.currentTimeMillis() + 123456789L); addStep("Check whether the default entry exists.", "It does!"); - Assert.assertTrue(cache.hasFile(DEFAULT_FILE_ID, collectionID)); + Assertions.assertTrue(cache.hasFile(DEFAULT_FILE_ID, collectionID)); ChecksumEntry oldEntry = cache.getEntry(DEFAULT_FILE_ID, collectionID); - Assert.assertEquals(oldEntry.getFileId(), DEFAULT_FILE_ID); - Assert.assertEquals(oldEntry.getChecksum(), DEFAULT_CHECKSUM); - Assert.assertEquals(oldEntry.getCalculationDate(), DEFAULT_DATE); + Assertions.assertEquals(DEFAULT_FILE_ID, oldEntry.getFileId()); + Assertions.assertEquals(DEFAULT_CHECKSUM, oldEntry.getChecksum()); + Assertions.assertEquals(DEFAULT_DATE, oldEntry.getCalculationDate()); addStep("Replace the checksum and date", "Should still exist, but have different values."); cache.insertChecksumCalculation(DEFAULT_FILE_ID, collectionID, newChecksum, newDate); - Assert.assertTrue(cache.hasFile(DEFAULT_FILE_ID, collectionID)); + Assertions.assertTrue(cache.hasFile(DEFAULT_FILE_ID, collectionID)); ChecksumEntry newEntry = cache.getEntry(DEFAULT_FILE_ID, collectionID); - Assert.assertEquals(newEntry.getFileId(), DEFAULT_FILE_ID); - Assert.assertEquals(newEntry.getChecksum(), newChecksum); - Assert.assertFalse(oldEntry.getChecksum().equals(newEntry.getChecksum())); - Assert.assertFalse(oldEntry.getCalculationDate().getTime() == newEntry.getCalculationDate().getTime()); + Assertions.assertEquals(DEFAULT_FILE_ID, newEntry.getFileId()); + Assertions.assertEquals(newChecksum, newEntry.getChecksum()); + Assertions.assertNotEquals(oldEntry.getChecksum(), newEntry.getChecksum()); + Assertions.assertNotEquals(oldEntry.getCalculationDate().getTime(), newEntry.getCalculationDate().getTime()); } - @Test( groups = {"regressiontest", "pillartest"}) + @Test + @Tag("regressiontest") + @Tag("pillartest") public void testExtractionOfMissingData() { addDescription("Test the handling of bad arguments."); ChecksumDAO cache = getCacheWithData(); @@ -148,7 +157,7 @@ public void testExtractionOfMissingData() { addStep("Try to get the date of a wrong file id.", "Should throw an exception"); try { cache.getCalculationDate(badFileId, collectionID); - Assert.fail("Should throw an exception here."); + Assertions.fail("Should throw an exception here."); } catch (IllegalStateException e) { // expected } @@ -156,7 +165,7 @@ public void testExtractionOfMissingData() { addStep("Try to get the date of a wrong file id.", "Should throw an exception"); try { cache.getChecksum(badFileId, collectionID); - Assert.fail("Should throw an exception here."); + Assertions.fail("Should throw an exception here."); } catch (IllegalStateException e) { // expected } @@ -164,13 +173,15 @@ public void testExtractionOfMissingData() { addStep("Try to remove a bad file id", "Should throw an exception"); try { cache.deleteEntry(badFileId, collectionID); - Assert.fail("Should throw an exception here."); + Assertions.fail("Should throw an exception here."); } catch (IllegalStateException e) { // expected } } - @Test( groups = {"regressiontest", "pillartest"}) + @Test + @Tag("regressiontest") + @Tag("pillartest") public void testSpecifiedEntryExtraction() { addDescription("Test that specific entries can be extracted. Has two entries in the database: " + "one for the current timestamp and one for the epoch."); @@ -182,40 +193,42 @@ public void testSpecifiedEntryExtraction() { addStep("Extract with out restrictions", "Both entries."); ExtractedChecksumResultSet extractedResults = cache.getChecksumResults(null, null, null, collectionID); - Assert.assertEquals(extractedResults.getEntries().size(), 2); + Assertions.assertEquals(2, extractedResults.getEntries().size()); addStep("Extract with a maximum of 1 entry", "The oldest entry"); extractedResults = cache.getChecksumResults(null, null, 1L, collectionID); - Assert.assertEquals(extractedResults.getEntries().size(), 1); + Assertions.assertEquals(1, extractedResults.getEntries().size()); ChecksumDataForChecksumSpecTYPE dataEntry = extractedResults.getEntries().get(0); - Assert.assertEquals(CalendarUtils.convertFromXMLGregorianCalendar(dataEntry.getCalculationTimestamp()).getTime(), 0); - Assert.assertEquals(dataEntry.getFileID(), oldFile); + Assertions.assertEquals(0, CalendarUtils.convertFromXMLGregorianCalendar(dataEntry.getCalculationTimestamp()).getTime()); + Assertions.assertEquals(oldFile, dataEntry.getFileID()); addStep("Extract all dates older than this tests instantiation", "The oldest entry"); extractedResults = cache.getChecksumResults(null, CalendarUtils.getXmlGregorianCalendar(beforeTest), null, collectionID); - Assert.assertEquals(extractedResults.getEntries().size(), 1); + Assertions.assertEquals(1, extractedResults.getEntries().size()); dataEntry = extractedResults.getEntries().get(0); - Assert.assertEquals(CalendarUtils.convertFromXMLGregorianCalendar(dataEntry.getCalculationTimestamp()).getTime(), 0); - Assert.assertEquals(dataEntry.getFileID(), oldFile); + Assertions.assertEquals(0, CalendarUtils.convertFromXMLGregorianCalendar(dataEntry.getCalculationTimestamp()).getTime()); + Assertions.assertEquals(oldFile, dataEntry.getFileID()); addStep("Extract all dates newer than this tests instantiation", "The default entry"); extractedResults = cache.getChecksumResults(CalendarUtils.getXmlGregorianCalendar(beforeTest), null, null, collectionID); - Assert.assertEquals(extractedResults.getEntries().size(), 1); + Assertions.assertEquals(1, extractedResults.getEntries().size()); dataEntry = extractedResults.getEntries().get(0); - Assert.assertEquals(CalendarUtils.convertFromXMLGregorianCalendar(dataEntry.getCalculationTimestamp()), - DEFAULT_DATE); - Assert.assertEquals(dataEntry.getFileID(), DEFAULT_FILE_ID); + Assertions.assertEquals(DEFAULT_DATE, + CalendarUtils.convertFromXMLGregorianCalendar(dataEntry.getCalculationTimestamp())); + Assertions.assertEquals(DEFAULT_FILE_ID, dataEntry.getFileID()); addStep("Extract all dates older than the newest instance", "Both entries"); extractedResults = cache.getChecksumResults(null, CalendarUtils.getXmlGregorianCalendar(DEFAULT_DATE), null, collectionID); - Assert.assertEquals(extractedResults.getEntries().size(), 2); + Assertions.assertEquals(2, extractedResults.getEntries().size()); addStep("Extract all dates newer than the oldest instantiation", "Both entries"); extractedResults = cache.getChecksumResults(CalendarUtils.getEpoch(), null, null, collectionID); - Assert.assertEquals(extractedResults.getEntries().size(), 2); + Assertions.assertEquals(2, extractedResults.getEntries().size()); } - - @Test( groups = {"regressiontest", "pillartest"}) + + @Test + @Tag("regressiontest") + @Tag("pillartest") public void testGetFileIDsRestrictions() { addDescription("Tests the restrictions on the GetFileIDs call to the database."); addStep("Instantiate database with appropriate data.", ""); @@ -227,97 +240,101 @@ public void testGetFileIDsRestrictions() { Date MIDDLE_DATE = new Date(23456); cache.insertChecksumCalculation(FILE_ID_1, collectionID, DEFAULT_CHECKSUM, FILE_1_DATE); cache.insertChecksumCalculation(FILE_ID_2, collectionID, DEFAULT_CHECKSUM, FILE_2_DATE); - + addStep("Test with no time restrictions and 10000 max_results", "Delivers both files."); ExtractedFileIDsResultSet efirs = cache.getFileIDs(null, null, 100000L, null, collectionID); - Assert.assertEquals(efirs.getEntries().getFileIDsDataItems().getFileIDsDataItem().size(), 2); - + Assertions.assertEquals(2, efirs.getEntries().getFileIDsDataItems().getFileIDsDataItem().size()); + addStep("Test with minimum-date earlier than first file", "Delivers both files."); efirs = cache.getFileIDs(CalendarUtils.getFromMillis(0), null, 100000L, null, collectionID); - Assert.assertEquals(efirs.getEntries().getFileIDsDataItems().getFileIDsDataItem().size(), 2); + Assertions.assertEquals(2, efirs.getEntries().getFileIDsDataItems().getFileIDsDataItem().size()); addStep("Test with maximum-date earlier than first file", "Delivers no files."); efirs = cache.getFileIDs(null, CalendarUtils.getFromMillis(0), 100000L, null, collectionID); - Assert.assertEquals(efirs.getEntries().getFileIDsDataItems().getFileIDsDataItem().size(), 0); + Assertions.assertEquals(0, efirs.getEntries().getFileIDsDataItems().getFileIDsDataItem().size()); addStep("Test with minimum-date set to later than second file.", "Delivers no files."); efirs = cache.getFileIDs(CalendarUtils.getXmlGregorianCalendar(new Date()), null, 100000L, null, collectionID); - Assert.assertEquals(efirs.getEntries().getFileIDsDataItems().getFileIDsDataItem().size(), 0); + Assertions.assertEquals(0, efirs.getEntries().getFileIDsDataItems().getFileIDsDataItem().size()); addStep("Test with maximum-date set to later than second file.", "Delivers both files."); efirs = cache.getFileIDs(null, CalendarUtils.getXmlGregorianCalendar(new Date()), 100000L, null, collectionID); - Assert.assertEquals(efirs.getEntries().getFileIDsDataItems().getFileIDsDataItem().size(), 2); + Assertions.assertEquals(2, efirs.getEntries().getFileIDsDataItems().getFileIDsDataItem().size()); addStep("Test with minimum-date set to middle date.", "Delivers second file."); efirs = cache.getFileIDs(CalendarUtils.getXmlGregorianCalendar(MIDDLE_DATE), null, 100000L, null, collectionID); - Assert.assertEquals(efirs.getEntries().getFileIDsDataItems().getFileIDsDataItem().size(), 1); - Assert.assertEquals(efirs.getEntries().getFileIDsDataItems().getFileIDsDataItem().get(0).getFileID(), FILE_ID_2); - + Assertions.assertEquals(1, efirs.getEntries().getFileIDsDataItems().getFileIDsDataItem().size()); + Assertions.assertEquals(FILE_ID_2, efirs.getEntries().getFileIDsDataItems().getFileIDsDataItem().get(0).getFileID()); + addStep("Test with maximum-date set to middle date.", "Delivers first file."); efirs = cache.getFileIDs(null, CalendarUtils.getXmlGregorianCalendar(MIDDLE_DATE), 100000L, null, collectionID); - Assert.assertEquals(efirs.getEntries().getFileIDsDataItems().getFileIDsDataItem().size(), 1); - Assert.assertEquals(efirs.getEntries().getFileIDsDataItems().getFileIDsDataItem().get(0).getFileID(), FILE_ID_1); + Assertions.assertEquals(1, efirs.getEntries().getFileIDsDataItems().getFileIDsDataItem().size()); + Assertions.assertEquals(FILE_ID_1, efirs.getEntries().getFileIDsDataItems().getFileIDsDataItem().get(0).getFileID()); addStep("Test with both minimum-date and maximum-date set to middle date.", "Delivers no files."); efirs = cache.getFileIDs(CalendarUtils.getXmlGregorianCalendar(MIDDLE_DATE), CalendarUtils.getXmlGregorianCalendar(MIDDLE_DATE), 100000L, null, collectionID); - Assert.assertEquals(efirs.getEntries().getFileIDsDataItems().getFileIDsDataItem().size(), 0); - + Assertions.assertEquals(0, efirs.getEntries().getFileIDsDataItems().getFileIDsDataItem().size()); + addStep("Test the first file-id, with no other restrictions", "Only delivers the requested file-id"); efirs = cache.getFileIDs(null, null, 100000L, FILE_ID_1, collectionID); - Assert.assertEquals(efirs.getEntries().getFileIDsDataItems().getFileIDsDataItem().size(), 1); - Assert.assertEquals(efirs.getEntries().getFileIDsDataItems().getFileIDsDataItem().get(0).getFileID(), FILE_ID_1); - + Assertions.assertEquals(1, efirs.getEntries().getFileIDsDataItems().getFileIDsDataItem().size()); + Assertions.assertEquals(FILE_ID_1, efirs.getEntries().getFileIDsDataItems().getFileIDsDataItem().get(0).getFileID()); + addStep("Test the second file-id, with no other restrictions", "Only delivers the requested file-id"); efirs = cache.getFileIDs(null, null, 100000L, FILE_ID_2, collectionID); - Assert.assertEquals(efirs.getEntries().getFileIDsDataItems().getFileIDsDataItem().size(), 1); - Assert.assertEquals(efirs.getEntries().getFileIDsDataItems().getFileIDsDataItem().get(0).getFileID(), FILE_ID_2); - + Assertions.assertEquals(1, efirs.getEntries().getFileIDsDataItems().getFileIDsDataItem().size()); + Assertions.assertEquals(FILE_ID_2, efirs.getEntries().getFileIDsDataItems().getFileIDsDataItem().get(0).getFileID()); + addStep("Test the date for the first file-id, while requesting the second file-id", "Should not deliver anything"); efirs = cache.getFileIDs(CalendarUtils.getFromMillis(0), CalendarUtils.getXmlGregorianCalendar(MIDDLE_DATE), 100000L, FILE_ID_2, collectionID); - Assert.assertEquals(efirs.getEntries().getFileIDsDataItems().getFileIDsDataItem().size(), 0); + Assertions.assertEquals(0, efirs.getEntries().getFileIDsDataItems().getFileIDsDataItem().size()); } - @Test( groups = {"regressiontest", "pillartest"}) + @Test + @Tag("regressiontest") + @Tag("pillartest") public void testGetChecksumResult() { addDescription("Tests the restrictions on the GetChecksumResult call to the database."); addStep("Instantiate database with appropriate data.", ""); ChecksumDAO cache = getCacheWithData(); - + addStep("Test with no time restrictions", "Retrieves the file"); - ExtractedChecksumResultSet extractedChecksums = cache.getChecksumResult(null, null, DEFAULT_FILE_ID, collectionID); - Assert.assertEquals(extractedChecksums.getEntries().size(), 1); - Assert.assertEquals(extractedChecksums.getEntries().get(0).getFileID(), DEFAULT_FILE_ID); - + ExtractedChecksumResultSet extractedChecksums = cache.getChecksumResult(null, null, DEFAULT_FILE_ID, collectionID); + Assertions.assertEquals(1, extractedChecksums.getEntries().size()); + Assertions.assertEquals(DEFAULT_FILE_ID, extractedChecksums.getEntries().get(0).getFileID()); + addStep("Test with time restrictions from epoc to now", "Retrieves the file"); - extractedChecksums = cache.getChecksumResult(CalendarUtils.getEpoch(), CalendarUtils.getNow(), DEFAULT_FILE_ID, collectionID); - Assert.assertEquals(extractedChecksums.getEntries().size(), 1); - + extractedChecksums = cache.getChecksumResult(CalendarUtils.getEpoch(), CalendarUtils.getNow(), DEFAULT_FILE_ID, collectionID); + Assertions.assertEquals(1, extractedChecksums.getEntries().size()); + addStep("Test with very strict time restrictions around the default date", "Retrieves the file"); - extractedChecksums = cache.getChecksumResult(CalendarUtils.getFromMillis(DEFAULT_DATE.getTime() - 1), CalendarUtils.getFromMillis(DEFAULT_DATE.getTime() + 1), DEFAULT_FILE_ID, collectionID); - Assert.assertEquals(extractedChecksums.getEntries().size(), 1); - + extractedChecksums = cache.getChecksumResult(CalendarUtils.getFromMillis(DEFAULT_DATE.getTime() - 1), CalendarUtils.getFromMillis(DEFAULT_DATE.getTime() + 1), DEFAULT_FILE_ID, collectionID); + Assertions.assertEquals(1, extractedChecksums.getEntries().size()); + addStep("Test with too new a lower limit", "Does not retrieve the file"); - extractedChecksums = cache.getChecksumResult(CalendarUtils.getFromMillis(DEFAULT_DATE.getTime() + 1), CalendarUtils.getNow(), DEFAULT_FILE_ID, collectionID); - Assert.assertEquals(extractedChecksums.getEntries().size(), 0); - + extractedChecksums = cache.getChecksumResult(CalendarUtils.getFromMillis(DEFAULT_DATE.getTime() + 1), CalendarUtils.getNow(), DEFAULT_FILE_ID, collectionID); + Assertions.assertEquals(0, extractedChecksums.getEntries().size()); + addStep("Test with exact date as both upper and lower limit", "Does not retrieve the file"); - extractedChecksums = cache.getChecksumResult(CalendarUtils.getFromMillis(DEFAULT_DATE.getTime()), CalendarUtils.getFromMillis(DEFAULT_DATE.getTime()), DEFAULT_FILE_ID, collectionID); - Assert.assertEquals(extractedChecksums.getEntries().size(), 0); + extractedChecksums = cache.getChecksumResult(CalendarUtils.getFromMillis(DEFAULT_DATE.getTime()), CalendarUtils.getFromMillis(DEFAULT_DATE.getTime()), DEFAULT_FILE_ID, collectionID); + Assertions.assertEquals(0, extractedChecksums.getEntries().size()); addStep("Test with date limit from 1 millis before as lower and exact date a upper limit", "Does retrieve the file"); - extractedChecksums = cache.getChecksumResult(CalendarUtils.getFromMillis(DEFAULT_DATE.getTime()-1), CalendarUtils.getFromMillis(DEFAULT_DATE.getTime()), DEFAULT_FILE_ID, collectionID); - Assert.assertEquals(extractedChecksums.getEntries().size(), 1); + extractedChecksums = cache.getChecksumResult(CalendarUtils.getFromMillis(DEFAULT_DATE.getTime() - 1), CalendarUtils.getFromMillis(DEFAULT_DATE.getTime()), DEFAULT_FILE_ID, collectionID); + Assertions.assertEquals(1, extractedChecksums.getEntries().size()); addStep("Test with date limit from exact date as lower and 1 millis after date a upper limit", "Does not retrieve the file"); - extractedChecksums = cache.getChecksumResult(CalendarUtils.getFromMillis(DEFAULT_DATE.getTime()), CalendarUtils.getFromMillis(DEFAULT_DATE.getTime()+1), DEFAULT_FILE_ID, collectionID); - Assert.assertEquals(extractedChecksums.getEntries().size(), 0); + extractedChecksums = cache.getChecksumResult(CalendarUtils.getFromMillis(DEFAULT_DATE.getTime()), CalendarUtils.getFromMillis(DEFAULT_DATE.getTime() + 1), DEFAULT_FILE_ID, collectionID); + Assertions.assertEquals(0, extractedChecksums.getEntries().size()); addStep("Test with too old an upper limit", "Does not retrieve the file"); - extractedChecksums = cache.getChecksumResult(CalendarUtils.getEpoch(), CalendarUtils.getFromMillis(DEFAULT_DATE.getTime() - 1), DEFAULT_FILE_ID, collectionID); - Assert.assertEquals(extractedChecksums.getEntries().size(), 0); + extractedChecksums = cache.getChecksumResult(CalendarUtils.getEpoch(), CalendarUtils.getFromMillis(DEFAULT_DATE.getTime() - 1), DEFAULT_FILE_ID, collectionID); + Assertions.assertEquals(0, extractedChecksums.getEntries().size()); } - @Test( groups = {"regressiontest", "pillartest"}) + @Test + @Tag("regressiontest") + @Tag("pillartest") public void testGetFileIDsWithOldChecksums() { addDescription("Tests the restrictions on the GetFileIDsWithOldChecksums call to the database."); addStep("Instantiate database with appropriate data.", ""); @@ -329,27 +346,27 @@ public void testGetFileIDsWithOldChecksums() { Date MIDDLE_DATE = new Date(23456); cache.insertChecksumCalculation(FILE_ID_1, collectionID, DEFAULT_CHECKSUM, FILE_1_DATE); cache.insertChecksumCalculation(FILE_ID_2, collectionID, DEFAULT_CHECKSUM, FILE_2_DATE); - + addStep("Extract all entries with checksum date older than now", "Returns both file ids"); List extractedFileIDs = cache.getFileIDsWithOldChecksums(Instant.now(), collectionID); - Assert.assertEquals(extractedFileIDs.size(), 2); - Assert.assertTrue(extractedFileIDs.contains(FILE_ID_1)); - Assert.assertTrue(extractedFileIDs.contains(FILE_ID_2)); - + Assertions.assertEquals(2, extractedFileIDs.size()); + Assertions.assertTrue(extractedFileIDs.contains(FILE_ID_1)); + Assertions.assertTrue(extractedFileIDs.contains(FILE_ID_2)); + addStep("Extract all entries with checksum date older than epoch", "Returns no file ids"); extractedFileIDs = cache.getFileIDsWithOldChecksums(Instant.EPOCH, collectionID); - Assert.assertEquals(extractedFileIDs.size(), 0); - + Assertions.assertEquals(0, extractedFileIDs.size()); + addStep("Extract all entries with checksum date older than middle date", "Returns the first file id"); extractedFileIDs = cache.getFileIDsWithOldChecksums(MIDDLE_DATE.toInstant(), collectionID); - Assert.assertEquals(extractedFileIDs.size(), 1); - Assert.assertTrue(extractedFileIDs.contains(FILE_ID_1)); + Assertions.assertEquals(1, extractedFileIDs.size()); + Assertions.assertTrue(extractedFileIDs.contains(FILE_ID_1)); } - + private ChecksumDAO getCacheWithData() { ChecksumDAO res = new ChecksumDAO(new ChecksumDatabaseManager(settings)); - for(String fileID : res.getAllFileIDs(collectionID)) { + for (String fileID : res.getAllFileIDs(collectionID)) { res.deleteEntry(fileID, collectionID); } res.insertChecksumCalculation(DEFAULT_FILE_ID, collectionID, DEFAULT_CHECKSUM, DEFAULT_DATE); diff --git a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/store/checksumcache/ChecksumEntryTest.java b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/store/checksumcache/ChecksumEntryTest.java index f52b9379a..bbed75b5e 100644 --- a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/store/checksumcache/ChecksumEntryTest.java +++ b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/store/checksumcache/ChecksumEntryTest.java @@ -23,8 +23,9 @@ import org.bitrepository.pillar.store.checksumdatabase.ChecksumEntry; import org.jaccept.structure.ExtendedTestCase; -import org.testng.Assert; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; import java.util.Date; @@ -33,13 +34,15 @@ public class ChecksumEntryTest extends ExtendedTestCase { private static final String CE_CHECKSUM = "checksum"; private static final Date CE_DATE = new Date(1234567890); - @Test( groups = {"regressiontest", "pillartest"}) + @Test + @Tag("regressiontest") + @Tag("pillartest") public void testExtendedTestCase() throws Exception { addDescription("Test the ChecksumEntry"); addStep("Create a ChecksumEntry", "The data should be extractable again."); ChecksumEntry ce = new ChecksumEntry(CE_FILE, CE_CHECKSUM, CE_DATE); - Assert.assertEquals(ce.getFileId(), CE_FILE); - Assert.assertEquals(ce.getChecksum(), CE_CHECKSUM); - Assert.assertEquals(ce.getCalculationDate(), CE_DATE); + Assertions.assertEquals(CE_FILE, ce.getFileId()); + Assertions.assertEquals(CE_CHECKSUM, ce.getChecksum()); + Assertions.assertEquals(CE_DATE, ce.getCalculationDate()); } } diff --git a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/store/checksumcache/MemoryCacheMock.java b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/store/checksumcache/MemoryCacheMock.java index dfcd43209..7f188f28a 100644 --- a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/store/checksumcache/MemoryCacheMock.java +++ b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/store/checksumcache/MemoryCacheMock.java @@ -45,7 +45,7 @@ public class MemoryCacheMock implements ChecksumStore { /** * The checksum mapping between the file ids and their checksum. */ - private Map checksumMap = new HashMap<>(); + private final Map checksumMap = new HashMap<>(); public MemoryCacheMock() {} diff --git a/bitrepository-reference-pillar/src/test/java/org/bitrepository/protocol/GlobalSuiteExtension.java b/bitrepository-reference-pillar/src/test/java/org/bitrepository/protocol/GlobalSuiteExtension.java new file mode 100644 index 000000000..1838231cb --- /dev/null +++ b/bitrepository-reference-pillar/src/test/java/org/bitrepository/protocol/GlobalSuiteExtension.java @@ -0,0 +1,213 @@ +package org.bitrepository.protocol; + +import org.bitrepository.common.settings.Settings; +import org.bitrepository.common.settings.TestSettingsProvider; +import org.bitrepository.common.utils.SettingsUtils; +import org.bitrepository.common.utils.TestFileHelper; +import org.bitrepository.protocol.bus.LocalActiveMQBroker; +import org.bitrepository.protocol.bus.MessageReceiver; +import org.bitrepository.protocol.fileexchange.HttpServerConfiguration; +import org.bitrepository.protocol.http.EmbeddedHttpServer; +import org.bitrepository.protocol.messagebus.MessageBus; +import org.bitrepository.protocol.messagebus.MessageBusManager; +import org.bitrepository.protocol.messagebus.SimpleMessageBus; +import org.bitrepository.protocol.security.DummySecurityManager; +import org.bitrepository.protocol.security.SecurityManager; +import org.jaccept.TestEventManager; +import org.junit.jupiter.api.extension.AfterAllCallback; +import org.junit.jupiter.api.extension.BeforeAllCallback; +import org.junit.jupiter.api.extension.ExtensionContext; + +import javax.jms.JMSException; +import java.net.MalformedURLException; +import java.net.URL; + +public class GlobalSuiteExtension implements BeforeAllCallback, AfterAllCallback { + + private static boolean initialized = false; + protected static TestEventManager testEventManager = TestEventManager.getInstance(); + public static LocalActiveMQBroker broker; + public static EmbeddedHttpServer server; + public static HttpServerConfiguration httpServerConfiguration; + public static MessageBus messageBus; + private MessageReceiverManager receiverManager; + protected static String alarmDestinationID; + protected static MessageReceiver alarmReceiver; + protected static SecurityManager securityManager; + protected static Settings settingsForCUT; + protected static Settings settingsForTestClient; + protected static String collectionID; + protected String NON_DEFAULT_FILE_ID; + protected static String DEFAULT_FILE_ID; + protected static URL DEFAULT_FILE_URL; + protected static String DEFAULT_DOWNLOAD_FILE_ADDRESS; + protected static String DEFAULT_UPLOAD_FILE_ADDRESS; + protected String DEFAULT_AUDIT_INFORMATION; + protected String testMethodName; + + @Override + public void beforeAll(ExtensionContext context) { + if (!initialized) { + initialized = true; + settingsForCUT = loadSettings(getComponentID()); + settingsForTestClient = loadSettings("TestSuiteInitialiser"); + makeUserSpecificSettings(settingsForCUT); + makeUserSpecificSettings(settingsForTestClient); + httpServerConfiguration = new HttpServerConfiguration(settingsForTestClient.getReferenceSettings().getFileExchangeSettings()); + collectionID = settingsForTestClient.getCollections().get(0).getID(); + + securityManager = createSecurityManager(); + DEFAULT_FILE_ID = "DefaultFile"; + try { + DEFAULT_FILE_URL = httpServerConfiguration.getURL(TestFileHelper.DEFAULT_FILE_ID); + DEFAULT_DOWNLOAD_FILE_ADDRESS = DEFAULT_FILE_URL.toExternalForm(); + DEFAULT_UPLOAD_FILE_ADDRESS = DEFAULT_FILE_URL.toExternalForm() + "-" + DEFAULT_FILE_ID; + } catch (MalformedURLException e) { + throw new RuntimeException("Never happens", e); + } + } + } + + @Override + public void afterAll(ExtensionContext context) { + if (initialized) { + teardownMessageBus(); + teardownHttpServer(); + } + } + + /** + * May be extended by subclasses needing to have their receivers managed. Remember to still call + * super.registerReceivers() when overriding + */ + protected void registerMessageReceivers() { + alarmReceiver = new MessageReceiver(settingsForCUT.getAlarmDestination(), testEventManager); + addReceiver(alarmReceiver); + } + + protected void addReceiver(MessageReceiver receiver) { + receiverManager.addReceiver(receiver); + } + + protected void initializeCUT() { + } + + /** + * Purges all messages from the receivers. + */ + protected void clearReceivers() { + receiverManager.clearMessagesInReceivers(); + } + + /** + * May be overridden by specific tests wishing to do stuff. Remember to call super if this is overridden. + */ + protected void shutdownCUT() { + } + + /** + * Initializes the settings. Will postfix the alarm and collection topics with '-${user.name} + */ + protected void setupSettings() { + settingsForCUT = loadSettings(getComponentID()); + makeUserSpecificSettings(settingsForCUT); + SettingsUtils.initialize(settingsForCUT); + + alarmDestinationID = settingsForCUT.getRepositorySettings().getProtocolSettings().getAlarmDestination(); + + settingsForTestClient = loadSettings(testMethodName); + makeUserSpecificSettings(settingsForTestClient); + } + + + protected Settings loadSettings(String componentID) { + return TestSettingsProvider.reloadSettings(componentID); + } + + protected void makeUserSpecificSettings(Settings settings) { + settings.getRepositorySettings().getProtocolSettings() + .setCollectionDestination(settings.getCollectionDestination() + getTopicPostfix()); + settings.getRepositorySettings().getProtocolSettings().setAlarmDestination(settings.getAlarmDestination() + getTopicPostfix()); + } + + /** + * Indicated whether an embedded active MQ should be started and used + */ + public boolean useEmbeddedMessageBus() { + return System.getProperty("useEmbeddedMessageBus", "true").equals("true"); + } + + /** + * Indicated whether an embedded http server should be started and used + */ + public boolean useEmbeddedHttpServer() { + return System.getProperty("useEmbeddedHttpServer", "false").equals("true"); + } + + /** + * Hooks up the message bus. + */ + protected void setupMessageBus() { + if (useEmbeddedMessageBus()) { + if (messageBus == null) { + messageBus = new SimpleMessageBus(); + } + } + } + + /** + * Shutdown the message bus. + */ + private void teardownMessageBus() { + MessageBusManager.clear(); + if (messageBus != null) { + try { + messageBus.close(); + messageBus = null; + } catch (JMSException e) { + throw new RuntimeException(e); + } + } + + if (broker != null) { + try { + broker.stop(); + broker = null; + } catch (Exception e) { + // No reason to pollute the test output with this + } + } + } + + /** + * Shutdown the embedded http server if any. + */ + protected void teardownHttpServer() { + if (useEmbeddedHttpServer()) { + server.stop(); + } + } + + /** + * Returns the postfix string to use when accessing user specific topics, which is the mechanism we use in the + * bit repository tests. + * + * @return The string to postfix all topix names with. + */ + protected String getTopicPostfix() { + return "-" + System.getProperty("user.name"); + } + + protected String getComponentID() { + return getClass().getSimpleName(); + } + + protected String createDate() { + return Long.toString(System.currentTimeMillis()); + } + + protected SecurityManager createSecurityManager() { + return new DummySecurityManager(); + } + +} \ No newline at end of file diff --git a/bitrepository-reference-pillar/src/test/resources/conf/ReferenceSettings.xml b/bitrepository-reference-pillar/src/test/resources/conf/ReferenceSettings.xml index c828809f9..ca72807bc 100644 --- a/bitrepository-reference-pillar/src/test/resources/conf/ReferenceSettings.xml +++ b/bitrepository-reference-pillar/src/test/resources/conf/ReferenceSettings.xml @@ -37,6 +37,8 @@ EmbeddedReferencePillar FILE + DefaultCollection + NonDefaultCollection target/reference1pillar/test-archive 1000000000 diff --git a/bitrepository-service/src/test/java/org/bitrepository/service/ServiceSettingsProviderTest.java b/bitrepository-service/src/test/java/org/bitrepository/service/ServiceSettingsProviderTest.java index 96e8ebff6..7a77a0ff5 100644 --- a/bitrepository-service/src/test/java/org/bitrepository/service/ServiceSettingsProviderTest.java +++ b/bitrepository-service/src/test/java/org/bitrepository/service/ServiceSettingsProviderTest.java @@ -26,8 +26,10 @@ import org.bitrepository.common.settings.SettingsProvider; import org.bitrepository.common.settings.XMLFileSettingsLoader; import org.bitrepository.settings.referencesettings.ServiceType; -import org.testng.Assert; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + /** * jaccept report generating test of whether ServiceSettingsProvider actually knows the enum ServiceType. @@ -36,34 +38,35 @@ public class ServiceSettingsProviderTest { private static final String PATH_TO_TEST_SETTINGS = "settings/xml/bitrepository-devel"; - @Test(groups = {"regressiontest"}) + @Test + @Tag("regressiontest") public void componentIDTest() { SettingsProvider settingsLoader = new ServiceSettingsProvider(new XMLFileSettingsLoader(PATH_TO_TEST_SETTINGS), ServiceType.ALARM_SERVICE); Settings settings = settingsLoader.getSettings(); - Assert.assertEquals( + Assertions.assertEquals( settings.getReferenceSettings().getAlarmServiceSettings().getID(), settings.getComponentID()); settingsLoader = new ServiceSettingsProvider(new XMLFileSettingsLoader(PATH_TO_TEST_SETTINGS), ServiceType.AUDIT_TRAIL_SERVICE); settings = settingsLoader.getSettings(); - Assert.assertEquals( + Assertions.assertEquals( settings.getReferenceSettings().getAuditTrailServiceSettings().getID(), settings.getComponentID()); settingsLoader = new ServiceSettingsProvider(new XMLFileSettingsLoader(PATH_TO_TEST_SETTINGS), ServiceType.INTEGRITY_SERVICE); settings = settingsLoader.getSettings(); - Assert.assertEquals( + Assertions.assertEquals( settings.getReferenceSettings().getIntegrityServiceSettings().getID(), settings.getComponentID()); settingsLoader = new ServiceSettingsProvider(new XMLFileSettingsLoader(PATH_TO_TEST_SETTINGS), ServiceType.MONITORING_SERVICE); settings = settingsLoader.getSettings(); - Assert.assertEquals( + Assertions.assertEquals( settings.getReferenceSettings().getMonitoringServiceSettings().getID(), settings.getComponentID()); } diff --git a/bitrepository-service/src/test/java/org/bitrepository/service/audit/AuditTrailContributorDatabaseMigrationTest.java b/bitrepository-service/src/test/java/org/bitrepository/service/audit/AuditTrailContributorDatabaseMigrationTest.java index 0be217d7c..74cac052f 100644 --- a/bitrepository-service/src/test/java/org/bitrepository/service/audit/AuditTrailContributorDatabaseMigrationTest.java +++ b/bitrepository-service/src/test/java/org/bitrepository/service/audit/AuditTrailContributorDatabaseMigrationTest.java @@ -5,16 +5,16 @@ * Copyright (C) 2010 - 2013 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% @@ -29,9 +29,10 @@ import org.bitrepository.service.database.DerbyDatabaseDestroyer; import org.bitrepository.settings.referencesettings.DatabaseSpecifics; import org.jaccept.structure.ExtendedTestCase; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; import java.io.File; @@ -39,23 +40,25 @@ import static org.bitrepository.service.audit.AuditDatabaseConstants.DATABASE_VERSION_ENTRY; import static org.bitrepository.service.audit.AuditDatabaseConstants.FILE_FILE_ID; import static org.bitrepository.service.audit.AuditDatabaseConstants.FILE_TABLE; -import static org.testng.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; + -/** Test database migration. Generates jaccept reports. +/** + * Test database migration. Generates jaccept reports. * */ public class AuditTrailContributorDatabaseMigrationTest extends ExtendedTestCase { protected Settings settings; - + static final String PATH_TO_DATABASE_UNPACKED = "target/test/audits/auditcontributerdb-v1"; static final String PATH_TO_DATABASE_JAR_FILE = "src/test/resources/auditcontributerdb-v1.jar"; - + static final String FILE_ID = "default-file-id"; - @BeforeMethod (alwaysRun = true) + @BeforeEach public void setup() throws Exception { settings = TestSettingsProvider.reloadSettings("ReferencePillarTest"); - + settings.getReferenceSettings().getPillarSettings().getAuditTrailContributerDatabase().setDatabaseURL( "jdbc:derby:" + PATH_TO_DATABASE_UNPACKED + "/auditcontributerdb"); @@ -65,13 +68,15 @@ public void setup() throws Exception { FileUtils.unzip(new File(PATH_TO_DATABASE_JAR_FILE), FileUtils.retrieveDirectory(PATH_TO_DATABASE_UNPACKED)); } - - @AfterMethod (alwaysRun = true) + + @AfterEach public void cleanup() throws Exception { FileUtils.deleteDirIfExists(new File(PATH_TO_DATABASE_UNPACKED)); } - - @Test( groups = {"regressiontest", "databasetest"}) + + @Test + @Tag("regressiontest") + @Tag("databasetest") public void testMigratingAuditContributorDatabase() { addDescription("Tests that the database can be migrated to latest version with the provided scripts."); DBConnector connector = new DBConnector( @@ -80,22 +85,22 @@ public void testMigratingAuditContributorDatabase() { addStep("Validate setup", "File table and audit table has version 1 "); String extractVersionSql = "SELECT version FROM tableversions WHERE tablename = ?"; int fileTableVersionBefore = DatabaseUtils.selectIntValue(connector, extractVersionSql, FILE_TABLE); - assertEquals(fileTableVersionBefore, 1, "File table before migration"); + assertEquals(1, fileTableVersionBefore, "File table before migration"); int auditTableVersionBefore = DatabaseUtils.selectIntValue(connector, extractVersionSql, AUDIT_TRAIL_AUDIT); - assertEquals(auditTableVersionBefore, 1, "Table version before migration"); - + assertEquals(1, auditTableVersionBefore, "Table version before migration"); + addStep("Ingest a entry to the database without the collection id", "works only in version 1."); String sqlInsert = "INSERT INTO " + FILE_TABLE + " ( " + FILE_FILE_ID + " ) VALUES ( ? )"; DatabaseUtils.executeStatement(connector, sqlInsert, FILE_ID); - + addStep("Perform migration", "File table has version 2, audit table version 5 and database-version is 5"); AuditTrailContributorDatabaseMigrator migrator = new AuditTrailContributorDatabaseMigrator(connector); migrator.migrate(); int fileTableVersionAfter = DatabaseUtils.selectIntValue(connector, extractVersionSql, FILE_TABLE); - assertEquals(fileTableVersionAfter, 2, "Table version after migration"); + assertEquals(2, fileTableVersionAfter, "Table version after migration"); int auditTableVersionAfter = DatabaseUtils.selectIntValue(connector, extractVersionSql, AUDIT_TRAIL_AUDIT); - assertEquals(auditTableVersionAfter, 5, "Table version after migration"); + assertEquals(5, auditTableVersionAfter, "Table version after migration"); int dbTableVersionAfter = DatabaseUtils.selectIntValue(connector, extractVersionSql, DATABASE_VERSION_ENTRY); - assertEquals(dbTableVersionAfter, AuditTrailContributorDatabaseMigrator.CURRENT_VERSION, "Table version after migration"); + assertEquals(AuditTrailContributorDatabaseMigrator.CURRENT_VERSION, dbTableVersionAfter, "Table version after migration"); } } diff --git a/bitrepository-service/src/test/java/org/bitrepository/service/audit/AuditTrailContributorDatabaseTest.java b/bitrepository-service/src/test/java/org/bitrepository/service/audit/AuditTrailContributorDatabaseTest.java index f7e905d03..35a02d8e1 100644 --- a/bitrepository-service/src/test/java/org/bitrepository/service/audit/AuditTrailContributorDatabaseTest.java +++ b/bitrepository-service/src/test/java/org/bitrepository/service/audit/AuditTrailContributorDatabaseTest.java @@ -5,16 +5,16 @@ * Copyright (C) 2010 - 2012 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% @@ -30,22 +30,25 @@ import org.bitrepository.service.database.DerbyDatabaseDestroyer; import org.bitrepository.settings.referencesettings.DatabaseSpecifics; import org.jaccept.structure.ExtendedTestCase; -import org.testng.Assert; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; -/** Run audit trail contributor database test using Derby. Generates jaccept reports. */ +/** + * Run audit trail contributor database test using Derby. Generates jaccept reports. + */ public class AuditTrailContributorDatabaseTest extends ExtendedTestCase { private Settings settings; private DatabaseSpecifics databaseSpecifics; private String firstCollectionID; - + private static final String DEFAULT_ACTOR = "ACTOR"; private static final String DEFAULT_INFO = "Adding a info"; private static final String DEFAULT_AUDIT_TRAIL_MESSAGE = "AuditTrail"; @@ -54,7 +57,7 @@ public class AuditTrailContributorDatabaseTest extends ExtendedTestCase { private static final String FILE_ID_1 = "FILE-ID-1"; private static final String FILE_ID_2 = "FILE-ID-2"; - @BeforeMethod (alwaysRun = true) + @BeforeEach public void setup() throws Exception { settings = TestSettingsProvider.reloadSettings(getClass().getSimpleName()); @@ -69,7 +72,9 @@ public void setup() throws Exception { firstCollectionID = settings.getCollections().get(0).getID(); } - @Test(groups = {"regressiontest", "databasetest"}) + @Test + @Tag("regressiontest") + @Tag("databasetest") public void testAuditTrailDatabaseExtraction() throws Exception { addDescription("Testing the basic functions of the audit trail database interface."); addStep("Setup varibles and the database connection.", "No errors."); @@ -83,50 +88,52 @@ public void testAuditTrailDatabaseExtraction() throws Exception { daba.addAuditEvent(firstCollectionID, FILE_ID_2, DEFAULT_ACTOR, DEFAULT_INFO, DEFAULT_AUDIT_TRAIL_MESSAGE, FileAction.FILE_MOVED, DEFAULT_OPERATION_ID, DEFAULT_CERTIFICATE_ID); daba.addAuditEvent(firstCollectionID, FILE_ID_2, DEFAULT_ACTOR, DEFAULT_INFO, DEFAULT_AUDIT_TRAIL_MESSAGE, FileAction.FAILURE, DEFAULT_OPERATION_ID, DEFAULT_CERTIFICATE_ID); daba.addAuditEvent(firstCollectionID, FILE_ID_2, DEFAULT_ACTOR, DEFAULT_INFO, DEFAULT_AUDIT_TRAIL_MESSAGE, FileAction.INCONSISTENCY, DEFAULT_OPERATION_ID, DEFAULT_CERTIFICATE_ID); - + addStep("Test extracting all the events", "Should be all 5 events."); AuditTrailDatabaseResults events = daba.getAudits(firstCollectionID, null, null, null, null, null, null); - Assert.assertEquals(events.getAuditTrailEvents().getAuditTrailEvent().size(), 5); - + Assertions.assertEquals(5, events.getAuditTrailEvents().getAuditTrailEvent().size()); + addStep("Test extracting the events for fileID1", "Should be 2 events."); events = daba.getAudits(firstCollectionID, FILE_ID_1, null, null, null, null, null); - Assert.assertEquals(events.getAuditTrailEvents().getAuditTrailEvent().size(), 2); + Assertions.assertEquals(2, events.getAuditTrailEvents().getAuditTrailEvent().size()); addStep("Test extracting the events for fileID2", "Should be 3 events."); events = daba.getAudits(firstCollectionID, FILE_ID_2, null, null, null, null, null); - Assert.assertEquals(events.getAuditTrailEvents().getAuditTrailEvent().size(), 3); - - addStep("Test extracting the events with the sequence number at least equal to the largest sequence number.", + Assertions.assertEquals(3, events.getAuditTrailEvents().getAuditTrailEvent().size()); + + addStep("Test extracting the events with the sequence number at least equal to the largest sequence number.", "Should be 1 event."); Long seq = daba.extractLargestSequenceNumber(); events = daba.getAudits(firstCollectionID, null, seq, null, null, null, null); - Assert.assertEquals(events.getAuditTrailEvents().getAuditTrailEvent().size(), 1); - + Assertions.assertEquals(1, events.getAuditTrailEvents().getAuditTrailEvent().size()); + addStep("Test extracting the events for fileID1 with sequence number 2 or more", "Should be 1 event."); - events = daba.getAudits(firstCollectionID, FILE_ID_1, seq-3, null, null, null, null); - Assert.assertEquals(events.getAuditTrailEvents().getAuditTrailEvent().size(), 1); + events = daba.getAudits(firstCollectionID, FILE_ID_1, seq - 3, null, null, null, null); + Assertions.assertEquals(1, events.getAuditTrailEvents().getAuditTrailEvent().size()); addStep("Test extracting the events for fileID1 with at most sequence number 2", "Should be 2 events."); - events = daba.getAudits(firstCollectionID, FILE_ID_1, null, seq-3, null, null, null); - Assert.assertEquals(events.getAuditTrailEvents().getAuditTrailEvent().size(), 2); + events = daba.getAudits(firstCollectionID, FILE_ID_1, null, seq - 3, null, null, null); + Assertions.assertEquals(2, events.getAuditTrailEvents().getAuditTrailEvent().size()); addStep("Test extracting at most 3 events", "Should extract 3 events."); events = daba.getAudits(firstCollectionID, null, null, null, null, null, 3L); - Assert.assertEquals(events.getAuditTrailEvents().getAuditTrailEvent().size(), 3); + Assertions.assertEquals(3, events.getAuditTrailEvents().getAuditTrailEvent().size()); addStep("Test extracting at most 1000 events", "Should extract all 5 events."); events = daba.getAudits(firstCollectionID, null, null, null, null, null, 1000L); - Assert.assertEquals(events.getAuditTrailEvents().getAuditTrailEvent().size(), 5); - + Assertions.assertEquals(5, events.getAuditTrailEvents().getAuditTrailEvent().size()); + addStep("Test extracting from another collection", "Should not extract anything."); String secondCollectionID = settings.getCollections().get(1).getID(); events = daba.getAudits(secondCollectionID, null, null, null, null, null, 1000L); - Assert.assertEquals(events.getAuditTrailEvents().getAuditTrailEvent().size(), 0); - + Assertions.assertEquals(0, events.getAuditTrailEvents().getAuditTrailEvent().size()); + dm.getConnector().destroy(); } - - @Test(groups = {"regressiontest", "databasetest"}) + + @Test + @Tag("regressiontest") + @Tag("databasetest") public void testAuditTrailDatabaseExtractionOrder() throws Exception { addDescription("Test the order of extraction"); addStep("Setup variables and database connection", "No errors"); @@ -143,60 +150,62 @@ public void testAuditTrailDatabaseExtractionOrder() throws Exception { addStep("Extract 3 audit-trails", "Should give first 3 audit-trails in order."); AuditTrailDatabaseResults events = daba.getAudits(firstCollectionID, null, null, null, null, null, 3L); - Assert.assertEquals(events.getAuditTrailEvents().getAuditTrailEvent().size(), 3L); - Assert.assertEquals(events.getAuditTrailEvents().getAuditTrailEvent().get(0).getActionOnFile(), FileAction.PUT_FILE); - Assert.assertEquals(events.getAuditTrailEvents().getAuditTrailEvent().get(0).getSequenceNumber().longValue(), 1L); - Assert.assertEquals(events.getAuditTrailEvents().getAuditTrailEvent().get(1).getActionOnFile(), FileAction.CHECKSUM_CALCULATED); - Assert.assertEquals(events.getAuditTrailEvents().getAuditTrailEvent().get(1).getSequenceNumber().longValue(), 2L); - Assert.assertEquals(events.getAuditTrailEvents().getAuditTrailEvent().get(2).getActionOnFile(), FileAction.FILE_MOVED); - Assert.assertEquals(events.getAuditTrailEvents().getAuditTrailEvent().get(2).getSequenceNumber().longValue(), 3L); - + Assertions.assertEquals(3L, events.getAuditTrailEvents().getAuditTrailEvent().size()); + Assertions.assertEquals(FileAction.PUT_FILE, events.getAuditTrailEvents().getAuditTrailEvent().get(0).getActionOnFile()); + Assertions.assertEquals(1L, events.getAuditTrailEvents().getAuditTrailEvent().get(0).getSequenceNumber().longValue()); + Assertions.assertEquals(FileAction.CHECKSUM_CALCULATED, events.getAuditTrailEvents().getAuditTrailEvent().get(1).getActionOnFile()); + Assertions.assertEquals(2L, events.getAuditTrailEvents().getAuditTrailEvent().get(1).getSequenceNumber().longValue()); + Assertions.assertEquals(FileAction.FILE_MOVED, events.getAuditTrailEvents().getAuditTrailEvent().get(2).getActionOnFile()); + Assertions.assertEquals(3L, events.getAuditTrailEvents().getAuditTrailEvent().get(2).getSequenceNumber().longValue()); + long firstSeq = events.getAuditTrailEvents().getAuditTrailEvent().get(0).getSequenceNumber().longValue(); addStep("Extract 3 audit-trails, with larger seq-number than the first", "Should give audit-trail #2, #3, #4"); - events = daba.getAudits(firstCollectionID, null, firstSeq+1, null, null, null, 3L); - Assert.assertEquals(events.getAuditTrailEvents().getAuditTrailEvent().size(), 3L); - Assert.assertEquals(events.getAuditTrailEvents().getAuditTrailEvent().get(0).getActionOnFile(), FileAction.CHECKSUM_CALCULATED); - Assert.assertEquals(events.getAuditTrailEvents().getAuditTrailEvent().get(1).getActionOnFile(), FileAction.FILE_MOVED); - Assert.assertEquals(events.getAuditTrailEvents().getAuditTrailEvent().get(2).getActionOnFile(), FileAction.FAILURE); - + events = daba.getAudits(firstCollectionID, null, firstSeq + 1, null, null, null, 3L); + Assertions.assertEquals(3L, events.getAuditTrailEvents().getAuditTrailEvent().size()); + Assertions.assertEquals(FileAction.CHECKSUM_CALCULATED, events.getAuditTrailEvents().getAuditTrailEvent().get(0).getActionOnFile()); + Assertions.assertEquals(FileAction.FILE_MOVED, events.getAuditTrailEvents().getAuditTrailEvent().get(1).getActionOnFile()); + Assertions.assertEquals(FileAction.FAILURE, events.getAuditTrailEvents().getAuditTrailEvent().get(2).getActionOnFile()); + dm.getConnector().destroy(); } - + public void contributorDatabaseCorrectTimestampTest() throws ParseException { addDescription("Testing the correct ingest and extraction of audittrail dates"); DatabaseManager dm = new AuditDatabaseManager(databaseSpecifics); AuditTrailContributorDAO daba = new DerbyAuditTrailContributorDAO(dm); daba.initialize(settings.getComponentID()); - + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX", Locale.ROOT); Date summertimeTS = sdf.parse("2015-10-25T02:59:54.000+02:00"); Date summertimeUnix = new Date(1445734794000L); - Assert.assertEquals(summertimeTS, summertimeUnix); - + Assertions.assertEquals(summertimeTS, summertimeUnix); + Date wintertimeTS = sdf.parse("2015-10-25T02:59:54.000+01:00"); Date wintertimeUnix = new Date(1445738394000L); - Assert.assertEquals(wintertimeTS, wintertimeUnix); - - daba.addAuditEvent(firstCollectionID, "summertime", summertimeTS, "actor", "info", "auditTrail", + Assertions.assertEquals(wintertimeTS, wintertimeUnix); + + daba.addAuditEvent(firstCollectionID, "summertime", summertimeTS, "actor", "info", "auditTrail", FileAction.OTHER, null, null); - daba.addAuditEvent(firstCollectionID, "wintertime", wintertimeTS, "actor", "info", "auditTrail", + daba.addAuditEvent(firstCollectionID, "wintertime", wintertimeTS, "actor", "info", "auditTrail", FileAction.OTHER, null, null); - + AuditTrailDatabaseResults events = daba.getAudits(firstCollectionID, "summertime", null, null, null, null, 2L); - Assert.assertEquals(events.getAuditTrailEvents().getAuditTrailEvent().size(), 1, events.toString()); - Assert.assertEquals(CalendarUtils.convertFromXMLGregorianCalendar( - events.getAuditTrailEvents().getAuditTrailEvent().get(0).getActionDateTime()), summertimeUnix); - + Assertions.assertEquals(1, events.getAuditTrailEvents().getAuditTrailEvent().size(), events.toString()); + Assertions.assertEquals(CalendarUtils.convertFromXMLGregorianCalendar( + events.getAuditTrailEvents().getAuditTrailEvent().get(0).getActionDateTime()), summertimeUnix); + events = daba.getAudits(firstCollectionID, "wintertime", null, null, null, null, 2L); - Assert.assertEquals(events.getAuditTrailEvents().getAuditTrailEvent().size(), 1, events.toString()); - Assert.assertEquals(CalendarUtils.convertFromXMLGregorianCalendar( - events.getAuditTrailEvents().getAuditTrailEvent().get(0).getActionDateTime()), wintertimeUnix); - + Assertions.assertEquals(1, events.getAuditTrailEvents().getAuditTrailEvent().size(), events.toString()); + Assertions.assertEquals(CalendarUtils.convertFromXMLGregorianCalendar( + events.getAuditTrailEvents().getAuditTrailEvent().get(0).getActionDateTime()), wintertimeUnix); + } - - @Test(groups = {"regressiontest", "databasetest"}) + + @Test + @Tag("regressiontest") + @Tag("databasetest") public void testAuditTrailDatabaseIngest() throws Exception { addDescription("Testing the ingest of data."); addStep("Setup varibles and the database connection.", "No errors."); @@ -207,25 +216,25 @@ public void testAuditTrailDatabaseIngest() throws Exception { String operationID = "op1"; String certificateID = "aa"; String veryLongString = ""; - for(int i = 0; i < 255; i++) { + for (int i = 0; i < 255; i++) { veryLongString += i; } DatabaseManager dm = new AuditDatabaseManager(databaseSpecifics); AuditTrailContributorDAO daba = new DerbyAuditTrailContributorDAO(dm); daba.initialize(settings.getComponentID()); - + addStep("Test with all data.", "No failures"); daba.addAuditEvent(firstCollectionID, fileID1, actor, info, auditTrail, FileAction.FAILURE, operationID, certificateID); - + addStep("Test with no collection", "Throws exception"); try { daba.addAuditEvent(null, fileID1, actor, info, auditTrail, FileAction.FAILURE, operationID, certificateID); - Assert.fail("Should throw an exception"); + Assertions.fail("Should throw an exception"); } catch (IllegalArgumentException e) { // expected } - + addStep("Test with with no file id.", "No failures"); daba.addAuditEvent(firstCollectionID, null, actor, info, auditTrail, FileAction.FAILURE, operationID, certificateID); @@ -247,7 +256,7 @@ public void testAuditTrailDatabaseIngest() throws Exception { addStep("Test with with no action.", "Throws exception"); try { daba.addAuditEvent(firstCollectionID, fileID1, actor, info, auditTrail, null, operationID, certificateID); - Assert.fail("Should throw an exception"); + Assertions.fail("Should throw an exception"); } catch (IllegalArgumentException e) { // expected } @@ -255,7 +264,7 @@ public void testAuditTrailDatabaseIngest() throws Exception { addStep("Test with with very large file id.", "Throws exception"); try { daba.addAuditEvent(firstCollectionID, veryLongString, actor, info, auditTrail, FileAction.FAILURE, operationID, certificateID); - Assert.fail("Should throw an exception"); + Assertions.fail("Should throw an exception"); } catch (IllegalStateException e) { // expected } @@ -263,7 +272,7 @@ public void testAuditTrailDatabaseIngest() throws Exception { addStep("Test with with very large actor name.", "Throws exception"); try { daba.addAuditEvent(firstCollectionID, fileID1, veryLongString, info, auditTrail, FileAction.FAILURE, operationID, certificateID); - Assert.fail("Should throw an exception"); + Assertions.fail("Should throw an exception"); } catch (IllegalStateException e) { // expected } @@ -273,7 +282,7 @@ public void testAuditTrailDatabaseIngest() throws Exception { addStep("Test with with very large audittrail.", "No failures"); daba.addAuditEvent(firstCollectionID, fileID1, actor, info, veryLongString, FileAction.FAILURE, operationID, certificateID); - + dm.getConnector().destroy(); } diff --git a/bitrepository-service/src/test/java/org/bitrepository/service/exception/IdentifyContributorExceptionTest.java b/bitrepository-service/src/test/java/org/bitrepository/service/exception/IdentifyContributorExceptionTest.java index 1af69d41c..d2711fcf1 100644 --- a/bitrepository-service/src/test/java/org/bitrepository/service/exception/IdentifyContributorExceptionTest.java +++ b/bitrepository-service/src/test/java/org/bitrepository/service/exception/IdentifyContributorExceptionTest.java @@ -5,16 +5,16 @@ * Copyright (C) 2010 - 2012 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% @@ -23,8 +23,10 @@ import org.bitrepository.bitrepositoryelements.ResponseCode; import org.jaccept.structure.ExtendedTestCase; -import org.testng.Assert; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + /** * jaccept steps to validate that the exception thrown is the exception thrown. @@ -32,36 +34,37 @@ public class IdentifyContributorExceptionTest extends ExtendedTestCase { private final String TEST_COLLECTION_ID = "test-collection-id"; - @Test(groups = { "regressiontest" }) + @Test + @Tag("regressiontest") public void testIdentifyContributor() throws Exception { addDescription("Test the instantiation of the exception"); addStep("Setup", ""); String errMsg = "TEST-ERROR"; ResponseCode errCode = ResponseCode.FAILURE; String causeMsg = "CAUSE-EXCEPTION"; - + addStep("Try to throw such an exception", "Should be able to be caught and validated"); try { throw new IdentifyContributorException(errCode, errMsg); - } catch(Exception e) { - Assert.assertTrue(e instanceof IdentifyContributorException); - Assert.assertEquals(e.getMessage(), errMsg); - Assert.assertEquals(((IdentifyContributorException) e).getResponseInfo().getResponseCode(), errCode); - Assert.assertEquals(((IdentifyContributorException) e).getResponseInfo().getResponseText(), errMsg); - Assert.assertNull(e.getCause()); + } catch (Exception e) { + Assertions.assertInstanceOf(IdentifyContributorException.class, e); + Assertions.assertEquals(errMsg, e.getMessage()); + Assertions.assertEquals(errCode, ((IdentifyContributorException) e).getResponseInfo().getResponseCode()); + Assertions.assertEquals(errMsg, ((IdentifyContributorException) e).getResponseInfo().getResponseText()); + Assertions.assertNull(e.getCause()); } - + addStep("Throw the exception with an embedded exception", "The embedded exception should be the same."); try { throw new IdentifyContributorException(errCode, errMsg, new IllegalArgumentException(causeMsg)); - } catch(Exception e) { - Assert.assertTrue(e instanceof IdentifyContributorException); - Assert.assertEquals(e.getMessage(), errMsg); - Assert.assertEquals(((IdentifyContributorException) e).getResponseInfo().getResponseCode(), errCode); - Assert.assertEquals(((IdentifyContributorException) e).getResponseInfo().getResponseText(), errMsg); - Assert.assertNotNull(e.getCause()); - Assert.assertTrue(e.getCause() instanceof IllegalArgumentException); - Assert.assertEquals(e.getCause().getMessage(), causeMsg); + } catch (Exception e) { + Assertions.assertInstanceOf(IdentifyContributorException.class, e); + Assertions.assertEquals(errMsg, e.getMessage()); + Assertions.assertEquals(errCode, ((IdentifyContributorException) e).getResponseInfo().getResponseCode()); + Assertions.assertEquals(errMsg, ((IdentifyContributorException) e).getResponseInfo().getResponseText()); + Assertions.assertNotNull(e.getCause()); + Assertions.assertInstanceOf(IllegalArgumentException.class, e.getCause()); + Assertions.assertEquals(causeMsg, e.getCause().getMessage()); } - } + } } diff --git a/bitrepository-service/src/test/java/org/bitrepository/service/exception/IllegalOperationExceptionTest.java b/bitrepository-service/src/test/java/org/bitrepository/service/exception/IllegalOperationExceptionTest.java index 111596fe7..3543306fe 100644 --- a/bitrepository-service/src/test/java/org/bitrepository/service/exception/IllegalOperationExceptionTest.java +++ b/bitrepository-service/src/test/java/org/bitrepository/service/exception/IllegalOperationExceptionTest.java @@ -5,16 +5,16 @@ * Copyright (C) 2010 - 2012 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% @@ -23,12 +23,14 @@ import org.bitrepository.bitrepositoryelements.ResponseCode; import org.jaccept.structure.ExtendedTestCase; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertNotNull; -import static org.testng.Assert.assertNull; -import static org.testng.Assert.assertTrue; /** * Test that IllegalOperationException behaves as expected. @@ -36,8 +38,9 @@ public class IllegalOperationExceptionTest extends ExtendedTestCase { private final String TEST_COLLECTION_ID = "test-collection-id"; - - @Test(groups = { "regressiontest" }) + + @Test + @Tag("regressiontest") public void testIdentifyContributor() throws Exception { addDescription("Test the instantiation of the exception"); addStep("Setup", ""); @@ -45,33 +48,33 @@ public void testIdentifyContributor() throws Exception { String FileID = "FILE-ID"; ResponseCode errCode = ResponseCode.FAILURE; String causeMsg = "CAUSE-EXCEPTION"; - + addStep("Try to throw such an exception", "Should be able to be caught and validated"); try { throw new IllegalOperationException(errCode, errMsg, FileID); - } catch(Exception e) { - assertTrue(e instanceof IllegalOperationException); - assertEquals(e.getMessage(), errMsg); - assertEquals(((IllegalOperationException) e).getResponseInfo().getResponseCode(), errCode); - assertEquals(((IllegalOperationException) e).getResponseInfo().getResponseText(), errMsg); + } catch (Exception e) { + assertInstanceOf(IllegalOperationException.class, e); + assertEquals(errMsg, e.getMessage()); + assertEquals(errCode, ((IllegalOperationException) e).getResponseInfo().getResponseCode()); + assertEquals(errMsg, ((IllegalOperationException) e).getResponseInfo().getResponseText()); assertNull(e.getCause()); - assertEquals(((IllegalOperationException) e).getFileId(), FileID); + assertEquals(FileID, ((IllegalOperationException) e).getFileId()); } - + addStep("Throw the exception with an embedded exception", "The embedded exception should be the same."); try { throw new IllegalOperationException(errCode, errMsg, FileID, new IllegalArgumentException(causeMsg)); - } catch(Exception e) { - assertTrue(e instanceof IllegalOperationException); - assertTrue(e instanceof RequestHandlerException); - assertEquals(e.getMessage(), errMsg); - assertEquals(((IllegalOperationException) e).getResponseInfo().getResponseCode(), errCode); - assertEquals(((IllegalOperationException) e).getResponseInfo().getResponseText(), errMsg); + } catch (Exception e) { + assertInstanceOf(IllegalOperationException.class, e); + assertInstanceOf(RequestHandlerException.class, e); + assertEquals(errMsg, e.getMessage()); + assertEquals(errCode, ((IllegalOperationException) e).getResponseInfo().getResponseCode()); + assertEquals(errMsg, ((IllegalOperationException) e).getResponseInfo().getResponseText()); assertNotNull(e.getCause()); - assertTrue(e.getCause() instanceof IllegalArgumentException); - assertEquals(e.getCause().getMessage(), causeMsg); - assertNotNull(((RequestHandlerException) e).toString()); - assertEquals(((IllegalOperationException) e).getFileId(), FileID); + assertInstanceOf(IllegalArgumentException.class, e.getCause()); + assertEquals(causeMsg, e.getCause().getMessage()); + assertNotNull(e.toString()); + assertEquals(FileID, ((IllegalOperationException) e).getFileId()); } } } diff --git a/bitrepository-service/src/test/java/org/bitrepository/service/exception/InvalidMessageExceptionTest.java b/bitrepository-service/src/test/java/org/bitrepository/service/exception/InvalidMessageExceptionTest.java index 45aad12db..322ea4b55 100644 --- a/bitrepository-service/src/test/java/org/bitrepository/service/exception/InvalidMessageExceptionTest.java +++ b/bitrepository-service/src/test/java/org/bitrepository/service/exception/InvalidMessageExceptionTest.java @@ -5,16 +5,16 @@ * Copyright (C) 2010 - 2012 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% @@ -24,61 +24,64 @@ import org.bitrepository.bitrepositoryelements.ResponseCode; import org.bitrepository.bitrepositoryelements.ResponseInfo; import org.jaccept.structure.ExtendedTestCase; -import org.testng.Assert; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + /** * Test that InvalidMessageException works as expected. */ public class InvalidMessageExceptionTest extends ExtendedTestCase { private final String TEST_COLLECTION_ID = "test-collection-id"; - - @Test(groups = { "regressiontest" }) + + @Test + @Tag("regressiontest") public void testIdentifyContributor() throws Exception { addDescription("Test the instantiation of the exception"); addStep("Setup", ""); String errMsg = "TEST-ERROR"; ResponseCode errCode = ResponseCode.FAILURE; String causeMsg = "CAUSE-EXCEPTION"; - + addStep("Try to throw such an exception", "Should be able to be caught and validated"); try { throw new InvalidMessageException(errCode, errMsg); - } catch(Exception e) { - Assert.assertTrue(e instanceof InvalidMessageException); - Assert.assertEquals(e.getMessage(), errMsg); - Assert.assertEquals(((InvalidMessageException) e).getResponseInfo().getResponseCode(), errCode); - Assert.assertEquals(((InvalidMessageException) e).getResponseInfo().getResponseText(), errMsg); - Assert.assertNull(e.getCause()); + } catch (Exception e) { + Assertions.assertInstanceOf(InvalidMessageException.class, e); + Assertions.assertEquals(errMsg, e.getMessage()); + Assertions.assertEquals(errCode, ((InvalidMessageException) e).getResponseInfo().getResponseCode()); + Assertions.assertEquals(errMsg, ((InvalidMessageException) e).getResponseInfo().getResponseText()); + Assertions.assertNull(e.getCause()); } - + addStep("Throw the exception with an embedded exception", "The embedded exception should be the same."); try { throw new InvalidMessageException(errCode, errMsg, new IllegalArgumentException(causeMsg)); - } catch(Exception e) { - Assert.assertTrue(e instanceof InvalidMessageException); - Assert.assertTrue(e instanceof RequestHandlerException); - Assert.assertEquals(e.getMessage(), errMsg); - Assert.assertEquals(((InvalidMessageException) e).getResponseInfo().getResponseCode(), errCode); - Assert.assertEquals(((InvalidMessageException) e).getResponseInfo().getResponseText(), errMsg); - Assert.assertNotNull(e.getCause()); - Assert.assertTrue(e.getCause() instanceof IllegalArgumentException); - Assert.assertEquals(e.getCause().getMessage(), causeMsg); - Assert.assertNotNull(((RequestHandlerException) e).toString()); + } catch (Exception e) { + Assertions.assertInstanceOf(InvalidMessageException.class, e); + Assertions.assertInstanceOf(RequestHandlerException.class, e); + Assertions.assertEquals(errMsg, e.getMessage()); + Assertions.assertEquals(errCode, ((InvalidMessageException) e).getResponseInfo().getResponseCode()); + Assertions.assertEquals(errMsg, ((InvalidMessageException) e).getResponseInfo().getResponseText()); + Assertions.assertNotNull(e.getCause()); + Assertions.assertInstanceOf(IllegalArgumentException.class, e.getCause()); + Assertions.assertEquals(causeMsg, e.getCause().getMessage()); + Assertions.assertNotNull(e.toString()); } - + addStep("Throw the exception with a ResponseInfo", "Should be caught and validated"); try { ResponseInfo ri = new ResponseInfo(); ri.setResponseCode(errCode); ri.setResponseText(errMsg); throw new InvalidMessageException(ri); - } catch(Exception e) { - Assert.assertTrue(e instanceof InvalidMessageException); - Assert.assertEquals(e.getMessage(), errMsg); - Assert.assertEquals(((InvalidMessageException) e).getResponseInfo().getResponseCode(), errCode); - Assert.assertEquals(((InvalidMessageException) e).getResponseInfo().getResponseText(), errMsg); - Assert.assertNull(e.getCause()); + } catch (Exception e) { + Assertions.assertInstanceOf(InvalidMessageException.class, e); + Assertions.assertEquals(errMsg, e.getMessage()); + Assertions.assertEquals(errCode, ((InvalidMessageException) e).getResponseInfo().getResponseCode()); + Assertions.assertEquals(errMsg, ((InvalidMessageException) e).getResponseInfo().getResponseText()); + Assertions.assertNull(e.getCause()); } } } diff --git a/bitrepository-webclient/src/main/java/org/bitrepository/utils/LogbackConfigLoader.java b/bitrepository-webclient/src/main/java/org/bitrepository/utils/LogbackConfigLoader.java index 18b70c0d2..3af5ae76f 100644 --- a/bitrepository-webclient/src/main/java/org/bitrepository/utils/LogbackConfigLoader.java +++ b/bitrepository-webclient/src/main/java/org/bitrepository/utils/LogbackConfigLoader.java @@ -31,7 +31,7 @@ import java.io.IOException; public class LogbackConfigLoader { - private Logger log = LoggerFactory.getLogger(LogbackConfigLoader.class); + private final Logger log = LoggerFactory.getLogger(LogbackConfigLoader.class); public LogbackConfigLoader(String configFileLocation) throws IOException, JoranException{ LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory(); diff --git a/bitrepository-webclient/src/main/java/org/bitrepository/webservice/Reposervice.java b/bitrepository-webclient/src/main/java/org/bitrepository/webservice/Reposervice.java index 8a7a4d657..c7ecf31de 100644 --- a/bitrepository-webclient/src/main/java/org/bitrepository/webservice/Reposervice.java +++ b/bitrepository-webclient/src/main/java/org/bitrepository/webservice/Reposervice.java @@ -22,7 +22,6 @@ package org.bitrepository.webservice; import com.fasterxml.jackson.core.JsonFactory; -import com.fasterxml.jackson.core.JsonGenerationException; import com.fasterxml.jackson.core.JsonGenerator; import org.bitrepository.BasicClient; import org.bitrepository.BasicClientFactory; @@ -47,7 +46,7 @@ @Path("/reposervice") public class Reposervice { - private BasicClient client; + private final BasicClient client; public Reposervice() { @@ -99,7 +98,7 @@ public String getConfigurationOverview() throws IOException { return writer.toString(); } - private void writeCollectionsArray(JsonGenerator jg) throws JsonGenerationException, IOException { + private void writeCollectionsArray(JsonGenerator jg) throws IOException { List collections = client.getSettings().getRepositorySettings().getCollections().getCollection(); jg.writeArrayFieldStart("collections"); for(Collection c : collections) { @@ -117,7 +116,7 @@ private void writeCollectionsArray(JsonGenerator jg) throws JsonGenerationExcept jg.writeEndArray(); } - private void writeProtocolSettingsObj(JsonGenerator jg) throws JsonGenerationException, IOException { + private void writeProtocolSettingsObj(JsonGenerator jg) throws IOException { ProtocolSettings protocolSettings = client.getSettings().getRepositorySettings().getProtocolSettings(); jg.writeObjectFieldStart("protocolSettings"); jg.writeObjectField("Allowed fileID pattern", protocolSettings.getAllowedFileIDPattern()); diff --git a/pom.xml b/pom.xml index d74adb031..6d776fde9 100644 --- a/pom.xml +++ b/pom.xml @@ -1,514 +1,529 @@ - + - 4.0.0 - org.bitrepository.reference - bitrepository-parent - 1.12-SNAPSHOT + 4.0.0 + org.bitrepository.reference + bitrepository-parent + 1.12-SNAPSHOT - - org.sbforge - sbforge-parent - 22 - + + org.sbforge + sbforge-parent + 22 + - Bitrepository + Bitrepository - pom + pom - - bitrepository-reference-settings - bitrepository-core - bitrepository-client - bitrepository-service - bitrepository-integrity-service - bitrepository-alarm-service - bitrepository-audit-trail-service - bitrepository-reference-pillar - bitrepository-monitoring-service - bitrepository-integration - bitrepository-webclient - + + bitrepository-reference-settings + bitrepository-core + bitrepository-client + bitrepository-service + bitrepository-integrity-service + bitrepository-alarm-service + bitrepository-audit-trail-service + bitrepository-reference-pillar + bitrepository-monitoring-service + bitrepository-integration + bitrepository-webclient + - - - sbforge-nexus - https://sbforge.org/nexus/content/groups/public - - true - - - true - - - + + + sbforge-nexus + https://sbforge.org/nexus/content/groups/public + + true + + + true + + + - - - Mikis Seth Sørensen - mss - - Former Employee - - - - Kim Agerbo Christensen - ktc - - Former Employee - - - - Jonas Lindberg Frellesen - jolf - - Former Employee - - - - Asger Askov Blekinge - asga@kb.dk - The Danish Royal Library - https://www.kb.dk/en - - Developer - - - - Rasmus Bohl Kristensen - rbkr@kb.dk - The Danish Royal Library - https://www.kb.dk/en - - Developer - - - - Mathias Søby Jensen - masj@kb.dk - The Danish Royal Library - https://www.kb.dk/en - - Developer - - - + + + Mikis Seth Sørensen + mss + + Former Employee + + + + Kim Agerbo Christensen + ktc + + Former Employee + + + + Jonas Lindberg Frellesen + jolf + + Former Employee + + + + Asger Askov Blekinge + asga@kb.dk + The Danish Royal Library + https://www.kb.dk/en + + Developer + + + + Rasmus Bohl Kristensen + rbkr@kb.dk + The Danish Royal Library + https://www.kb.dk/en + + Developer + + + + Mathias Søby Jensen + masj@kb.dk + The Danish Royal Library + https://www.kb.dk/en + + Developer + + + - 2010 + 2010 - - - LGPL v2.1 - repo - http://www.gnu.org/licenses/lgpl-2.1.txt - - + + + LGPL v2.1 + repo + http://www.gnu.org/licenses/lgpl-2.1.txt + + - - JIRA - https://sbforge.org/jira/browse/BITMAG - + + JIRA + https://sbforge.org/jira/browse/BITMAG + - - Jenkins - https://sbforge.org/jenkins/ - + + Jenkins + https://sbforge.org/jenkins/ + - The Bit Repository system enables long-term preservation of data in a distributed, highly redundant - architecture. The data integrity is ensured by using multiple, independently developed data storage systems (Pillars) - across different organizations, together with functionality for maintaining the integrity of the data over time. - - https://sbforge.org/display/BITMAG - - - The State and University Library, The Royal Library and The State Archives, Denmark + The Bit Repository system enables long-term preservation of data in a distributed, highly redundant + architecture. The data integrity is ensured by using multiple, independently developed data storage systems + (Pillars) + across different organizations, together with functionality for maintaining the integrity of the data over + time. + https://sbforge.org/display/BITMAG - - - - https://sbforge.org/fisheye/browse/bitrepository-reference - scm:git:git@github.com:bitrepository/reference.git - scm:git:git@github.com:bitrepository/reference.git - HEAD - - - - - org.slf4j - slf4j-api - ${slf4j.version} - - - ch.qos.logback - logback-classic - 1.2.3 - - - - org.jvnet.jaxb2_commons - jaxb2-basics-runtime - 0.11.1 - - - - - jakarta.xml.bind - jakarta.xml.bind-api - 2.3.3 - - - - jakarta.activation - jakarta.activation-api - 1.2.2 - - - - org.glassfish.jaxb - jaxb-runtime - 2.3.6 - runtime - - - - org.testng - testng - 7.1.0 - test - - - org.mockito - mockito-core - 3.3.3 - test - - - - org.slf4j - jul-to-slf4j - ${slf4j.version} - - - org.slf4j - log4j-over-slf4j - ${slf4j.version} - - - org.slf4j - jcl-over-slf4j - ${slf4j.version} - - - org.jaccept - jaccept-core - 0.4 - test - - + + The State and University Library, The Royal Library and The State Archives, Denmark + https://sbforge.org/display/BITMAG + - - - - org.apache.maven.plugins - maven-enforcer-plugin - 3.0.0-M3 - - - enforce-maven - - enforce - - - - - 2.2.1 - - - - - - - - org.codehaus.mojo - license-maven-plugin - - true - true - true - lgpl_v2_1 - true - false - - **/*.java - **/*.xsd - **/*.sql - - - xml - - - + + https://sbforge.org/fisheye/browse/bitrepository-reference + scm:git:git@github.com:bitrepository/reference.git + scm:git:git@github.com:bitrepository/reference.git + HEAD + - - maven-surefire-plugin - - regressiontest - random - - - - maven-jar-plugin - - - - true - true - - - value - - - true - - - - - test-jar - - - - - - maven-release-plugin - - - true - - - - maven-war-plugin - - - - WEB-INF/lib/commons-logging-*.jar, - %regex[WEB-INF/lib/log4j-(?!over-slf4j).*.jar] - - false - - - - org.jacoco - jacoco-maven-plugin - 0.8.8 - - - - prepare-agent - - - - report - test - - report - - - - - - - - - org.codehaus.mojo - license-maven-plugin - 2.0.0 - - - maven-compiler-plugin - 3.8.1 - - - maven-source-plugin - 3.2.1 - - - maven-javadoc-plugin - 3.2.0 - - - maven-release-plugin - 3.0.0-M1 - - - maven-jar-plugin - 3.2.0 - - - maven-surefire-plugin - 3.0.0-M4 - - - maven-failsafe-plugin - 3.0.0-M4 - - - maven-war-plugin - 3.3.0 - - - maven-assembly-plugin - 3.3.0 - - - maven-resources-plugin - 3.1.0 - - - maven-remote-resources-plugin - 1.7.0 - - - maven-clean-plugin - 3.1.0 - - - maven-install-plugin - 3.0.0-M1 - - - maven-deploy-plugin - 3.0.0-M1 - - - maven-dependency-plugin - 3.1.2 - - - org.codehaus.mojo - jaxb2-maven-plugin - 2.5.0 - - - org.apache.tomcat.maven - tomcat7-maven-plugin - 2.2 - - - org.codehaus.mojo - exec-maven-plugin - 3.0.0 - - - - + + + org.slf4j + slf4j-api + ${slf4j.version} + + + ch.qos.logback + logback-classic + 1.2.3 + + + + org.jvnet.jaxb2_commons + jaxb2-basics-runtime + 0.11.1 + + + + + jakarta.xml.bind + jakarta.xml.bind-api + 2.3.3 + + + + jakarta.activation + jakarta.activation-api + 1.2.2 + + + + org.glassfish.jaxb + jaxb-runtime + 2.3.6 + runtime + + + org.junit.jupiter + junit-jupiter + 5.13.4 + test + + + + + + + + + org.junit.platform + junit-platform-suite-engine + 1.13.4 + test + + + org.mockito + mockito-core + 3.3.3 + test + + + + org.slf4j + jul-to-slf4j + ${slf4j.version} + + + org.slf4j + log4j-over-slf4j + ${slf4j.version} + + + org.slf4j + jcl-over-slf4j + ${slf4j.version} + + + org.jaccept + jaccept-core + 0.4 + test + + - - - - org.apache.maven.plugins - maven-project-info-reports-plugin - 3.1.0 - - - org.apache.maven.plugins - maven-checkstyle-plugin - 3.1.1 - - sonarCheckstyle.xml - - - - com.github.spotbugs - spotbugs-maven-plugin - 4.0.0 - - false - - - - org.jacoco - jacoco-maven-plugin - 0.8.5 - - - org.apache.maven.plugins - maven-pmd-plugin - 3.13.0 - - - - - - - deploy - + - - maven-source-plugin - - - attach-sources - - jar - - - - - - maven-javadoc-plugin - - - attach-javadocs - - jar - - - - + + org.apache.maven.plugins + maven-enforcer-plugin + 3.0.0-M3 + + + enforce-maven + + enforce + + + + + 2.2.1 + + + + + + + + org.codehaus.mojo + license-maven-plugin + + true + true + true + lgpl_v2_1 + true + false + + **/*.java + **/*.xsd + **/*.sql + + + xml + + + + + + maven-surefire-plugin + + regressiontest + random + + + + maven-jar-plugin + + + + true + true + + + value + + + true + + + + + test-jar + + + + + + maven-release-plugin + + + true + + + + maven-war-plugin + + + + WEB-INF/lib/commons-logging-*.jar, + %regex[WEB-INF/lib/log4j-(?!over-slf4j).*.jar] + + false + + + + org.jacoco + jacoco-maven-plugin + 0.8.8 + + + + prepare-agent + + + + report + test + + report + + + + - - - - skip-unit-tests - + + + + org.codehaus.mojo + license-maven-plugin + 2.0.0 + + + maven-compiler-plugin + 3.8.1 + + + maven-source-plugin + 3.2.1 + + + maven-javadoc-plugin + 3.2.0 + + + maven-release-plugin + 3.0.0-M1 + + + maven-jar-plugin + 3.2.0 + + + maven-surefire-plugin + 3.0.0-M4 + + + maven-failsafe-plugin + 3.0.0-M4 + + + maven-war-plugin + 3.3.0 + + + maven-assembly-plugin + 3.3.0 + + + maven-resources-plugin + 3.1.0 + + + maven-remote-resources-plugin + 1.7.0 + + + maven-clean-plugin + 3.1.0 + + + maven-install-plugin + 3.0.0-M1 + + + maven-deploy-plugin + 3.0.0-M1 + + + maven-dependency-plugin + 3.1.2 + + + org.codehaus.mojo + jaxb2-maven-plugin + 2.5.0 + + + org.apache.tomcat.maven + tomcat7-maven-plugin + 2.2 + + + org.codehaus.mojo + exec-maven-plugin + 3.0.0 + + + + + + - - maven-surefire-plugin - - - true - - + + org.apache.maven.plugins + maven-project-info-reports-plugin + 3.4.5 + + + org.apache.maven.plugins + maven-checkstyle-plugin + 3.6.0 + + sonarCheckstyle.xml + + + + com.github.spotbugs + spotbugs-maven-plugin + 4.0.0 + + false + + + + org.jacoco + jacoco-maven-plugin + 0.8.12 + + + org.apache.maven.plugins + maven-pmd-plugin + 3.26.0 + - - - + + + + + deploy + + + + maven-source-plugin + + + attach-sources + + jar + + + + + + maven-javadoc-plugin + + + attach-javadocs + + jar + + + + + + + + + skip-unit-tests + + + + maven-surefire-plugin + + + true + + + + + + - - - 11 - 11 - - process-classes - 31 - 14 - 10.14.2.0 - 5.16.4 - 3.3.6 - 2.12.5 - 2.1.6 - 8.0.1 - 4.0.1 - 1.7.30 - dav:https://sbforge.org/maven/bitrepository/sites/reference/${project.version} - UTF-8 - + + + 11 + 11 + + process-classes + + 31 + 14 + 10.14.2.0 + 5.16.4 + 3.3.6 + 2.12.5 + 2.1.6 + 8.0.1 + 4.0.1 + 1.7.30 + dav:https://sbforge.org/maven/bitrepository/sites/reference/${project.version} + + UTF-8 +