diff --git a/pic-sure-api-data/pom.xml b/pic-sure-api-data/pom.xml index c696b0fc9..ab4576eb4 100755 --- a/pic-sure-api-data/pom.xml +++ b/pic-sure-api-data/pom.xml @@ -29,6 +29,11 @@ javaee-api provided + + org.junit.jupiter + junit-jupiter + test + org.hibernate.javax.persistence hibernate-jpa-2.1-api diff --git a/pic-sure-api-data/src/test/java/edu/harvard/dbmi/avillach/DataTest.java b/pic-sure-api-data/src/test/java/edu/harvard/dbmi/avillach/DataTest.java index 322791636..735187770 100755 --- a/pic-sure-api-data/src/test/java/edu/harvard/dbmi/avillach/DataTest.java +++ b/pic-sure-api-data/src/test/java/edu/harvard/dbmi/avillach/DataTest.java @@ -1,26 +1,28 @@ package edu.harvard.dbmi.avillach; import edu.harvard.dbmi.avillach.data.entity.BaseEntity; + import edu.harvard.dbmi.avillach.data.entity.AuthUser; -import org.junit.Test; + +import org.junit.jupiter.api.Test; import java.util.UUID; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; /** * Unit test for simple App. */ public class DataTest { - @Test - public void BaseEntityBasicFunctionsTest() { - BaseEntity user = new AuthUser(); - user.setUuid(UUID.fromString("6ef9387a-4cde-4253-bd47-0bdc74ff76ab")); + @Test + public void BaseEntityBasicFunctionsTest() { + BaseEntity user = new AuthUser(); + user.setUuid(UUID.fromString("6ef9387a-4cde-4253-bd47-0bdc74ff76ab")); - BaseEntity user2 = new AuthUser(); - user2.setUuid(UUID.fromString("6ef9387a-4cde-4253-bd47-0bdc74ff76ab")); + BaseEntity user2 = new AuthUser(); + user2.setUuid(UUID.fromString("6ef9387a-4cde-4253-bd47-0bdc74ff76ab")); - assertEquals(user, user2); - } + assertEquals(user, user2); + } } diff --git a/pic-sure-api-war/pom.xml b/pic-sure-api-war/pom.xml index 828476a48..150f30ec7 100755 --- a/pic-sure-api-war/pom.xml +++ b/pic-sure-api-war/pom.xml @@ -64,7 +64,12 @@ org.mockito mockito-core test - + + + org.mockito + mockito-junit-jupiter + test + org.glassfish.jersey.core jersey-common @@ -73,7 +78,12 @@ org.apache.cxf cxf-rt-frontend-jaxrs test - + + + org.junit.jupiter + junit-jupiter + test + org.jboss.resteasy resteasy-jackson2-provider diff --git a/pic-sure-api-war/src/test/java/edu/harvard/dbmi/avillach/BaseServiceTest.java b/pic-sure-api-war/src/test/java/edu/harvard/dbmi/avillach/BaseServiceTest.java index f89ff5840..929fda658 100644 --- a/pic-sure-api-war/src/test/java/edu/harvard/dbmi/avillach/BaseServiceTest.java +++ b/pic-sure-api-war/src/test/java/edu/harvard/dbmi/avillach/BaseServiceTest.java @@ -1,24 +1,23 @@ package edu.harvard.dbmi.avillach; import org.glassfish.jersey.internal.RuntimeDelegateImpl; -import org.junit.BeforeClass; - -import org.junit.Ignore; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Disabled; import javax.ws.rs.ext.RuntimeDelegate; -@Ignore +@Disabled public class BaseServiceTest { protected static String endpointUrl; - @BeforeClass + @BeforeAll public static void beforeClass() { endpointUrl = System.getProperty("service.url"); - //Need to be able to throw exceptions without container so we can verify correct errors are being thrown + // Need to be able to throw exceptions without container so we can verify correct errors are being thrown RuntimeDelegate runtimeDelegate = new RuntimeDelegateImpl(); RuntimeDelegate.setInstance(runtimeDelegate); -} + } } diff --git a/pic-sure-api-war/src/test/java/edu/harvard/dbmi/avillach/ConfigurationRSTest.java b/pic-sure-api-war/src/test/java/edu/harvard/dbmi/avillach/ConfigurationRSTest.java index 7858542dd..ce7178283 100644 --- a/pic-sure-api-war/src/test/java/edu/harvard/dbmi/avillach/ConfigurationRSTest.java +++ b/pic-sure-api-war/src/test/java/edu/harvard/dbmi/avillach/ConfigurationRSTest.java @@ -1,7 +1,8 @@ package edu.harvard.dbmi.avillach; +import org.junit.jupiter.api.Test; + import edu.harvard.dbmi.avillach.data.request.ConfigurationRequest; -import org.junit.Test; import javax.annotation.security.PermitAll; import javax.annotation.security.RolesAllowed; @@ -10,16 +11,16 @@ import java.util.Arrays; import java.util.UUID; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; public class ConfigurationRSTest { private final String SUPER_ADMIN = "SUPER_ADMIN"; private void assertRolesAllowed(Method method, String role) { RolesAllowed annotation = method.getAnnotation(RolesAllowed.class); - assertNotNull("@RolesAllowed missing on " + method.getName(), annotation); - assertTrue(role + " role missing on " + method.getName(), Arrays.asList(annotation.value()).contains(role)); + assertNotNull(annotation, "@RolesAllowed missing on " + method.getName()); + assertTrue(Arrays.asList(annotation.value()).contains(role), role + " role missing on " + method.getName()); } // These unit tests only guard against accidental removal during refactor & they are not an E2E test of the functionality @@ -37,7 +38,7 @@ public void adminEndpoints_requireAdminRole() throws NoSuchMethodException { private void assertPermitAll(Method method) { PermitAll permitAll = method.getAnnotation(PermitAll.class); - assertNotNull(method.getName() + " must have @PermitAll annotation", permitAll); + assertNotNull(permitAll, method.getName() + " must have @PermitAll annotation"); } @Test diff --git a/pic-sure-api-war/src/test/java/edu/harvard/dbmi/avillach/LoggerReaderInterceptorTest.java b/pic-sure-api-war/src/test/java/edu/harvard/dbmi/avillach/LoggerReaderInterceptorTest.java index 2da958f44..e5d4aa89c 100644 --- a/pic-sure-api-war/src/test/java/edu/harvard/dbmi/avillach/LoggerReaderInterceptorTest.java +++ b/pic-sure-api-war/src/test/java/edu/harvard/dbmi/avillach/LoggerReaderInterceptorTest.java @@ -6,56 +6,47 @@ import org.apache.cxf.message.ExchangeImpl; import org.apache.cxf.message.Message; import org.apache.cxf.message.MessageImpl; -import org.junit.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; import javax.ws.rs.ext.ReaderInterceptorContext; + import java.io.IOException; + +import org.junit.jupiter.api.Test; import java.io.InputStream; import java.util.HashMap; import org.apache.cxf.jaxrs.impl.ReaderInterceptorContextImpl; -import static org.junit.Assert.*; - public class LoggerReaderInterceptorTest { private LoggerReaderInterceptor cut = new LoggerReaderInterceptor(); @Test - public void testCredentialsRedacted() throws IOException{ - - //Different pieces of a query - String resourceCredentials = "resourceCredentials\": " + - "{ \"IRCT_BEARER_TOKEN\": \"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ0ZXN0fGF2bGJvdEBkYm1pLmhtcy5oYXJ2YXJkLmVkdSIsImVtYWlsIjoiYXZsYm90QGRibWkuaG1zLmhhcnZhcmQuZWR1In0.51TYsm-uw2VtI8aGawdggbGdCSrPJvjtvzafd2Ii9NU\"}"; - - String query = "query\": " + - "{ " + - "\"select\": [" + - " {" + - " \"alias\": \"gender\", \"field\": {\"pui\": \"/nhanes/Demo/demographics/demographics/SEX/male\", \"dataType\":\"STRING\"}" + - " }," + - " {" + - " \"alias\": \"gender\", \"field\": {\"pui\": \"/nhanes/Demo/demographics/demographics/SEX/female\", \"dataType\":\"STRING\"}" + - " }," + - " {" + - " \"alias\": \"age\", \"field\": {\"pui\": \"/nhanes/Demo/demographics/demographics/AGE\", \"dataType\":\"STRING\"}" + - " }" + - " ]," + - " \"where\": [ " + - "{ \"predicate\": \"CONTAINS\", " + - "\"field\": " + - "{ \"pui\": \"/nhanes/Demo/demographics/demographics/SEX/male/\", " + - "\"dataType\": \"STRING\" " + - "}, " + - "\"fields\": " + - "{ \"ENOUNTER\": \"YES\" } " + - "} ]" + - "}"; + public void testCredentialsRedacted() throws IOException { + + // Different pieces of a query + String resourceCredentials = "resourceCredentials\": " + + "{ \"IRCT_BEARER_TOKEN\": \"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ0ZXN0fGF2bGJvdEBkYm1pLmhtcy5oYXJ2YXJkLmVkdSIsImVtYWlsIjoiYXZsYm90QGRibWkuaG1zLmhhcnZhcmQuZWR1In0.51TYsm-uw2VtI8aGawdggbGdCSrPJvjtvzafd2Ii9NU\"}"; + + String query = "query\": " + "{ " + "\"select\": [" + " {" + + " \"alias\": \"gender\", \"field\": {\"pui\": \"/nhanes/Demo/demographics/demographics/SEX/male\", \"dataType\":\"STRING\"}" + + " }," + " {" + + " \"alias\": \"gender\", \"field\": {\"pui\": \"/nhanes/Demo/demographics/demographics/SEX/female\", \"dataType\":\"STRING\"}" + + " }," + " {" + + " \"alias\": \"age\", \"field\": {\"pui\": \"/nhanes/Demo/demographics/demographics/AGE\", \"dataType\":\"STRING\"}" + + " }" + " ]," + " \"where\": [ " + "{ \"predicate\": \"CONTAINS\", " + "\"field\": " + + "{ \"pui\": \"/nhanes/Demo/demographics/demographics/SEX/male/\", " + "\"dataType\": \"STRING\" " + "}, " + "\"fields\": " + + "{ \"ENOUNTER\": \"YES\" } " + "} ]" + "}"; String resourceUUID = "\"resourceUUID\" : \"{{resourceUUID}}\""; - //Assemble pieces into different test queries + // Assemble pieces into different test queries String order1 = "{ " + resourceUUID + "," + query + ", " + resourceCredentials + "}"; String order2 = "{ " + query + "," + resourceCredentials + ", " + resourceUUID + "}"; String credentialsOnly = "{" + resourceCredentials + "}"; @@ -63,18 +54,18 @@ public void testCredentialsRedacted() throws IOException{ String nested2 = "{ " + resourceCredentials + "," + "query:" + nested1 + ", " + resourceUUID + "}"; - //Mocking turned out to be a mess so let's just do this this dumb way + // Mocking turned out to be a mess so let's just do this this dumb way Message message = new MessageImpl(); Exchange ex = new ExchangeImpl(); ex.put("jaxrs.filter.properties", new HashMap()); message.setExchange(ex); - //Put the test string into a stream and stuff it in a context to test + // Put the test string into a stream and stuff it in a context to test InputStream stream = IOUtils.toInputStream(order1, "UTF-8"); - ReaderInterceptorContext context = new ReaderInterceptorContextImpl(null, null, null, stream,message, null); + ReaderInterceptorContext context = new ReaderInterceptorContextImpl(null, null, null, stream, message, null); cut.aroundReadFrom(context); - //See if it's done what we want + // See if it's done what we want Object result = context.getProperty("requestContent"); assertNotNull(result); String resultString = result.toString(); @@ -84,9 +75,9 @@ public void testCredentialsRedacted() throws IOException{ assertFalse(resultString.contains("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9")); assertTrue(resultString.contains("RESOURCE_CREDENTIALS_REDACTED")); - //Make sure order isn't an issue + // Make sure order isn't an issue stream = IOUtils.toInputStream(order2, "UTF-8"); - context = new ReaderInterceptorContextImpl(null, null, null, stream,message, null); + context = new ReaderInterceptorContextImpl(null, null, null, stream, message, null); cut.aroundReadFrom(context); result = context.getProperty("requestContent"); @@ -98,9 +89,9 @@ public void testCredentialsRedacted() throws IOException{ assertFalse(resultString.contains("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9")); assertTrue(resultString.contains("RESOURCE_CREDENTIALS_REDACTED")); - //What if there's nothing in there but credentials + // What if there's nothing in there but credentials stream = IOUtils.toInputStream(credentialsOnly, "UTF-8"); - context = new ReaderInterceptorContextImpl(null, null, null, stream,message, null); + context = new ReaderInterceptorContextImpl(null, null, null, stream, message, null); cut.aroundReadFrom(context); result = context.getProperty("requestContent"); @@ -112,9 +103,9 @@ public void testCredentialsRedacted() throws IOException{ assertFalse(resultString.contains("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9")); assertTrue(resultString.contains("RESOURCE_CREDENTIALS_REDACTED")); - //What if it's nested? + // What if it's nested? stream = IOUtils.toInputStream(nested1, "UTF-8"); - context = new ReaderInterceptorContextImpl(null, null, null, stream,message, null); + context = new ReaderInterceptorContextImpl(null, null, null, stream, message, null); cut.aroundReadFrom(context); result = context.getProperty("requestContent"); @@ -127,9 +118,9 @@ public void testCredentialsRedacted() throws IOException{ assertTrue(resultString.contains("RESOURCE_CREDENTIALS_REDACTED")); assertEquals(2, StringUtils.countMatches(resultString, "RESOURCE_CREDENTIALS_REDACTED")); - //What if it's nested two layers deep?? + // What if it's nested two layers deep?? stream = IOUtils.toInputStream(nested2, "UTF-8"); - context = new ReaderInterceptorContextImpl(null, null, null, stream,message, null); + context = new ReaderInterceptorContextImpl(null, null, null, stream, message, null); cut.aroundReadFrom(context); result = context.getProperty("requestContent"); diff --git a/pic-sure-api-war/src/test/java/edu/harvard/dbmi/avillach/PicsureInfoServiceTest.java b/pic-sure-api-war/src/test/java/edu/harvard/dbmi/avillach/PicsureInfoServiceTest.java index f667c3131..78d17e494 100644 --- a/pic-sure-api-war/src/test/java/edu/harvard/dbmi/avillach/PicsureInfoServiceTest.java +++ b/pic-sure-api-war/src/test/java/edu/harvard/dbmi/avillach/PicsureInfoServiceTest.java @@ -8,24 +8,27 @@ import edu.harvard.dbmi.avillach.service.ResourceWebClient; import edu.harvard.dbmi.avillach.util.exception.ApplicationException; import edu.harvard.dbmi.avillach.util.exception.ProtocolException; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentMatchers; import org.mockito.InjectMocks; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; import java.util.*; -import static junit.framework.TestCase.assertTrue; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; import static org.mockito.AdditionalMatchers.not; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; -@RunWith(MockitoJUnitRunner.class) +@MockitoSettings(strictness = Strictness.WARN) +@ExtendWith(MockitoExtension.class) public class PicsureInfoServiceTest extends BaseServiceTest { private UUID resourceId = UUID.randomUUID(); @@ -42,7 +45,7 @@ public class PicsureInfoServiceTest extends BaseServiceTest { @Mock private ResourceWebClient webClient = mock(ResourceWebClient.class); - @Before + @BeforeEach public void setUp() { ResourceInfo results = new ResourceInfo(); Resource testResource = new Resource().setName("A Mock Resource"); @@ -64,38 +67,45 @@ public void testInfoEndpoints() { Map clientCredentials = new HashMap(); infoRequest.setResourceCredentials(clientCredentials); - //Should fail with a nonexistent id + // Should fail with a nonexistent id try { ResourceInfo info = infoService.info(UUID.randomUUID(), infoRequest, null); fail(); - } catch (ProtocolException e){ + } catch (ProtocolException e) { assertNotNull(e.getContent()); - assertTrue("Error message should say '" + ProtocolException.RESOURCE_NOT_FOUND + "'", e.getContent().toString().contains(ProtocolException.RESOURCE_NOT_FOUND)); } + assertTrue( + e.getContent().toString().contains(ProtocolException.RESOURCE_NOT_FOUND), + "Error message should say '" + ProtocolException.RESOURCE_NOT_FOUND + "'" + ); + } - //Should fail without the url in the resource + // Should fail without the url in the resource try { ResourceInfo info = infoService.info(resourceId, infoRequest, null); fail(); - } catch (ApplicationException e){ + } catch (ApplicationException e) { assertNotNull(e.getContent()); - assertEquals("Error message should say '" + ApplicationException.MISSING_RESOURCE_PATH + "'", ApplicationException.MISSING_RESOURCE_PATH, e.getContent().toString()); + assertEquals( + ApplicationException.MISSING_RESOURCE_PATH, e.getContent().toString(), + "Error message should say '" + ApplicationException.MISSING_RESOURCE_PATH + "'" + ); } when(mockResource.getResourceRSPath()).thenReturn("resourceRsPath"); ResourceInfo responseInfo = infoService.info(resourceId, infoRequest, null); - assertNotNull("Resource response should not be null", responseInfo); + assertNotNull(responseInfo, "Resource response should not be null"); - //Should also work without clientCredentials + // Should also work without clientCredentials responseInfo = infoService.info(resourceId, null, null); - assertNotNull("Resource response should not be null", responseInfo); + assertNotNull(responseInfo, "Resource response should not be null"); } @Test public void testResourcesEndpoint() { - //Should give a UUID list of all resources + // Should give a UUID list of all resources Map resourceList = infoService.resources(null); - assertNotNull("Resource listing should not be null", resourceList); - assertEquals("Resource listing should only have 1 entry", 1, resourceList.size()); - assertSame("Resource listing should be UUID of our mocked resource", resourceId, resourceList.keySet().iterator().next()); + assertNotNull(resourceList, "Resource listing should not be null"); + assertEquals(1, resourceList.size(), "Resource listing should only have 1 entry"); + assertSame(resourceId, resourceList.keySet().iterator().next(), "Resource listing should be UUID of our mocked resource"); } } diff --git a/pic-sure-api-war/src/test/java/edu/harvard/dbmi/avillach/PicsureQueryServiceTest.java b/pic-sure-api-war/src/test/java/edu/harvard/dbmi/avillach/PicsureQueryServiceTest.java index 07f2c2dac..180c2cb3f 100644 --- a/pic-sure-api-war/src/test/java/edu/harvard/dbmi/avillach/PicsureQueryServiceTest.java +++ b/pic-sure-api-war/src/test/java/edu/harvard/dbmi/avillach/PicsureQueryServiceTest.java @@ -1,9 +1,9 @@ package edu.harvard.dbmi.avillach; -import static junit.framework.TestCase.assertTrue; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doAnswer; @@ -20,16 +20,16 @@ import edu.harvard.dbmi.avillach.domain.PicSureStatus; import edu.harvard.dbmi.avillach.service.ResourceWebClient; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; - +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.invocation.InvocationOnMock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; import org.mockito.stubbing.Answer; import edu.harvard.dbmi.avillach.data.entity.Query; @@ -43,7 +43,8 @@ import edu.harvard.dbmi.avillach.util.exception.ApplicationException; import edu.harvard.dbmi.avillach.util.exception.ProtocolException; -@RunWith(MockitoJUnitRunner.class) +@MockitoSettings(strictness = Strictness.WARN) +@ExtendWith(MockitoExtension.class) public class PicsureQueryServiceTest extends BaseServiceTest { private UUID resourceId; @@ -70,7 +71,7 @@ public class PicsureQueryServiceTest extends BaseServiceTest { @Mock private AuditContext auditContext = mock(AuditContext.class); - @Before + @BeforeEach public void setUp() { resourceId = UUID.randomUUID(); queryString = "queryDoesntMatterForTest"; @@ -111,8 +112,8 @@ public void testQueryEmptyRequest() { } catch (ProtocolException e) { assertNotNull(e.getContent()); assertEquals( - "Error message should say '" + ProtocolException.MISSING_DATA + "'", ProtocolException.MISSING_DATA, - e.getContent().toString() + ProtocolException.MISSING_DATA, e.getContent().toString(), + "Error message should say '" + ProtocolException.MISSING_DATA + "'" ); } } @@ -135,8 +136,8 @@ public void testQueryMissingResourceId() { } catch (ProtocolException e) { assertNotNull(e.getContent()); assertEquals( - "Error message should say '" + ProtocolException.MISSING_RESOURCE_ID + "'", ProtocolException.MISSING_RESOURCE_ID, - e.getContent().toString() + ProtocolException.MISSING_RESOURCE_ID, e.getContent().toString(), + "Error message should say '" + ProtocolException.MISSING_RESOURCE_ID + "'" ); } @@ -159,8 +160,8 @@ public void testQueryInvalidResourceId() { } catch (ProtocolException e) { assertNotNull(e.getContent()); assertTrue( - "Error message should say '" + ProtocolException.RESOURCE_NOT_FOUND + "'", - e.getContent().toString().contains(ProtocolException.RESOURCE_NOT_FOUND) + e.getContent().toString().contains(ProtocolException.RESOURCE_NOT_FOUND), + "Error message should say '" + ProtocolException.RESOURCE_NOT_FOUND + "'" ); } @@ -176,24 +177,24 @@ public void testQueryValidRequest() { dataQueryRequest.setQuery(queryString); QueryStatus result = queryService.query(dataQueryRequest, null); - assertNotNull("Status should not be null", result.getStatus()); - assertNotNull("Resource result id should not be null", result.getResourceResultId()); - assertNotNull("Picsure result id should not be null", result.getPicsureResultId()); + assertNotNull(result.getStatus(), "Status should not be null"); + assertNotNull(result.getResourceResultId(), "Resource result id should not be null"); + assertNotNull(result.getPicsureResultId(), "Picsure result id should not be null"); // Since there was no resource result id, it should be the same as the picsure // result id assertEquals( - "Resource result id and Picsure result id should match in case of no resource result id", result.getResourceResultId(), - result.getPicsureResultId().toString() + result.getResourceResultId(), result.getPicsureResultId().toString(), + "Resource result id and Picsure result id should match in case of no resource result id" ); // Make sure the query is persisted - assertNotNull("Query Entity should have been persisted", queryEntity); - assertEquals("QueryEntity should be linked to resource", queryEntity.getResource(), mockResource); + assertNotNull(queryEntity, "Query Entity should have been persisted"); + assertEquals(queryEntity.getResource(), mockResource, "QueryEntity should be linked to resource"); - assertTrue("Query Entity should have query stored", queryEntity.getQuery().contains(queryString)); + assertTrue(queryEntity.getQuery().contains(queryString), "Query Entity should have query stored"); assertEquals( - "Resource result id and Picsure result id should match in case of no resource result id", queryEntity.getResourceResultId(), - queryEntity.getUuid().toString() + queryEntity.getResourceResultId(), queryEntity.getUuid().toString(), + "Resource result id and Picsure result id should match in case of no resource result id" ); } @@ -210,8 +211,8 @@ public void testQueryStatusNoId() { } catch (ProtocolException e) { assertNotNull(e.getContent()); assertEquals( - "Error message should say '" + ProtocolException.MISSING_QUERY_ID + "'", ProtocolException.MISSING_QUERY_ID, - e.getContent().toString() + ProtocolException.MISSING_QUERY_ID, e.getContent().toString(), + "Error message should say '" + ProtocolException.MISSING_QUERY_ID + "'" ); } @@ -231,8 +232,8 @@ public void testQueryStatusInvalidId() { } catch (ProtocolException e) { assertNotNull(e.getContent()); assertTrue( - "Error message should say '" + ProtocolException.QUERY_NOT_FOUND + "'", - e.getContent().toString().contains(ProtocolException.QUERY_NOT_FOUND) + e.getContent().toString().contains(ProtocolException.QUERY_NOT_FOUND), + "Error message should say '" + ProtocolException.QUERY_NOT_FOUND + "'" ); } @@ -261,13 +262,13 @@ public void testQueryStatusValid() { // This one should work QueryStatus result = queryService.queryStatus(queryId, statusRequest, null); // These fields are set by the method - assertNotNull("Result should not be null", result); - assertEquals("Picsure ResultId should match", queryId, result.getPicsureResultId()); - assertEquals("Resource Id should match", resourceId, result.getResourceID()); - assertNotNull("Start time should not be null", result.getStartTime()); + assertNotNull(result, "Result should not be null"); + assertEquals(queryId, result.getPicsureResultId(), "Picsure ResultId should match"); + assertEquals(resourceId, result.getResourceID(), "Resource Id should match"); + assertNotNull(result.getStartTime(), "Start time should not be null"); // Make sure info was saved to the query entity - assertEquals("Query status should have been updated", PicSureStatus.AVAILABLE, queryEntity.getStatus()); + assertEquals(PicSureStatus.AVAILABLE, queryEntity.getStatus(), "Query status should have been updated"); } @Test @@ -283,8 +284,8 @@ public void testQueryResultNoId() { } catch (ProtocolException e) { assertNotNull(e.getContent()); assertEquals( - "Error message should say '" + ProtocolException.MISSING_QUERY_ID + "'", ProtocolException.MISSING_QUERY_ID, - e.getContent().toString() + ProtocolException.MISSING_QUERY_ID, e.getContent().toString(), + "Error message should say '" + ProtocolException.MISSING_QUERY_ID + "'" ); } @@ -303,8 +304,8 @@ public void testQueryResultInvalidId() { } catch (ProtocolException e) { assertNotNull(e.getContent()); assertTrue( - "Error message should say '" + ProtocolException.QUERY_NOT_FOUND + "'", - e.getContent().toString().contains(ProtocolException.QUERY_NOT_FOUND) + e.getContent().toString().contains(ProtocolException.QUERY_NOT_FOUND), + "Error message should say '" + ProtocolException.QUERY_NOT_FOUND + "'" ); } @@ -335,7 +336,7 @@ public void testQueryResultValid() { // This one should work Response result = queryService.queryResult(queryId, resultRequest, null); - assertNotNull("Result should not be null", result); + assertNotNull(result, "Result should not be null"); } @Test @@ -348,8 +349,8 @@ public void testQuerySyncNoQuery() { } catch (ProtocolException e) { assertNotNull(e.getContent()); assertEquals( - "Error message should say '" + ProtocolException.MISSING_DATA + "'", ProtocolException.MISSING_DATA, - e.getContent().toString() + ProtocolException.MISSING_DATA, e.getContent().toString(), + "Error message should say '" + ProtocolException.MISSING_DATA + "'" ); } @@ -372,8 +373,8 @@ public void testQuerySyncNoResourceId() { } catch (ProtocolException e) { assertNotNull(e.getContent()); assertEquals( - "Error message should say '" + ProtocolException.MISSING_RESOURCE_ID + "'", ProtocolException.MISSING_RESOURCE_ID, - e.getContent().toString() + ProtocolException.MISSING_RESOURCE_ID, e.getContent().toString(), + "Error message should say '" + ProtocolException.MISSING_RESOURCE_ID + "'" ); } @@ -395,8 +396,8 @@ public void testQuerySyncInvalidResourceId() { } catch (ApplicationException e) { assertNotNull(e.getContent()); assertTrue( - "Error message should say '" + ApplicationException.MISSING_RESOURCE + "'", - e.getContent().toString().contains(ApplicationException.MISSING_RESOURCE) + e.getContent().toString().contains(ApplicationException.MISSING_RESOURCE), + "Error message should say '" + ApplicationException.MISSING_RESOURCE + "'" ); } @@ -437,16 +438,16 @@ public Void answer(InvocationOnMock invocation) { // Test correct request dataQueryRequest.setResourceUUID(resourceId); Response result = queryService.querySync(dataQueryRequest, null); - assertNotNull("Result should not be null", result.getStatus()); + assertNotNull(result.getStatus(), "Result should not be null"); // Make sure the query is persisted - assertNotNull("Query Entity should have been persisted", queryEntity); - assertEquals("QueryEntity should be linked to resource", queryEntity.getResource(), mockResource); + assertNotNull(queryEntity, "Query Entity should have been persisted"); + assertEquals(queryEntity.getResource(), mockResource, "QueryEntity should be linked to resource"); - assertTrue("Query Entity should have query stored", queryEntity.getQuery().contains(queryString)); + assertTrue(queryEntity.getQuery().contains(queryString), "Query Entity should have query stored"); assertEquals( - "Resource result id and Picsure result id should match in case of no resource result id", queryId.toString(), - queryEntity.getResourceResultId() + queryId.toString(), queryEntity.getResourceResultId(), + "Resource result id and Picsure result id should match in case of no resource result id" ); } @@ -472,7 +473,7 @@ public void testShouldQueryMetadata() { QueryStatus status = queryService.queryMetadata(query.getUuid(), null); String actual = (String) status.getResultMetadata().get("queryResultMetadata"); - Assert.assertEquals(metaData, actual); + assertEquals(metaData, actual); } @Test @@ -516,14 +517,14 @@ public Void answer(InvocationOnMock invocation) { // Test correct request dataQueryRequest.setResourceUUID(resourceId); Response result = queryService.querySync(dataQueryRequest, null); - assertNotNull("Result should not be null", result.getStatus()); + assertNotNull(result.getStatus(), "Result should not be null"); // Make sure the query is persisted - assertNotNull("Query Entity should have been persisted", queryEntity); - assertEquals("QueryEntity should be linked to resource", queryEntity.getResource(), mockResource); + assertNotNull(queryEntity, "Query Entity should have been persisted"); + assertEquals(queryEntity.getResource(), mockResource, "QueryEntity should be linked to resource"); - assertTrue("Query Entity should have query stored", queryEntity.getQuery().contains(queryString)); - assertEquals("Resource result id should match returned header", resultId, queryEntity.getResourceResultId()); + assertTrue(queryEntity.getQuery().contains(queryString), "Query Entity should have query stored"); + assertEquals(resultId, queryEntity.getResourceResultId(), "Resource result id should match returned header"); } diff --git a/pic-sure-api-war/src/test/java/edu/harvard/dbmi/avillach/PicsureSearchServiceTest.java b/pic-sure-api-war/src/test/java/edu/harvard/dbmi/avillach/PicsureSearchServiceTest.java index 4f82b7c58..cfc7e4c18 100644 --- a/pic-sure-api-war/src/test/java/edu/harvard/dbmi/avillach/PicsureSearchServiceTest.java +++ b/pic-sure-api-war/src/test/java/edu/harvard/dbmi/avillach/PicsureSearchServiceTest.java @@ -7,34 +7,38 @@ import edu.harvard.dbmi.avillach.service.ResourceWebClient; import edu.harvard.dbmi.avillach.util.exception.ApplicationException; import edu.harvard.dbmi.avillach.util.exception.ProtocolException; -import org.junit.Before; -import org.junit.Test; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import java.util.UUID; import edu.harvard.dbmi.avillach.data.entity.Resource; import edu.harvard.dbmi.avillach.domain.GeneralQueryRequest; -import org.junit.runner.RunWith; import org.mockito.ArgumentMatchers; import org.mockito.InjectMocks; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; import java.util.HashMap; import java.util.Map; -import static junit.framework.TestCase.assertTrue; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import static org.mockito.AdditionalMatchers.not; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -@RunWith(MockitoJUnitRunner.class) +@MockitoSettings(strictness = Strictness.WARN) +@ExtendWith(MockitoExtension.class) public class PicsureSearchServiceTest extends BaseServiceTest { private UUID resourceId = UUID.randomUUID(); @@ -54,7 +58,7 @@ public class PicsureSearchServiceTest extends BaseServiceTest { @Mock private AuditContext auditContext = mock(AuditContext.class); - @Before + @BeforeEach public void setUp() { SearchResults results = new SearchResults(); when(resourceRepo.getById(resourceId)).thenReturn(mockResource); @@ -76,8 +80,8 @@ public void testSearch() { } catch (ApplicationException e) { assertNotNull(e.getContent()); assertEquals( - "Error message should say '" + ApplicationException.MISSING_RESOURCE_PATH + "'", ApplicationException.MISSING_RESOURCE_PATH, - e.getContent().toString() + ApplicationException.MISSING_RESOURCE_PATH, e.getContent().toString(), + "Error message should say '" + ApplicationException.MISSING_RESOURCE_PATH + "'" ); } @@ -90,8 +94,8 @@ public void testSearch() { } catch (ProtocolException e) { assertNotNull(e.getContent()); assertEquals( - "Error message should say '" + ProtocolException.MISSING_DATA + "'", ProtocolException.MISSING_DATA, - e.getContent().toString() + ProtocolException.MISSING_DATA, e.getContent().toString(), + "Error message should say '" + ProtocolException.MISSING_DATA + "'" ); } @@ -102,8 +106,8 @@ public void testSearch() { } catch (ProtocolException e) { assertNotNull(e.getContent()); assertEquals( - "Error message should say '" + ProtocolException.MISSING_RESOURCE_ID + "'", ProtocolException.MISSING_RESOURCE_ID, - e.getContent().toString() + ProtocolException.MISSING_RESOURCE_ID, e.getContent().toString(), + "Error message should say '" + ProtocolException.MISSING_RESOURCE_ID + "'" ); } @@ -115,19 +119,19 @@ public void testSearch() { } catch (ProtocolException e) { assertNotNull(e.getContent()); assertTrue( - "Error message should say '" + ProtocolException.RESOURCE_NOT_FOUND + "'", - e.getContent().toString().contains(ProtocolException.RESOURCE_NOT_FOUND) + e.getContent().toString().contains(ProtocolException.RESOURCE_NOT_FOUND), + "Error message should say '" + ProtocolException.RESOURCE_NOT_FOUND + "'" ); } // This should work SearchResults results = searchService.search(resourceId, searchQueryRequest, null); - assertNotNull("SearchResults should not be null", results); + assertNotNull(results, "SearchResults should not be null"); // There should also be no problem if the resourceCredentials are null searchQueryRequest.setResourceCredentials(null); results = searchService.search(resourceId, searchQueryRequest, null); - assertNotNull("SearchResults should not be null", results); + assertNotNull(results, "SearchResults should not be null"); } @Test diff --git a/pic-sure-api-war/src/test/java/edu/harvard/dbmi/avillach/security/AuditLoggingFilterTest.java b/pic-sure-api-war/src/test/java/edu/harvard/dbmi/avillach/security/AuditLoggingFilterTest.java index b88fd7c63..91177f9a2 100644 --- a/pic-sure-api-war/src/test/java/edu/harvard/dbmi/avillach/security/AuditLoggingFilterTest.java +++ b/pic-sure-api-war/src/test/java/edu/harvard/dbmi/avillach/security/AuditLoggingFilterTest.java @@ -1,6 +1,9 @@ package edu.harvard.dbmi.avillach.security; -import static org.junit.Assert.*; +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.mockito.Mockito.*; import java.io.IOException; @@ -13,8 +16,8 @@ import javax.ws.rs.core.SecurityContext; import javax.ws.rs.core.UriInfo; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import edu.harvard.dbmi.avillach.data.entity.AuthUser; @@ -30,7 +33,7 @@ public class AuditLoggingFilterTest { private HttpServletRequest httpServletRequest; private AuditContext auditContext; - @Before + @BeforeEach public void setup() { filter = new AuditLoggingFilter(); loggingClient = mock(LoggingClient.class); diff --git a/pic-sure-api-war/src/test/java/edu/harvard/dbmi/avillach/security/JWTFilterTest.java b/pic-sure-api-war/src/test/java/edu/harvard/dbmi/avillach/security/JWTFilterTest.java index 0fdc4ff77..902a12493 100644 --- a/pic-sure-api-war/src/test/java/edu/harvard/dbmi/avillach/security/JWTFilterTest.java +++ b/pic-sure-api-war/src/test/java/edu/harvard/dbmi/avillach/security/JWTFilterTest.java @@ -1,7 +1,9 @@ package edu.harvard.dbmi.avillach.security; import static com.github.tomakehurst.wiremock.client.WireMock.*; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.*; import java.io.ByteArrayInputStream; @@ -21,15 +23,17 @@ import javax.ws.rs.core.Response; import javax.ws.rs.core.UriInfo; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; import org.mockito.ArgumentCaptor; import com.fasterxml.jackson.databind.ObjectMapper; -import com.github.tomakehurst.wiremock.junit.WireMockRule; import edu.harvard.dbmi.avillach.PicSureWarInit; + +import com.github.tomakehurst.wiremock.core.WireMockConfiguration; +import com.github.tomakehurst.wiremock.junit5.WireMockExtension; import edu.harvard.dbmi.avillach.data.entity.Query; import edu.harvard.dbmi.avillach.data.entity.Resource; import edu.harvard.dbmi.avillach.data.repository.QueryRepository; @@ -43,8 +47,8 @@ public class JWTFilterTest { private static final UUID RESOURCE_UUID = UUID.fromString("30ef4941-9656-4b47-af80-528f2b98cf17"); - @Rule - public WireMockRule wireMockRule = new WireMockRule(0); + @RegisterExtension + public WireMockExtension wireMockRule = WireMockExtension.newInstance().options(WireMockConfiguration.options().port(0)).build(); private int port; @@ -52,9 +56,10 @@ public class JWTFilterTest { private JWTFilter filter; - @Before + @BeforeEach public void setup() { - port = wireMockRule.port(); + port = wireMockRule.getPort(); + com.github.tomakehurst.wiremock.client.WireMock.configureFor(port); picSureWarInit = mock(PicSureWarInit.class); when(picSureWarInit.getToken_introspection_token()).thenReturn("INTROSPECTION_TOKEN"); when(picSureWarInit.getToken_introspection_url()).thenReturn("http://localhost:" + port + "/introspection_endpoint"); @@ -91,7 +96,7 @@ private Query persistedQuery() { private Resource basicResource() { Resource resource = mock(Resource.class); - when(resource.getResourceRSPath()).thenReturn("http://localhost:" + wireMockRule.port() + "/resource"); + when(resource.getResourceRSPath()).thenReturn("http://localhost:" + wireMockRule.getPort() + "/resource"); when(resource.getToken()).thenReturn("RESOURCE_TOKEN"); when(resource.getUuid()).thenReturn(RESOURCE_UUID); @@ -167,23 +172,29 @@ public void testExcludedFilterPaths_config_validPathsWithNoAuthRequired() throws assertEquals(0, exceptions.size()); } - @Test(expected = NotAuthorizedException.class) + @Test public void testExcludedFilterPaths_config_invalidPathsHitNoAuthException() throws IOException { - ContainerRequestContext ctx = createRequestContext(); - when(ctx.getUriInfo().getPath()).thenReturn("/configuration/SOME_FLA%G"); - when(ctx.getRequest().getMethod()).thenReturn(HttpMethod.GET); + assertThrows(NotAuthorizedException.class, () -> { + ContainerRequestContext ctx = createRequestContext(); + when(ctx.getUriInfo().getPath()).thenReturn("/configuration/SOME_FLA%G"); + when(ctx.getRequest().getMethod()).thenReturn(HttpMethod.GET); - filter.filter(ctx); + filter.filter(ctx); + // Test passes if NotAuthorizedException is thrown + }); // Test passes if NotAuthorizedException is thrown } - @Test(expected = NotAuthorizedException.class) + @Test public void testExcludedFilterPaths_config_blockedAdminPathHitsNoAuthException() throws IOException { - ContainerRequestContext ctx = createRequestContext(); - when(ctx.getUriInfo().getPath()).thenReturn("/configuration/admin"); - when(ctx.getRequest().getMethod()).thenReturn(HttpMethod.GET); + assertThrows(NotAuthorizedException.class, () -> { + ContainerRequestContext ctx = createRequestContext(); + when(ctx.getUriInfo().getPath()).thenReturn("/configuration/admin"); + when(ctx.getRequest().getMethod()).thenReturn(HttpMethod.GET); - filter.filter(ctx); + filter.filter(ctx); + // Test passes if NotAuthorizedException is thrown + }); // Test passes if NotAuthorizedException is thrown } @@ -203,7 +214,7 @@ public void testFilterCallsTokenIntrospectionAppropriatelyForQuerySync() throws verify( postRequestedFor(urlEqualTo("/introspection_endpoint")) .withRequestBody(matchingJsonPath("$.request.['Target Service']", matching("/query/sync"))) - .withRequestBody(matchingJsonPath("$.request.['query']", matchingJsonPath("query", matching("test")))) + .withRequestBody(matchingJsonPath("$.request.query.query", equalTo("test"))) .withRequestBody(matchingJsonPath("$.token", matching("USER_TOKEN"))) ); } @@ -224,7 +235,7 @@ public void testFilterCallsTokenIntrospectionAppropriatelyForQuery() throws IOEx verify( postRequestedFor(urlEqualTo("/introspection_endpoint")) .withRequestBody(matchingJsonPath("$.request.['Target Service']", matching("/query"))) - .withRequestBody(matchingJsonPath("$.request.['query']", matchingJsonPath("query", matching("test")))) + .withRequestBody(matchingJsonPath("$.request.query.query", equalTo("test"))) .withRequestBody(matchingJsonPath("$.token", matching("USER_TOKEN"))) ); } @@ -250,7 +261,7 @@ public void testFilterCallsTokenIntrospectionAppropriatelyForResultWithoutTraili .withRequestBody( matchingJsonPath("$.request.['Target Service']", matching("/query/e830138f-2943-4661-90ae-da053bd94a18/result")) ).withRequestBody(matchingJsonPath("$.request.query", equalToJson(query.getQuery()))) - .withRequestBody(matchingJsonPath("$.request.formattedQuery", equalToJson("{\"formatted\":\"query\"}"))) + .withRequestBody(matchingJsonPath("$.request.formattedQuery", equalTo("{\"formatted\":\"query\"}"))) .withRequestBody(matchingJsonPath("$.token", matching("USER_TOKEN"))) ); } @@ -276,7 +287,7 @@ public void testFilterCallsTokenIntrospectionAppropriatelyForResultWithTrailingS .withRequestBody( matchingJsonPath("$.request.['Target Service']", matching("/query/e830138f-2943-4661-90ae-da053bd94a18/result/")) ).withRequestBody(matchingJsonPath("$.request.query", equalToJson(query.getQuery()))) - .withRequestBody(matchingJsonPath("$.request.formattedQuery", equalToJson("{\"formatted\":\"query\"}"))) + .withRequestBody(matchingJsonPath("$.request.formattedQuery", equalTo("{\"formatted\":\"query\"}"))) .withRequestBody(matchingJsonPath("$.token", matching("USER_TOKEN"))) ); } @@ -332,7 +343,7 @@ public void testFilterParsesPsamaUpdatedQueryIntoObjectInsteadOfRawText() throws Map finalRequestBody = mapper.readValue(currentBody[0], Map.class); Object query = finalRequestBody.get("query"); - assertTrue("PSAMA's updated query must be stored as a nested object, not a re-escaped JSON string", query instanceof Map); + assertTrue(query instanceof Map, "PSAMA's updated query must be stored as a nested object, not a re-escaped JSON string"); assertEquals(updatedQuery, query); } @@ -398,8 +409,8 @@ public void testFilterRemovesResourceCredentialsBeforeSendingToTokenIntrospectio verify( postRequestedFor(urlEqualTo("/introspection_endpoint")) .withRequestBody(matchingJsonPath("$.request.['Target Service']", matching("/query"))) - .withRequestBody(matchingJsonPath("$.request.['query']", matchingJsonPath("query", matching("test")))) - .withRequestBody(matchingJsonPath("$.request.['query']", notMatching("resourceCredentials"))) + .withRequestBody(matchingJsonPath("$.request.query.query", equalTo("test"))) + .withRequestBody(notMatching(".*resourceCredentials.*")) .withRequestBody(matchingJsonPath("$.token", matching("USER_TOKEN"))) ); } diff --git a/pic-sure-api-war/src/test/java/edu/harvard/dbmi/avillach/service/ConfigurationServiceTest.java b/pic-sure-api-war/src/test/java/edu/harvard/dbmi/avillach/service/ConfigurationServiceTest.java index 38bec8790..f4470d181 100644 --- a/pic-sure-api-war/src/test/java/edu/harvard/dbmi/avillach/service/ConfigurationServiceTest.java +++ b/pic-sure-api-war/src/test/java/edu/harvard/dbmi/avillach/service/ConfigurationServiceTest.java @@ -1,11 +1,14 @@ package edu.harvard.dbmi.avillach.service; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -13,14 +16,14 @@ import java.util.*; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import edu.harvard.dbmi.avillach.data.entity.Configuration; import edu.harvard.dbmi.avillach.data.repository.ConfigurationRepository; import edu.harvard.dbmi.avillach.data.request.ConfigurationRequest; -@RunWith(MockitoJUnitRunner.class) +@MockitoSettings(strictness = Strictness.WARN) +@ExtendWith(MockitoExtension.class) public class ConfigurationServiceTest { private final String testName = "FEATURE_FLAG_X"; private final String testKind = "ui"; @@ -67,7 +70,7 @@ public void getConfigurations_withKind_success() { // Then return a non-empty optional with the configurations assertTrue(response.isPresent()); - assertEquals("correct number of configurations returned", 2, response.get().size()); + assertEquals(2, response.get().size(), "correct number of configurations returned"); } @Test @@ -85,7 +88,7 @@ public void getConfigurations_withoutKind_success() { // Then return a non-empty optional with all configurations assertTrue(response.isPresent()); - assertEquals("correct number of configurations returned", 2, response.get().size()); + assertEquals(2, response.get().size(), "correct number of configurations returned"); } @Test @@ -114,7 +117,7 @@ public void getConfigurationByIdentifier_withUUID_success() { // Then return a non-empty optional assertTrue(response.isPresent()); - assertEquals("correct configuration returned", configId, response.get().getUuid()); + assertEquals(configId, response.get().getUuid(), "correct configuration returned"); } @Test @@ -130,7 +133,7 @@ public void getConfigurationByIdentifier_withName_success() { // Then return a non-empty optional assertTrue(response.isPresent()); - assertEquals("correct configuration returned", testName, response.get().getName()); + assertEquals(testName, response.get().getName(), "correct configuration returned"); } @Test @@ -198,10 +201,10 @@ public void addConfiguration_success() { // Then return a non-empty optional assertTrue(response.isPresent()); - assertEquals("name is saved", testName, response.get().getName()); - assertEquals("kind is saved", testKind, response.get().getKind()); - assertEquals("value is saved", testValue, response.get().getValue()); - assertEquals("description is saved", testDescription, response.get().getDescription()); + assertEquals(testName, response.get().getName(), "name is saved"); + assertEquals(testKind, response.get().getKind(), "kind is saved"); + assertEquals(testValue, response.get().getValue(), "value is saved"); + assertEquals(testDescription, response.get().getDescription(), "description is saved"); } @Test @@ -249,7 +252,7 @@ public void updateConfiguration_changeValue_success() { // Then return a non-empty optional assertTrue(response.isPresent()); - assertEquals("new value is saved", newValue, response.get().getValue()); + assertEquals(newValue, response.get().getValue(), "new value is saved"); } @Test @@ -268,7 +271,7 @@ public void updateConfiguration_changeName_success() { // Then return a non-empty optional assertTrue(response.isPresent()); - assertEquals("new name is saved", newName, response.get().getName()); + assertEquals(newName, response.get().getName(), "new name is saved"); } @@ -287,7 +290,7 @@ public void updateConfiguration_changeDeleteRequestedDate() { // Then return a non-empty optional assertTrue(response.isPresent()); - assertEquals("new delete requested date is saved", true, response.get().getMarkForDelete()); + assertEquals(true, response.get().getMarkForDelete(), "new delete requested date is saved"); } @Test @@ -333,7 +336,7 @@ public void updateConfiguration_changeKind_success() { // Then return a non-empty optional assertTrue(response.isPresent()); - assertEquals("new kind is saved", newKind, response.get().getKind()); + assertEquals(newKind, response.get().getKind(), "new kind is saved"); } @Test @@ -352,7 +355,7 @@ public void updateConfiguration_changeDescription_success() { // Then return a non-empty optional assertTrue(response.isPresent()); - assertEquals("new description is saved", newDescription, response.get().getDescription()); + assertEquals(newDescription, response.get().getDescription(), "new description is saved"); } @Test @@ -399,7 +402,7 @@ public void deleteConfiguration_success() { // Then return a non-empty optional with the deleted configuration assertTrue(response.isPresent()); - assertEquals("correct configuration returned", configId, response.get().getUuid()); + assertEquals(configId, response.get().getUuid(), "correct configuration returned"); } @Test diff --git a/pic-sure-api-war/src/test/java/edu/harvard/dbmi/avillach/service/LoggingClientProducerTest.java b/pic-sure-api-war/src/test/java/edu/harvard/dbmi/avillach/service/LoggingClientProducerTest.java index a3f8f6814..affbaabf7 100644 --- a/pic-sure-api-war/src/test/java/edu/harvard/dbmi/avillach/service/LoggingClientProducerTest.java +++ b/pic-sure-api-war/src/test/java/edu/harvard/dbmi/avillach/service/LoggingClientProducerTest.java @@ -1,9 +1,10 @@ package edu.harvard.dbmi.avillach.service; -import static org.junit.Assert.*; +import org.junit.jupiter.api.Test; import edu.harvard.dbmi.avillach.logging.LoggingClient; -import org.junit.Test; + +import static org.junit.jupiter.api.Assertions.*; public class LoggingClientProducerTest { @@ -15,7 +16,7 @@ public void producesNoOpWhenJndiBindingsAreMissing() { LoggingClient client = producer.loggingClient(); assertNotNull(client); - assertFalse("Should be no-op when JNDI bindings are missing", client.isEnabled()); + assertFalse(client.isEnabled(), "Should be no-op when JNDI bindings are missing"); } @Test diff --git a/pic-sure-api-war/src/test/java/edu/harvard/dbmi/avillach/service/NamedDatasetServiceTest.java b/pic-sure-api-war/src/test/java/edu/harvard/dbmi/avillach/service/NamedDatasetServiceTest.java index 87466e3c8..7aceb25d3 100644 --- a/pic-sure-api-war/src/test/java/edu/harvard/dbmi/avillach/service/NamedDatasetServiceTest.java +++ b/pic-sure-api-war/src/test/java/edu/harvard/dbmi/avillach/service/NamedDatasetServiceTest.java @@ -1,11 +1,14 @@ package edu.harvard.dbmi.avillach.service; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -17,8 +20,7 @@ import java.util.HashMap; import java.util.Optional; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import edu.harvard.dbmi.avillach.data.entity.NamedDataset; import edu.harvard.dbmi.avillach.data.entity.Query; @@ -26,7 +28,8 @@ import edu.harvard.dbmi.avillach.data.repository.QueryRepository; import edu.harvard.dbmi.avillach.data.request.NamedDatasetRequest; -@RunWith(MockitoJUnitRunner.class) +@MockitoSettings(strictness = Strictness.WARN) +@ExtendWith(MockitoExtension.class) public class NamedDatasetServiceTest { private String user = "test.user@email.com"; private String testName = "test name"; @@ -40,14 +43,14 @@ public class NamedDatasetServiceTest { @Mock private QueryRepository queryRepo = mock(QueryRepository.class); - private Query makeQuery(UUID id){ + private Query makeQuery(UUID id) { Query query = new Query(); query.setUuid(id); query.setQuery("{}"); return query; } - private NamedDataset makeNamedDataset(UUID id, Query query){ + private NamedDataset makeNamedDataset(UUID id, Query query) { NamedDataset dataset = new NamedDataset(); dataset.setUuid(id); dataset.setUser(user); @@ -57,7 +60,7 @@ private NamedDataset makeNamedDataset(UUID id, Query query){ return dataset; } - private NamedDatasetRequest makeNamedDatasetRequest(UUID queryId){ + private NamedDatasetRequest makeNamedDatasetRequest(UUID queryId) { NamedDatasetRequest request = new NamedDatasetRequest(); request.setName(testName); request.setQueryId(queryId); @@ -76,7 +79,7 @@ public void getNamedDataset_success() { // When the request is recieved Optional> response = namedDatasetService.getNamedDatasets(user); - + // Then return a non-empty optional assertTrue(response.isPresent()); } @@ -152,9 +155,9 @@ public void addNamedDataset_success() { // Then return a non-empty optional assertTrue(response.isPresent()); - assertEquals("related user is saved", user, response.get().getUser()); - assertEquals("related name is saved", testName, response.get().getName()); - assertEquals("related query is saved", queryId, response.get().getQuery().getUuid()); + assertEquals(user, response.get().getUser(), "related user is saved"); + assertEquals(testName, response.get().getName(), "related name is saved"); + assertEquals(queryId, response.get().getQuery().getUuid(), "related query is saved"); } @Test @@ -175,7 +178,7 @@ public void addNamedDataset_metadataSet_success() { // Then return a non-empty optional assertTrue(response.isPresent()); - assertEquals("related metadata is saved", testValue, response.get().getMetadata().get(testKey)); + assertEquals(testValue, response.get().getMetadata().get(testKey), "related metadata is saved"); } @Test @@ -225,7 +228,7 @@ public void updateNamedDataset_changeName_success() { // Then return a non-empty optional assertTrue(response.isPresent()); - assertEquals("new name id is saved", newName, response.get().getName()); + assertEquals(newName, response.get().getName(), "new name id is saved"); } @Test @@ -244,7 +247,7 @@ public void updateNamedDataset_changeArchiveState_success() { // Then return a non-empty optional assertTrue(response.isPresent()); - assertEquals("new archive state is retained", true, response.get().getArchived()); + assertEquals(true, response.get().getArchived(), "new archive state is retained"); } @Test @@ -270,7 +273,7 @@ public void updateNamedDataset_changeMetadata_success() { // Then return a non-empty optional assertTrue(response.isPresent()); - assertEquals("new metadata is retained", testValue, response.get().getMetadata().get(testKey)); + assertEquals(testValue, response.get().getMetadata().get(testKey), "new metadata is retained"); } @Test @@ -292,9 +295,9 @@ public void updateNamedDataset_changeQueryId_success() { // Then return a non-empty optional assertTrue(response.isPresent()); - assertEquals("new query id is saved", newQueryId, response.get().getQuery().getUuid()); + assertEquals(newQueryId, response.get().getQuery().getUuid(), "new query id is saved"); } - + @Test public void updateNamedDataset_noNamedDatasetWithId() { // Given there is no named dataset in the database with this id diff --git a/pic-sure-api-war/src/test/java/edu/harvard/dbmi/avillach/service/SiteParsingServiceTest.java b/pic-sure-api-war/src/test/java/edu/harvard/dbmi/avillach/service/SiteParsingServiceTest.java index 22c63dda2..73f5ff6a8 100644 --- a/pic-sure-api-war/src/test/java/edu/harvard/dbmi/avillach/service/SiteParsingServiceTest.java +++ b/pic-sure-api-war/src/test/java/edu/harvard/dbmi/avillach/service/SiteParsingServiceTest.java @@ -2,20 +2,21 @@ import edu.harvard.dbmi.avillach.data.entity.Site; import edu.harvard.dbmi.avillach.data.repository.SiteRepository; -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; import java.util.List; import java.util.Optional; -import static org.junit.Assert.assertEquals; - -@RunWith(MockitoJUnitRunner.class) +@MockitoSettings(strictness = Strictness.WARN) +@ExtendWith(MockitoExtension.class) public class SiteParsingServiceTest { @InjectMocks @@ -30,26 +31,22 @@ public void shouldParse() { site.setCode("BCH"); site.setName("Bowston Children's Hospital"); site.setDomain("childrens.harvard.edu"); - Mockito - .when(repository.getByColumn("domain", "childrens.harvard.edu")) - .thenReturn(List.of(site)); + Mockito.when(repository.getByColumn("domain", "childrens.harvard.edu")).thenReturn(List.of(site)); Optional actual = subject.parseSiteOfOrigin("aaaaaaah@childrens.harvard.edu"); Optional expected = Optional.of("BCH"); - Assert.assertEquals(expected, actual); + Assertions.assertEquals(expected, actual); } @Test public void shouldFailWhenNoSite() { - Mockito - .when(repository.getByColumn("domain", "childrens.harvard.edu")) - .thenReturn(List.of()); + Mockito.when(repository.getByColumn("domain", "childrens.harvard.edu")).thenReturn(List.of()); Optional actual = subject.parseSiteOfOrigin("aaaaaaah@childrens.harvard.edu"); Optional expected = Optional.empty(); - Assert.assertEquals(expected, actual); + Assertions.assertEquals(expected, actual); } @Test @@ -62,13 +59,11 @@ public void shouldFailWhenManySites() { siteB.setCode("CHOP"); siteB.setName("Children's Hospital of Philly"); siteB.setDomain("edu"); - Mockito - .when(repository.getByColumn("domain", "edu")) - .thenReturn(List.of(siteA, siteB)); + Mockito.when(repository.getByColumn("domain", "edu")).thenReturn(List.of(siteA, siteB)); Optional actual = subject.parseSiteOfOrigin("aaaaaaah@edu"); Optional expected = Optional.empty(); - Assert.assertEquals(expected, actual); + Assertions.assertEquals(expected, actual); } -} \ No newline at end of file +} diff --git a/pic-sure-api-war/src/test/java/edu/harvard/dbmi/avillach/service/SystemServiceTest.java b/pic-sure-api-war/src/test/java/edu/harvard/dbmi/avillach/service/SystemServiceTest.java index 354ca31ec..2d0309b83 100644 --- a/pic-sure-api-war/src/test/java/edu/harvard/dbmi/avillach/service/SystemServiceTest.java +++ b/pic-sure-api-war/src/test/java/edu/harvard/dbmi/avillach/service/SystemServiceTest.java @@ -1,188 +1,194 @@ package edu.harvard.dbmi.avillach.service; import static com.github.tomakehurst.wiremock.client.WireMock.*; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.*; import java.util.ArrayList; import java.util.List; -import org.junit.Rule; -import org.junit.Test; - -import com.github.tomakehurst.wiremock.junit.WireMockRule; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; import edu.harvard.dbmi.avillach.PicSureWarInit; + +import com.github.tomakehurst.wiremock.core.WireMockConfiguration; +import com.github.tomakehurst.wiremock.junit5.WireMockExtension; import edu.harvard.dbmi.avillach.data.entity.Resource; import edu.harvard.dbmi.avillach.data.repository.ResourceRepository; public class SystemServiceTest { - @Rule - public WireMockRule wireMockRule = new WireMockRule(0); - - private int port; - - private void tokenIntrospectionStub(int status, String tokenIntrospectionResult) { - stubFor(post(urlEqualTo("/introspection_endpoint")) - .willReturn(aResponse() - .withStatus(status) - .withHeader("Content-Type", "application/json") - .withBody("{\"active\":" + tokenIntrospectionResult + ",\"sub\":\"TEST_USER\"}"))); - } - - private void resourceStub(int status) { - stubFor(post(urlEqualTo("/resource")) - .willReturn(aResponse() - .withStatus(status) - .withHeader("Content-Type", "application/json") - .withBody("{\"info\":\"foobar\"}"))); - } - - - private SystemService basicService() { - SystemService service = new SystemService(); - service.picSureWarInit = mock(PicSureWarInit.class); - when(service.picSureWarInit.getToken_introspection_token()).thenReturn("TOKEN"); - when(service.picSureWarInit.getToken_introspection_url()).thenReturn( - "http://localhost:" + port + "/introspection_endpoint"); - service.init(); - return service; - } - - @Test - public void testStatusDegradedIfResourceRepositoryReturnsNull() { - SystemService service = basicService(); - service.resourceRepo = mock(ResourceRepository.class); - when(service.resourceRepo.list()).thenReturn(null); - String status = service.status(); - assertEquals(status, SystemService.ONE_OR_MORE_COMPONENTS_DEGRADED); - } - - @Test - public void testStatusDegradedIfResourcesNotDefined() { - SystemService service = basicService(); - service.resourceRepo = mock(ResourceRepository.class); - when(service.resourceRepo.list()).thenReturn(new ArrayList()); - String status = service.status(); - assertEquals(status, SystemService.ONE_OR_MORE_COMPONENTS_DEGRADED); - } - - @Test - public void testStatusDegradedIfResourceRepoThrowsException() { - SystemService service = basicService(); - service.resourceRepo = mock(ResourceRepository.class); - when(service.resourceRepo.list()).thenThrow(RuntimeException.class); - String status = service.status(); - assertEquals(status, SystemService.ONE_OR_MORE_COMPONENTS_DEGRADED); - } - - @Test - public void testThrowsExceptionOnStartupIfTokenIntrospectionTokenNotConfigured() { - SystemService service = basicService(); - when(service.picSureWarInit.getToken_introspection_token()).thenReturn(null); - try{ - service.token_introspection_token = null; - service.init(); - }catch(Exception e) { - return; - } - assertTrue("Expected an exception to be thrown.", false); - } - - @Test - public void testThrowsExceptionOnStartupIfTokenIntrospectionUrlNotConfigured() { - SystemService service = basicService(); - when(service.picSureWarInit.getToken_introspection_url()).thenReturn(null); - try{ - service.token_introspection_url = null; - service.init(); - }catch(Exception e) { - return; - } - assertTrue("Expected an exception to be thrown.", false); - } - - @Test - public void testStatusDegradedIfTokenIntrospectionFails() { - tokenIntrospectionStub(500, "false"); - SystemService service = basicService(); - service.resourceRepo = mock(ResourceRepository.class); - when(service.resourceRepo.list()).thenReturn(List.of(mock(Resource.class))); - String status = service.status(); - assertEquals(status, SystemService.ONE_OR_MORE_COMPONENTS_DEGRADED); - } - - @Test - public void testStatusDegradedIfTokenIntrospectionFailsDueToBadToken() { - tokenIntrospectionStub(401, "false"); - SystemService service = basicService(); - service.resourceRepo = mock(ResourceRepository.class); - when(service.resourceRepo.list()).thenReturn(List.of(mock(Resource.class))); - String status = service.status(); - assertEquals(status, SystemService.ONE_OR_MORE_COMPONENTS_DEGRADED); - } - - @Test - public void testStatusDegradedIfResourceUnreachable() { - tokenIntrospectionStub(200, "true"); - resourceStub(500); - SystemService service = basicService(); - service.resourceRepo = mock(ResourceRepository.class); - Resource resource = mock(Resource.class); - when(resource.getResourceRSPath()).thenReturn("http://localhost:"+port+"/resource"); - when(service.resourceRepo.list()).thenReturn(List.of(resource)); - String status = service.status(); - assertEquals(status, SystemService.ONE_OR_MORE_COMPONENTS_DEGRADED); - } - - @Test - public void testStatusRunningIfNothingIsWrong() { - tokenIntrospectionStub(200, "true"); - resourceStub(200); - SystemService service = basicService(); - service.resourceRepo = mock(ResourceRepository.class); - Resource resource = mock(Resource.class); - when(resource.getResourceRSPath()).thenReturn("http://localhost:"+port+"/resource"); - when(service.resourceRepo.list()).thenReturn(List.of(resource)); - String status = service.status(); - assertEquals(status, SystemService.ONE_OR_MORE_COMPONENTS_DEGRADED); - } - - @Test - public void testServiceOnlyChecksStatusOncePerMaxTestFrequency() throws Exception { - tokenIntrospectionStub(200, "true"); - resourceStub(200); - SystemService service = basicService(); - service.resourceRepo = mock(ResourceRepository.class); - Resource resource = mock(Resource.class); - when(resource.getResourceRSPath()).thenReturn("http://localhost:"+port+"/resource"); - when(service.resourceRepo.list()).thenReturn(List.of(resource)); - String status = service.status(); - assertEquals(status, SystemService.ONE_OR_MORE_COMPONENTS_DEGRADED); - SystemService.max_test_frequency = 200; - Thread.sleep(100); - status = service.status(); - assertEquals(status, SystemService.ONE_OR_MORE_COMPONENTS_DEGRADED); - verify(service.resourceRepo, atMost(1)).list(); - } - - @Test - public void testServiceRechecksStatusAfterMaxTestFrequency() throws Exception { - tokenIntrospectionStub(200, "true"); - resourceStub(200); - SystemService service = basicService(); - service.resourceRepo = mock(ResourceRepository.class); - Resource resource = mock(Resource.class); - when(resource.getResourceRSPath()).thenReturn("http://localhost:"+port+"/resource"); - when(service.resourceRepo.list()).thenReturn(List.of(resource)); - String status = service.status(); - assertEquals(status, SystemService.ONE_OR_MORE_COMPONENTS_DEGRADED); - SystemService.max_test_frequency = 100; - Thread.sleep(200); - status = service.status(); - assertEquals(status, SystemService.ONE_OR_MORE_COMPONENTS_DEGRADED); - verify(service.resourceRepo, atLeast(2)).list(); - } + @RegisterExtension + public WireMockExtension wireMockRule = WireMockExtension.newInstance().options(WireMockConfiguration.options().port(0)).build(); + + private int port; + + @org.junit.jupiter.api.BeforeEach + public void setup() { + this.port = wireMockRule.getPort(); + com.github.tomakehurst.wiremock.client.WireMock.configureFor(this.port); + } + + private void tokenIntrospectionStub(int status, String tokenIntrospectionResult) { + stubFor( + post(urlEqualTo("/introspection_endpoint")).willReturn( + aResponse().withStatus(status).withHeader("Content-Type", "application/json") + .withBody("{\"active\":" + tokenIntrospectionResult + ",\"sub\":\"TEST_USER\"}") + ) + ); + } + + private void resourceStub(int status) { + stubFor( + post(urlEqualTo("/resource")) + .willReturn(aResponse().withStatus(status).withHeader("Content-Type", "application/json").withBody("{\"info\":\"foobar\"}")) + ); + } + + + private SystemService basicService() { + SystemService service = new SystemService(); + service.picSureWarInit = mock(PicSureWarInit.class); + when(service.picSureWarInit.getToken_introspection_token()).thenReturn("TOKEN"); + when(service.picSureWarInit.getToken_introspection_url()).thenReturn("http://localhost:" + port + "/introspection_endpoint"); + service.init(); + return service; + } + + @Test + public void testStatusDegradedIfResourceRepositoryReturnsNull() { + SystemService service = basicService(); + service.resourceRepo = mock(ResourceRepository.class); + when(service.resourceRepo.list()).thenReturn(null); + String status = service.status(); + assertEquals(status, SystemService.ONE_OR_MORE_COMPONENTS_DEGRADED); + } + + @Test + public void testStatusDegradedIfResourcesNotDefined() { + SystemService service = basicService(); + service.resourceRepo = mock(ResourceRepository.class); + when(service.resourceRepo.list()).thenReturn(new ArrayList()); + String status = service.status(); + assertEquals(status, SystemService.ONE_OR_MORE_COMPONENTS_DEGRADED); + } + + @Test + public void testStatusDegradedIfResourceRepoThrowsException() { + SystemService service = basicService(); + service.resourceRepo = mock(ResourceRepository.class); + when(service.resourceRepo.list()).thenThrow(RuntimeException.class); + String status = service.status(); + assertEquals(status, SystemService.ONE_OR_MORE_COMPONENTS_DEGRADED); + } + + @Test + public void testThrowsExceptionOnStartupIfTokenIntrospectionTokenNotConfigured() { + SystemService service = basicService(); + when(service.picSureWarInit.getToken_introspection_token()).thenReturn(null); + try { + service.token_introspection_token = null; + service.init(); + } catch (Exception e) { + return; + } + assertTrue(false, "Expected an exception to be thrown."); + } + + @Test + public void testThrowsExceptionOnStartupIfTokenIntrospectionUrlNotConfigured() { + SystemService service = basicService(); + when(service.picSureWarInit.getToken_introspection_url()).thenReturn(null); + try { + service.token_introspection_url = null; + service.init(); + } catch (Exception e) { + return; + } + assertTrue(false, "Expected an exception to be thrown."); + } + + @Test + public void testStatusDegradedIfTokenIntrospectionFails() { + tokenIntrospectionStub(500, "false"); + SystemService service = basicService(); + service.resourceRepo = mock(ResourceRepository.class); + when(service.resourceRepo.list()).thenReturn(List.of(mock(Resource.class))); + String status = service.status(); + assertEquals(status, SystemService.ONE_OR_MORE_COMPONENTS_DEGRADED); + } + + @Test + public void testStatusDegradedIfTokenIntrospectionFailsDueToBadToken() { + tokenIntrospectionStub(401, "false"); + SystemService service = basicService(); + service.resourceRepo = mock(ResourceRepository.class); + when(service.resourceRepo.list()).thenReturn(List.of(mock(Resource.class))); + String status = service.status(); + assertEquals(status, SystemService.ONE_OR_MORE_COMPONENTS_DEGRADED); + } + + @Test + public void testStatusDegradedIfResourceUnreachable() { + tokenIntrospectionStub(200, "true"); + resourceStub(500); + SystemService service = basicService(); + service.resourceRepo = mock(ResourceRepository.class); + Resource resource = mock(Resource.class); + when(resource.getResourceRSPath()).thenReturn("http://localhost:" + port + "/resource"); + when(service.resourceRepo.list()).thenReturn(List.of(resource)); + String status = service.status(); + assertEquals(status, SystemService.ONE_OR_MORE_COMPONENTS_DEGRADED); + } + + @Test + public void testStatusRunningIfNothingIsWrong() { + tokenIntrospectionStub(200, "true"); + resourceStub(200); + SystemService service = basicService(); + service.resourceRepo = mock(ResourceRepository.class); + Resource resource = mock(Resource.class); + when(resource.getResourceRSPath()).thenReturn("http://localhost:" + port + "/resource"); + when(service.resourceRepo.list()).thenReturn(List.of(resource)); + String status = service.status(); + assertEquals(status, SystemService.ONE_OR_MORE_COMPONENTS_DEGRADED); + } + + @Test + public void testServiceOnlyChecksStatusOncePerMaxTestFrequency() throws Exception { + tokenIntrospectionStub(200, "true"); + resourceStub(200); + SystemService service = basicService(); + service.resourceRepo = mock(ResourceRepository.class); + Resource resource = mock(Resource.class); + when(resource.getResourceRSPath()).thenReturn("http://localhost:" + port + "/resource"); + when(service.resourceRepo.list()).thenReturn(List.of(resource)); + String status = service.status(); + assertEquals(status, SystemService.ONE_OR_MORE_COMPONENTS_DEGRADED); + SystemService.max_test_frequency = 200; + Thread.sleep(100); + status = service.status(); + assertEquals(status, SystemService.ONE_OR_MORE_COMPONENTS_DEGRADED); + verify(service.resourceRepo, atMost(1)).list(); + } + + @Test + public void testServiceRechecksStatusAfterMaxTestFrequency() throws Exception { + tokenIntrospectionStub(200, "true"); + resourceStub(200); + SystemService service = basicService(); + service.resourceRepo = mock(ResourceRepository.class); + Resource resource = mock(Resource.class); + when(resource.getResourceRSPath()).thenReturn("http://localhost:" + port + "/resource"); + when(service.resourceRepo.list()).thenReturn(List.of(resource)); + String status = service.status(); + assertEquals(status, SystemService.ONE_OR_MORE_COMPONENTS_DEGRADED); + SystemService.max_test_frequency = 100; + Thread.sleep(200); + status = service.status(); + assertEquals(status, SystemService.ONE_OR_MORE_COMPONENTS_DEGRADED); + verify(service.resourceRepo, atLeast(2)).list(); + } } diff --git a/pic-sure-resources/pic-sure-aggregate-data-sharing-resource/pom.xml b/pic-sure-resources/pic-sure-aggregate-data-sharing-resource/pom.xml index e057643c9..485389cbb 100644 --- a/pic-sure-resources/pic-sure-aggregate-data-sharing-resource/pom.xml +++ b/pic-sure-resources/pic-sure-aggregate-data-sharing-resource/pom.xml @@ -81,7 +81,7 @@ com.github.tomakehurst - wiremock-standalone + wiremock-jre8 test @@ -89,6 +89,11 @@ jersey-common test + + org.junit.jupiter + junit-jupiter + test + edu.harvard.dbmi.avillach pic-sure-logging-client diff --git a/pic-sure-resources/pic-sure-aggregate-data-sharing-resource/src/test/java/edu/harvard/hms/dbmi/avillach/AggregateDataSharingResourceRSAcceptanceTests.java b/pic-sure-resources/pic-sure-aggregate-data-sharing-resource/src/test/java/edu/harvard/hms/dbmi/avillach/AggregateDataSharingResourceRSAcceptanceTests.java index 3114d6826..0f9682a90 100644 --- a/pic-sure-resources/pic-sure-aggregate-data-sharing-resource/src/test/java/edu/harvard/hms/dbmi/avillach/AggregateDataSharingResourceRSAcceptanceTests.java +++ b/pic-sure-resources/pic-sure-aggregate-data-sharing-resource/src/test/java/edu/harvard/hms/dbmi/avillach/AggregateDataSharingResourceRSAcceptanceTests.java @@ -5,20 +5,23 @@ import edu.harvard.dbmi.avillach.util.exception.ResourceInterfaceException; import org.glassfish.jersey.message.internal.OutboundJaxrsResponse; import org.glassfish.jersey.message.internal.OutboundMessageContext; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; -import com.github.tomakehurst.wiremock.junit.WireMockClassRule; - +import com.github.tomakehurst.wiremock.junit5.WireMockExtension; +import com.github.tomakehurst.wiremock.core.WireMockConfiguration; import edu.harvard.dbmi.avillach.domain.GeneralQueryRequest; import static com.github.tomakehurst.wiremock.client.WireMock.*; -import static org.junit.Assert.*; -import static org.mockito.Mockito.*; +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.mockito.Mockito.mock; +import static org.mockito.Mockito.when; import java.io.IOException; import java.util.ArrayList; @@ -53,11 +56,12 @@ public class AggregateDataSharingResourceRSAcceptanceTests { private final static int port = 40000; private final static String testURL = "http://localhost:40000/"; - @Rule - public WireMockClassRule wireMockRule = new WireMockClassRule(port); + @org.junit.jupiter.api.extension.RegisterExtension + public WireMockExtension wireMockRule = WireMockExtension.newInstance().options(WireMockConfiguration.options().port(port)).build(); - @Before + @BeforeEach public void setup() throws IOException { + com.github.tomakehurst.wiremock.client.WireMock.configureFor(port); mockProperties = mock(ApplicationProperties.class); when(mockProperties.getTargetResourceId()).thenReturn("f0317fa9-0945-4390-993a-840416e97d13"); when(mockProperties.getTargetPicsureObfuscationThreshold()).thenReturn(10); @@ -76,8 +80,7 @@ public void setup() throws IOException { // Stub for study consents which is now called for every CROSS_COUNT query wireMockRule.stubFor( - post(urlEqualTo("/search")) - .withRequestBody(matchingJsonPath("$.query", containing("_studies_consents"))) + post(urlEqualTo("/search")).withRequestBody(matchingJsonPath("$.query", containing("_studies_consents"))) .willReturn(aResponse().withStatus(200).withBody("{\"results\": {\"phenotypes\": {}}}")) ); @@ -318,14 +321,16 @@ private static GeneralQueryRequest createRequest(Object query, Map queryMap = (Map) request.getQuery(); - queryMap.remove("expectedResultType"); - request.setQuery(queryMap); - subject.querySync(request); + assertThrows(ProtocolException.class, () -> { + GeneralQueryRequest request = getTestQuery(); + @SuppressWarnings("unchecked") + Map queryMap = (Map) request.getQuery(); + queryMap.remove("expectedResultType"); + request.setQuery(queryMap); + subject.querySync(request); + }); } @Test @@ -333,19 +338,16 @@ public void testCrossCountQueryModifiesRequest() throws IOException { // Mock /search for consents // We need to escape backslashes for Java string literals and JSON // JSON: "\\PHENO\\CONSENT1\\" -> Java String: "\"\\\\PHENO\\\\CONSENT1\\\\\"" - String consentResponseJson = "{\"results\": {\"phenotypes\": {\"\\\\PHENO\\\\CONSENT1\\\\\": {}, \"\\\\PHENO\\\\CONSENT2\\\\\": {}}}}"; + String consentResponseJson = + "{\"results\": {\"phenotypes\": {\"\\\\PHENO\\\\CONSENT1\\\\\": {}, \"\\\\PHENO\\\\CONSENT2\\\\\": {}}}}"; wireMockRule.stubFor( - post(urlEqualTo("/search")) - .withRequestBody(matchingJsonPath("$.query", containing("_studies_consents"))) + post(urlEqualTo("/search")).withRequestBody(matchingJsonPath("$.query", containing("_studies_consents"))) .willReturn(aResponse().withStatus(200).withBody(consentResponseJson)) ); // Mock /query/sync - wireMockRule.stubFor( - post(urlEqualTo("/query/sync")) - .willReturn(aResponse().withStatus(200).withBody("{}")) - ); + wireMockRule.stubFor(post(urlEqualTo("/query/sync")).willReturn(aResponse().withStatus(200).withBody("{}"))); GeneralQueryRequest request = getTestQuery(); @SuppressWarnings("unchecked") @@ -357,29 +359,27 @@ public void testCrossCountQueryModifiesRequest() throws IOException { subject.querySync(request); // Verify /query/sync called with modified body - verify(postRequestedFor(urlEqualTo("/query/sync")) - .withRequestBody(matchingJsonPath("$.query.crossCountFields", containing("CONSENT1"))) - .withRequestBody(matchingJsonPath("$.query.crossCountFields", containing("CONSENT2"))) - .withRequestBody(matchingJsonPath("$.query.expectedResultType", equalTo("CROSS_COUNT"))) + verify( + postRequestedFor(urlEqualTo("/query/sync")) + .withRequestBody(matchingJsonPath("$.query.crossCountFields", containing("CONSENT1"))) + .withRequestBody(matchingJsonPath("$.query.crossCountFields", containing("CONSENT2"))) + .withRequestBody(matchingJsonPath("$.query.expectedResultType", equalTo("CROSS_COUNT"))) ); } @Test public void testCrossCountQueryModifiesRequestV3() throws IOException { // Mock /search for consents - String consentResponseJson = "{\"results\": {\"phenotypes\": {\"\\\\PHENO\\\\CONSENT1\\\\\": {}, \"\\\\PHENO\\\\CONSENT2\\\\\": {}}}}"; + String consentResponseJson = + "{\"results\": {\"phenotypes\": {\"\\\\PHENO\\\\CONSENT1\\\\\": {}, \"\\\\PHENO\\\\CONSENT2\\\\\": {}}}}"; wireMockRule.stubFor( - post(urlEqualTo("/search")) - .withRequestBody(matchingJsonPath("$.query", containing("_studies_consents"))) + post(urlEqualTo("/search")).withRequestBody(matchingJsonPath("$.query", containing("_studies_consents"))) .willReturn(aResponse().withStatus(200).withBody(consentResponseJson)) ); // Mock /v3/query/sync (V3 appends /v3 prefix to path in getHttpResponse) - wireMockRule.stubFor( - post(urlEqualTo("/v3/query/sync")) - .willReturn(aResponse().withStatus(200).withBody("{}")) - ); + wireMockRule.stubFor(post(urlEqualTo("/v3/query/sync")).willReturn(aResponse().withStatus(200).withBody("{}"))); GeneralQueryRequest request = getTestQuery(); @SuppressWarnings("unchecked") @@ -390,19 +390,16 @@ public void testCrossCountQueryModifiesRequestV3() throws IOException { subjectV3.querySync(request); // Verify /v3/query/sync called with modified body using "select" - verify(postRequestedFor(urlEqualTo("/v3/query/sync")) - .withRequestBody(matchingJsonPath("$.query.select", containing("CONSENT1"))) - .withRequestBody(matchingJsonPath("$.query.select", containing("CONSENT2"))) - .withRequestBody(matchingJsonPath("$.query.expectedResultType", equalTo("CROSS_COUNT"))) + verify( + postRequestedFor(urlEqualTo("/v3/query/sync")).withRequestBody(matchingJsonPath("$.query.select", containing("CONSENT1"))) + .withRequestBody(matchingJsonPath("$.query.select", containing("CONSENT2"))) + .withRequestBody(matchingJsonPath("$.query.expectedResultType", equalTo("CROSS_COUNT"))) ); } @Test public void testOtherQueryTypeDoesNotModifyRequest() throws IOException { - wireMockRule.stubFor( - post(urlEqualTo("/query/sync")) - .willReturn(aResponse().withStatus(200).withBody("100")) - ); + wireMockRule.stubFor(post(urlEqualTo("/query/sync")).willReturn(aResponse().withStatus(200).withBody("100"))); GeneralQueryRequest request = getTestQuery(); @SuppressWarnings("unchecked") @@ -413,9 +410,9 @@ public void testOtherQueryTypeDoesNotModifyRequest() throws IOException { subject.querySync(request); - verify(postRequestedFor(urlEqualTo("/query/sync")) - .withRequestBody(matchingJsonPath("$.query.expectedResultType", equalTo("COUNT"))) - .withRequestBody(notMatching(".*crossCountFields.*")) + verify( + postRequestedFor(urlEqualTo("/query/sync")).withRequestBody(matchingJsonPath("$.query.expectedResultType", equalTo("COUNT"))) + .withRequestBody(notMatching(".*crossCountFields.*")) ); } diff --git a/pic-sure-resources/pic-sure-aggregate-data-sharing-resource/src/test/java/edu/harvard/hms/dbmi/avillach/ObfuscatedCountShapeTest.java b/pic-sure-resources/pic-sure-aggregate-data-sharing-resource/src/test/java/edu/harvard/hms/dbmi/avillach/ObfuscatedCountShapeTest.java index 074f2145d..a623f36b2 100644 --- a/pic-sure-resources/pic-sure-aggregate-data-sharing-resource/src/test/java/edu/harvard/hms/dbmi/avillach/ObfuscatedCountShapeTest.java +++ b/pic-sure-resources/pic-sure-aggregate-data-sharing-resource/src/test/java/edu/harvard/hms/dbmi/avillach/ObfuscatedCountShapeTest.java @@ -1,7 +1,7 @@ package edu.harvard.hms.dbmi.avillach; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -10,12 +10,12 @@ import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** - * Verifies that the obfuscation methods produce the rich {count, display} shape - * required by the visualization-resource for Plotly-compatible chart values. + * Verifies that the obfuscation methods produce the rich {count, display} shape required by the visualization-resource for + * Plotly-compatible chart values. * * Exercises both V1 and V3 implementations since they carry parallel copies. */ @@ -24,7 +24,7 @@ public class ObfuscatedCountShapeTest { private AggregateDataSharingResourceRS subject; private AggregateDataSharingResourceRSV3 subjectV3; - @Before + @BeforeEach public void setup() { ApplicationProperties props = mock(ApplicationProperties.class); when(props.getTargetPicsureObfuscationThreshold()).thenReturn(10); @@ -38,17 +38,17 @@ public void setup() { public void applyThresholdFloor_belowThreshold_returnsZeroCountWithThresholdBandAndLessThanDisplay() { Optional result = subject.applyThresholdFloor(3); - assertTrue("Below-threshold counts must be obfuscated", result.isPresent()); + assertTrue(result.isPresent(), "Below-threshold counts must be obfuscated"); assertEquals(0, result.get().count()); assertEquals("< 10", result.get().display()); - assertEquals("Band [max(0, 0-9), 0+9] renders 0..threshold-1", Integer.valueOf(9), result.get().variance()); + assertEquals(Integer.valueOf(9), result.get().variance(), "Band [max(0, 0-9), 0+9] renders 0..threshold-1"); } @Test public void applyThresholdFloor_zero_returnsZeroCountWithThresholdBandAndLessThanDisplay() { Optional result = subject.applyThresholdFloor(0); - assertTrue("Zero is treated as below-threshold (privacy floor)", result.isPresent()); + assertTrue(result.isPresent(), "Zero is treated as below-threshold (privacy floor)"); assertEquals(0, result.get().count()); assertEquals("< 10", result.get().display()); assertEquals(Integer.valueOf(9), result.get().variance()); @@ -69,16 +69,16 @@ public void applyThresholdFloor_stringOverload_nonNumeric_returnsEmpty() { public void randomize_appliesVariance_returnsNumericDisplayAndVariance() { ObfuscatedCount result = subject.randomize(100, 2); - assertEquals("count must be the numeric obfuscated value", 102, result.count()); - assertEquals("display must carry the formatted variance string", "102 ±3", result.display()); - assertEquals("variance must carry the configured band half-width", Integer.valueOf(3), result.variance()); + assertEquals(102, result.count(), "count must be the numeric obfuscated value"); + assertEquals("102 ±3", result.display(), "display must carry the formatted variance string"); + assertEquals(Integer.valueOf(3), result.variance(), "variance must carry the configured band half-width"); } @Test public void randomize_floorsAtThreshold_whenVarianceTakesItBelow() { ObfuscatedCount result = subject.randomize(10, -5); - assertEquals("Floored at threshold so the numeric stays >= threshold", 10, result.count()); + assertEquals(10, result.count(), "Floored at threshold so the numeric stays >= threshold"); assertEquals("10 ±3", result.display()); assertEquals(Integer.valueOf(3), result.variance()); } @@ -120,13 +120,12 @@ public void ofInt_factory_producesStringifiedDisplayAndNullVariance() { assertEquals(45000, result.count()); assertEquals("45000", result.display()); - assertEquals("Exact (authorized) values carry no uncertainty band", null, result.variance()); + assertEquals(null, result.variance(), "Exact (authorized) values carry no uncertainty band"); } /** - * Pins the JSON wire shape that visualization-resource (and any other consumer) deserializes against. - * If field names ever drift (e.g. someone renames the record component), this test fails BEFORE the - * cross-repo contract silently breaks in production. + * Pins the JSON wire shape that visualization-resource (and any other consumer) deserializes against. If field names ever drift (e.g. + * someone renames the record component), this test fails BEFORE the cross-repo contract silently breaks in production. */ @Test public void jsonShape_serializesAsCountDisplayAndVarianceFields() throws JsonProcessingException { @@ -145,8 +144,8 @@ public void jsonShape_serializesAsCountDisplayAndVarianceFields() throws JsonPro } /** - * Exact (authorized) values serialize variance as an explicit null, and below-threshold values pin - * the {count: 0, variance: threshold-1} encoding the frontend's band rule depends on. + * Exact (authorized) values serialize variance as an explicit null, and below-threshold values pin the {count: 0, variance: + * threshold-1} encoding the frontend's band rule depends on. */ @Test public void jsonShape_nullVarianceAndBelowThresholdEncoding() throws JsonProcessingException { diff --git a/pic-sure-resources/pic-sure-aggregate-data-sharing-resource/src/test/java/edu/harvard/hms/dbmi/avillach/ProxyPostEndpointMocker.java b/pic-sure-resources/pic-sure-aggregate-data-sharing-resource/src/test/java/edu/harvard/hms/dbmi/avillach/ProxyPostEndpointMocker.java index 256382d50..1ddfb4c65 100644 --- a/pic-sure-resources/pic-sure-aggregate-data-sharing-resource/src/test/java/edu/harvard/hms/dbmi/avillach/ProxyPostEndpointMocker.java +++ b/pic-sure-resources/pic-sure-aggregate-data-sharing-resource/src/test/java/edu/harvard/hms/dbmi/avillach/ProxyPostEndpointMocker.java @@ -3,13 +3,13 @@ import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.github.tomakehurst.wiremock.client.WireMock; -import com.github.tomakehurst.wiremock.junit.WireMockClassRule; +import com.github.tomakehurst.wiremock.junit5.WireMockExtension; /** * Prettier interface for mocking a http response. Only supports POST rn. */ public class ProxyPostEndpointMocker { - private WireMockClassRule rule; + private WireMockExtension rule; private String responseBody; @@ -20,7 +20,7 @@ public class ProxyPostEndpointMocker { private String path; - public static ProxyPostEndpointMocker start(WireMockClassRule rule) { + public static ProxyPostEndpointMocker start(WireMockExtension rule) { ProxyPostEndpointMocker mock = new ProxyPostEndpointMocker(); mock.rule = rule; return mock; @@ -47,12 +47,9 @@ public ProxyPostEndpointMocker withStatusCode(int status) { } public void commit() { - rule.stubFor(WireMock.post(WireMock.urlEqualTo(path)) - .withRequestBody(WireMock.equalToJson(requestBody)) - .willReturn(WireMock.aResponse() - .withStatus(status) - .withBody(responseBody) - ) + rule.stubFor( + WireMock.post(WireMock.urlEqualTo(path)).withRequestBody(WireMock.equalToJson(requestBody)) + .willReturn(WireMock.aResponse().withStatus(status).withBody(responseBody)) ); } diff --git a/pic-sure-resources/pic-sure-passthrough-resource/src/test/java/edu/harvard/hms/dbmi/avillach/resource/passthru/PassThroughResourceRSTest.java b/pic-sure-resources/pic-sure-passthrough-resource/src/test/java/edu/harvard/hms/dbmi/avillach/resource/passthru/PassThroughResourceRSTest.java index 18859271c..60cd6198d 100644 --- a/pic-sure-resources/pic-sure-passthrough-resource/src/test/java/edu/harvard/hms/dbmi/avillach/resource/passthru/PassThroughResourceRSTest.java +++ b/pic-sure-resources/pic-sure-passthrough-resource/src/test/java/edu/harvard/hms/dbmi/avillach/resource/passthru/PassThroughResourceRSTest.java @@ -1,7 +1,8 @@ package edu.harvard.hms.dbmi.avillach.resource.passthru; import static org.junit.jupiter.api.Assertions.*; -import static org.mockito.ArgumentMatchers.*; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.lenient; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; diff --git a/pic-sure-resources/pic-sure-resource-api/pom.xml b/pic-sure-resources/pic-sure-resource-api/pom.xml index 2d15aaa99..1e69605f5 100755 --- a/pic-sure-resources/pic-sure-resource-api/pom.xml +++ b/pic-sure-resources/pic-sure-resource-api/pom.xml @@ -46,9 +46,14 @@ mockito-core test + + org.mockito + mockito-junit-jupiter + test + com.github.tomakehurst - wiremock-standalone + wiremock-jre8 test @@ -56,15 +61,15 @@ jersey-common test + + org.junit.jupiter + junit-jupiter + test + io.swagger.core.v3 swagger-annotations - - org.junit.vintage - junit-vintage-engine - test - edu.harvard.hms.dbmi.avillach pic-sure-api-data diff --git a/pic-sure-resources/pic-sure-resource-api/src/test/java/edu/harvard/dbmi/avillach/AppTest.java b/pic-sure-resources/pic-sure-resource-api/src/test/java/edu/harvard/dbmi/avillach/AppTest.java index d8ae15963..f51361c86 100755 --- a/pic-sure-resources/pic-sure-resource-api/src/test/java/edu/harvard/dbmi/avillach/AppTest.java +++ b/pic-sure-resources/pic-sure-resource-api/src/test/java/edu/harvard/dbmi/avillach/AppTest.java @@ -1,38 +1,19 @@ -package edu.harvard.dbmi.avillach; - -import junit.framework.Test; -import junit.framework.TestCase; -import junit.framework.TestSuite; - -/** - * Unit test for simple App. - */ -public class AppTest - extends TestCase -{ - /** - * Create the test case - * - * @param testName name of the test case - */ - public AppTest( String testName ) - { - super( testName ); - } - - /** - * @return the suite of tests being tested - */ - public static Test suite() - { - return new TestSuite( AppTest.class ); - } - - /** - * Rigourous Test :-) - */ - public void testApp() - { - assertTrue( true ); - } -} +package edu.harvard.dbmi.avillach; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Unit test for simple App. + */ +public class AppTest { + + /** + * Rigourous Test :-) + */ + @Test + public void testApp() { + assertTrue(true); + } +} diff --git a/pic-sure-resources/pic-sure-resource-api/src/test/java/edu/harvard/dbmi/avillach/domain/PaginatedSearchResultTest.java b/pic-sure-resources/pic-sure-resource-api/src/test/java/edu/harvard/dbmi/avillach/domain/PaginatedSearchResultTest.java index 0db50028d..54d53ee2e 100644 --- a/pic-sure-resources/pic-sure-resource-api/src/test/java/edu/harvard/dbmi/avillach/domain/PaginatedSearchResultTest.java +++ b/pic-sure-resources/pic-sure-resource-api/src/test/java/edu/harvard/dbmi/avillach/domain/PaginatedSearchResultTest.java @@ -1,12 +1,14 @@ package edu.harvard.dbmi.avillach.domain; +import org.junit.jupiter.api.Test; + import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.Test; -import static org.junit.Assert.*; import java.util.List; +import static org.junit.jupiter.api.Assertions.*; + public class PaginatedSearchResultTest { @Test diff --git a/pic-sure-resources/pic-sure-resource-api/src/test/java/edu/harvard/dbmi/avillach/domain/QueryRequestTest.java b/pic-sure-resources/pic-sure-resource-api/src/test/java/edu/harvard/dbmi/avillach/domain/QueryRequestTest.java index 9e52a3580..42ccc4d56 100644 --- a/pic-sure-resources/pic-sure-resource-api/src/test/java/edu/harvard/dbmi/avillach/domain/QueryRequestTest.java +++ b/pic-sure-resources/pic-sure-resource-api/src/test/java/edu/harvard/dbmi/avillach/domain/QueryRequestTest.java @@ -3,8 +3,8 @@ import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.util.HashMap; import java.util.UUID; @@ -22,8 +22,8 @@ public void shouldSerializeGeneralQueryRequest() throws JsonProcessingException QueryRequest actual = mapper.readValue(json, QueryRequest.class); - Assert.assertEquals(GeneralQueryRequest.class, actual.getClass()); - Assert.assertEquals(expected.getResourceUUID(), actual.getResourceUUID()); + Assertions.assertEquals(GeneralQueryRequest.class, actual.getClass()); + Assertions.assertEquals(expected.getResourceUUID(), actual.getResourceUUID()); } @Test @@ -38,8 +38,8 @@ public void shouldSerializeGICRequest() throws JsonProcessingException { QueryRequest actual = mapper.readValue(json, QueryRequest.class); - Assert.assertEquals(FederatedQueryRequest.class, actual.getClass()); - Assert.assertEquals(expected.getResourceUUID(), actual.getResourceUUID()); + Assertions.assertEquals(FederatedQueryRequest.class, actual.getClass()); + Assertions.assertEquals(expected.getResourceUUID(), actual.getResourceUUID()); } @Test @@ -48,25 +48,27 @@ public void shouldSerializeRequestWithNoType() throws JsonProcessingException { String json = "{\"resourceCredentials\":{},\"query\":null,\"resourceUUID\":\"e4513cca-12c0-4fe2-b2fd-5d05b821056c\"}"; QueryRequest actual = mapper.readValue(json, QueryRequest.class); - Assert.assertEquals(GeneralQueryRequest.class, actual.getClass()); + Assertions.assertEquals(GeneralQueryRequest.class, actual.getClass()); } @Test public void shouldSerializeRequestWithNoTypeWithGICFields() throws JsonProcessingException { - String json = "{\"resourceCredentials\":{},\"query\":null,\"resourceUUID\":\"716d744f-9c89-40af-b572-222c1b20848f\",\"commonAreaUUID\":\"a79e3da0-e1fa-4626-9873-41cffd5e9115\",\"institutionOfOrigin\":\"Top secret institution (shh!)\"}"; + String json = + "{\"resourceCredentials\":{},\"query\":null,\"resourceUUID\":\"716d744f-9c89-40af-b572-222c1b20848f\",\"commonAreaUUID\":\"a79e3da0-e1fa-4626-9873-41cffd5e9115\",\"institutionOfOrigin\":\"Top secret institution (shh!)\"}"; QueryRequest actual = mapper.readValue(json, QueryRequest.class); // This is for backwards compatibility. An un-updated client should handle unknown fields gracefully - Assert.assertEquals(GeneralQueryRequest.class, actual.getClass()); + Assertions.assertEquals(GeneralQueryRequest.class, actual.getClass()); } @Test public void shouldSerializeRequestWithGICTypeAndExtraField() throws JsonProcessingException { - String json = "{\"@type\":\"FederatedQueryRequest\",\"madeUpField\":0,\"resourceCredentials\":{},\"query\":null,\"resourceUUID\":\"716d744f-9c89-40af-b572-222c1b20848f\",\"commonAreaUUID\":\"a79e3da0-e1fa-4626-9873-41cffd5e9115\",\"institutionOfOrigin\":\"Top secret institution (shh!)\"}"; + String json = + "{\"@type\":\"FederatedQueryRequest\",\"madeUpField\":0,\"resourceCredentials\":{},\"query\":null,\"resourceUUID\":\"716d744f-9c89-40af-b572-222c1b20848f\",\"commonAreaUUID\":\"a79e3da0-e1fa-4626-9873-41cffd5e9115\",\"institutionOfOrigin\":\"Top secret institution (shh!)\"}"; QueryRequest actual = mapper.readValue(json, QueryRequest.class); // This is for backwards compatibility. // An un-updated client should handle unknown fields gracefully, even when it's a GIC request - Assert.assertEquals(FederatedQueryRequest.class, actual.getClass()); + Assertions.assertEquals(FederatedQueryRequest.class, actual.getClass()); } -} \ No newline at end of file +} diff --git a/pic-sure-resources/pic-sure-resource-api/src/test/java/edu/harvard/dbmi/avillach/domain/SignedUrlResponseTest.java b/pic-sure-resources/pic-sure-resource-api/src/test/java/edu/harvard/dbmi/avillach/domain/SignedUrlResponseTest.java index 14f9d1281..c6e902cc2 100644 --- a/pic-sure-resources/pic-sure-resource-api/src/test/java/edu/harvard/dbmi/avillach/domain/SignedUrlResponseTest.java +++ b/pic-sure-resources/pic-sure-resource-api/src/test/java/edu/harvard/dbmi/avillach/domain/SignedUrlResponseTest.java @@ -1,9 +1,11 @@ package edu.harvard.dbmi.avillach.domain; +import org.junit.jupiter.api.Test; + import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.Test; -import static org.junit.Assert.*; + +import static org.junit.jupiter.api.Assertions.*; public class SignedUrlResponseTest { diff --git a/pic-sure-resources/pic-sure-resource-api/src/test/java/edu/harvard/dbmi/avillach/service/HttpClientUtilTest.java b/pic-sure-resources/pic-sure-resource-api/src/test/java/edu/harvard/dbmi/avillach/service/HttpClientUtilTest.java index 53afc1d12..bf73183b9 100644 --- a/pic-sure-resources/pic-sure-resource-api/src/test/java/edu/harvard/dbmi/avillach/service/HttpClientUtilTest.java +++ b/pic-sure-resources/pic-sure-resource-api/src/test/java/edu/harvard/dbmi/avillach/service/HttpClientUtilTest.java @@ -1,33 +1,34 @@ package edu.harvard.dbmi.avillach.service; -import static org.junit.Assert.assertEquals; +import org.junit.jupiter.api.Test; import edu.harvard.dbmi.avillach.util.HttpClientUtil; -import org.junit.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; public class HttpClientUtilTest { - @Test - public void testComposeUrl() { - String test = HttpClientUtil.composeURL("http://foo.bar.com/pic-sure", "info"); - assertEquals("http://foo.bar.com/pic-sure/info", test); - - test = HttpClientUtil.composeURL("http://foo.bar.com/pic-sure/", "info"); - assertEquals("http://foo.bar.com/pic-sure/info", test); - - test = HttpClientUtil.composeURL("http://foo.bar.com/pic-sure///", "//info"); - assertEquals("http://foo.bar.com/pic-sure/info", test); - - test = HttpClientUtil.composeURL("http://foo.bar.com/pic-sure", "info/something/something"); - assertEquals("http://foo.bar.com/pic-sure/info/something/something", test); - - test = HttpClientUtil.composeURL("http://foo.bar.com/pic-sure/", "/info"); - assertEquals("http://foo.bar.com/pic-sure/info", test); - - test = HttpClientUtil.composeURL("http://localhost:8080", "/info"); - assertEquals("http://localhost:8080/info", test); - - test = HttpClientUtil.composeURL("http://localhost:8080/", "/info"); - assertEquals("http://localhost:8080/info", test); - } + @Test + public void testComposeUrl() { + String test = HttpClientUtil.composeURL("http://foo.bar.com/pic-sure", "info"); + assertEquals("http://foo.bar.com/pic-sure/info", test); + + test = HttpClientUtil.composeURL("http://foo.bar.com/pic-sure/", "info"); + assertEquals("http://foo.bar.com/pic-sure/info", test); + + test = HttpClientUtil.composeURL("http://foo.bar.com/pic-sure///", "//info"); + assertEquals("http://foo.bar.com/pic-sure/info", test); + + test = HttpClientUtil.composeURL("http://foo.bar.com/pic-sure", "info/something/something"); + assertEquals("http://foo.bar.com/pic-sure/info/something/something", test); + + test = HttpClientUtil.composeURL("http://foo.bar.com/pic-sure/", "/info"); + assertEquals("http://foo.bar.com/pic-sure/info", test); + + test = HttpClientUtil.composeURL("http://localhost:8080", "/info"); + assertEquals("http://localhost:8080/info", test); + + test = HttpClientUtil.composeURL("http://localhost:8080/", "/info"); + assertEquals("http://localhost:8080/info", test); + } } diff --git a/pic-sure-resources/pic-sure-resource-api/src/test/java/edu/harvard/dbmi/avillach/service/ProxyWebClientTest.java b/pic-sure-resources/pic-sure-resource-api/src/test/java/edu/harvard/dbmi/avillach/service/ProxyWebClientTest.java index 6d894d865..a7b800802 100644 --- a/pic-sure-resources/pic-sure-resource-api/src/test/java/edu/harvard/dbmi/avillach/service/ProxyWebClientTest.java +++ b/pic-sure-resources/pic-sure-resource-api/src/test/java/edu/harvard/dbmi/avillach/service/ProxyWebClientTest.java @@ -8,15 +8,21 @@ import org.apache.http.StatusLine; import org.apache.http.message.BasicHeader; import org.apache.http.client.HttpClient; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.MediaType; @@ -29,9 +35,8 @@ import java.io.InputStream; import java.util.List; -import static org.junit.Assert.*; - -@RunWith(MockitoJUnitRunner.class) +@MockitoSettings(strictness = Strictness.WARN) +@ExtendWith(MockitoExtension.class) public class ProxyWebClientTest { @Mock @@ -67,7 +72,7 @@ public void shouldPostToProxy() throws IOException { Response actual = subject.postProxy("foo", "/my/cool/path", "{}", new MultivaluedHashMap<>(), null); - Assert.assertEquals(200, actual.getStatus()); + Assertions.assertEquals(200, actual.getStatus()); } @Test @@ -85,7 +90,7 @@ public void shouldGetToProxy() throws IOException { Response actual = subject.getProxy("bar", "/my/cool/path", new MultivaluedHashMap<>(), null); - Assert.assertEquals(200, actual.getStatus()); + Assertions.assertEquals(200, actual.getStatus()); } @Test @@ -152,8 +157,7 @@ public void shouldForwardSessionIdHeader() throws IOException { Mockito.when(client.execute(Mockito.argThat(request -> { if (request instanceof HttpPost) { HttpPost post = (HttpPost) request; - return post.getFirstHeader("x-session-id") != null - && "sess-abc-123".equals(post.getFirstHeader("x-session-id").getValue()); + return post.getFirstHeader("x-session-id") != null && "sess-abc-123".equals(post.getFirstHeader("x-session-id").getValue()); } return false; }))).thenReturn(response); @@ -225,7 +229,7 @@ public void shouldPostWithParams() throws IOException { params.put("site", List.of("bch")); Response actual = subject.postProxy("foo", "/my/cool/path", "{}", params, null); - Assert.assertEquals(200, actual.getStatus()); + Assertions.assertEquals(200, actual.getStatus()); } @Test @@ -241,7 +245,7 @@ public void shouldBufferSmallResponse() throws IOException { Response actual = subject.getProxy("bar", "/my/cool/path", new MultivaluedHashMap<>(), null); - Assert.assertEquals(200, actual.getStatus()); + Assertions.assertEquals(200, actual.getStatus()); // Small responses should be buffered as a byte array assertTrue(actual.getEntity() instanceof byte[]); } @@ -260,7 +264,7 @@ public void shouldStreamLargeResponse() throws IOException { Response actual = subject.getProxy("bar", "/my/cool/path", new MultivaluedHashMap<>(), null); - Assert.assertEquals(200, actual.getStatus()); + Assertions.assertEquals(200, actual.getStatus()); // Large responses should use StreamingOutput for true chunked streaming assertTrue(actual.getEntity() instanceof StreamingOutput); ByteArrayOutputStream out = new ByteArrayOutputStream(); @@ -282,7 +286,7 @@ public void shouldStreamWhenContentLengthUnknown() throws IOException { Response actual = subject.getProxy("bar", "/my/cool/path", new MultivaluedHashMap<>(), null); - Assert.assertEquals(200, actual.getStatus()); + Assertions.assertEquals(200, actual.getStatus()); // Unknown content length (-1) should use StreamingOutput to be safe assertTrue(actual.getEntity() instanceof StreamingOutput); ByteArrayOutputStream out = new ByteArrayOutputStream(); @@ -304,7 +308,7 @@ public void shouldForwardContentType() throws IOException { Response actual = subject.getProxy("bar", "/my/cool/path", new MultivaluedHashMap<>(), null); - Assert.assertEquals(200, actual.getStatus()); + Assertions.assertEquals(200, actual.getStatus()); assertEquals("application/json", actual.getMediaType().toString()); } @@ -322,7 +326,7 @@ public void shouldDefaultContentTypeWhenMissing() throws IOException { Response actual = subject.getProxy("bar", "/my/cool/path", new MultivaluedHashMap<>(), null); - Assert.assertEquals(200, actual.getStatus()); + Assertions.assertEquals(200, actual.getStatus()); assertEquals(MediaType.APPLICATION_OCTET_STREAM, actual.getMediaType().toString()); } } diff --git a/pic-sure-resources/pic-sure-resource-api/src/test/java/edu/harvard/dbmi/avillach/service/ResourceWebClientTest.java b/pic-sure-resources/pic-sure-resource-api/src/test/java/edu/harvard/dbmi/avillach/service/ResourceWebClientTest.java index b3ea54b1b..990594ac1 100644 --- a/pic-sure-resources/pic-sure-resource-api/src/test/java/edu/harvard/dbmi/avillach/service/ResourceWebClientTest.java +++ b/pic-sure-resources/pic-sure-resource-api/src/test/java/edu/harvard/dbmi/avillach/service/ResourceWebClientTest.java @@ -2,16 +2,19 @@ import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; -import com.github.tomakehurst.wiremock.junit.WireMockClassRule; +import com.github.tomakehurst.wiremock.junit5.WireMockExtension; +import com.github.tomakehurst.wiremock.core.WireMockConfiguration; import edu.harvard.dbmi.avillach.domain.*; import edu.harvard.dbmi.avillach.util.exception.ApplicationException; import edu.harvard.dbmi.avillach.util.exception.ProtocolException; import org.glassfish.jersey.internal.RuntimeDelegateImpl; -import org.junit.BeforeClass; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.junit.MockitoJUnitRunner; +import org.junit.jupiter.api.extension.RegisterExtension; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; import javax.ws.rs.core.Response; import javax.ws.rs.ext.RuntimeDelegate; @@ -20,9 +23,14 @@ import java.util.UUID; import static com.github.tomakehurst.wiremock.client.WireMock.*; -import static org.junit.Assert.*; - -@RunWith(MockitoJUnitRunner.class) +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; + +@MockitoSettings(strictness = Strictness.WARN) +@ExtendWith(MockitoExtension.class) public class ResourceWebClientTest { private final static ObjectMapper json = new ObjectMapper(); @@ -31,10 +39,10 @@ public class ResourceWebClientTest { private final static String testURL = "http://localhost:" + port; private final ResourceWebClient cut = new ResourceWebClient(); - @Rule - public WireMockClassRule wireMockRule = new WireMockClassRule(port); + @RegisterExtension + public WireMockExtension wireMockRule = WireMockExtension.newInstance().options(WireMockConfiguration.options().port(port)).build(); - @BeforeClass + @BeforeAll public static void beforeClass() { // Need to be able to throw exceptions without container so we can verify correct errors are being thrown @@ -83,7 +91,7 @@ public void testInfo() throws JsonProcessingException { // Assuming everything goes right // queryRequest.setTargetURL(targetURL); ResourceInfo result = cut.info(testURL, queryRequest); - assertNotNull("Result should not be null", result); + assertNotNull(result, "Result should not be null"); // What if the resource has a problem? wireMockRule.stubFor(any(urlEqualTo("/info")).willReturn(aResponse().withStatus(500))); @@ -180,7 +188,7 @@ public void testSearch() throws JsonProcessingException { // request.setTargetURL(targetURL); SearchResults result = cut.search(testURL, request); - assertNotNull("Result should not be null", result); + assertNotNull(result, "Result should not be null"); // What if the resource has a problem? wireMockRule.stubFor(any(urlEqualTo("/search")).willReturn(aResponse().withStatus(500))); @@ -254,7 +262,7 @@ public void testQuery() throws JsonProcessingException { // Everything goes correctly QueryStatus result = cut.query(testURL, request); - assertNotNull("Result should not be null", result); + assertNotNull(result, "Result should not be null"); // What if the resource has a problem? wireMockRule.stubFor(any(urlEqualTo("/query")).willReturn(aResponse().withStatus(500))); @@ -288,7 +296,6 @@ public void testQueryResult() throws JsonProcessingException { byte[] mockResult = new byte[] {}; - wireMockRule.stubFor(any(urlMatching("/query/.*/result")).willReturn(aResponse().withStatus(200).withBody(mockResult))); // Should fail if missing any parameters @@ -332,10 +339,10 @@ public void testQueryResult() throws JsonProcessingException { // Everything should work here Response result = cut.queryResult(testURL, testId, queryRequest); - assertNotNull("Result should not be null", result); + assertNotNull(result, "Result should not be null"); // String resultContent = IOUtils.toString((InputStream) result.getEntity(), "UTF-8"); byte[] resultContent = (byte[]) result.getEntity(); - assertArrayEquals("Result should match " + mockResult, mockResult, resultContent); + assertArrayEquals(mockResult, resultContent, "Result should match " + mockResult); // What if the resource has a problem? wireMockRule.stubFor(any(urlMatching("/query/.*/result")).willReturn(aResponse().withStatus(500))); @@ -396,17 +403,16 @@ public void testQueryStatus() throws JsonProcessingException { // } - // queryRequest.setTargetURL(targetURL); // Everything should work here QueryStatus result = cut.queryStatus(testURL, testId, queryRequest); - assertNotNull("Result should not be null", result); + assertNotNull(result, "Result should not be null"); // Make sure all necessary fields are present - assertNotNull("Duration should not be null", result.getDuration()); - assertNotNull("Expiration should not be null", result.getExpiration()); - assertNotNull("ResourceStatus should not be null", result.getResourceStatus()); - assertNotNull("Status should not be null", result.getStatus()); + assertNotNull(result.getDuration(), "Duration should not be null"); + assertNotNull(result.getExpiration(), "Expiration should not be null"); + assertNotNull(result.getResourceStatus(), "ResourceStatus should not be null"); + assertNotNull(result.getStatus(), "Status should not be null"); // What if the resource has a problem? wireMockRule.stubFor(any(urlMatching("/query/.*/status")).willReturn(aResponse().withStatus(500))); diff --git a/pom.xml b/pom.xml index 97fac3bbc..b3fe59de5 100644 --- a/pom.xml +++ b/pom.xml @@ -25,9 +25,9 @@ 2.18.6 - 5.6.2 - 3.5.10 - 3.5.10 + 5.9.3 + 4.11.0 + 4.11.0 5.3.31 6.4.0.Final 4.5.13 @@ -71,7 +71,7 @@ org.apache.maven.plugins maven-surefire-plugin - 2.22.0 + 3.1.2 --illegal-access=permit @@ -81,14 +81,6 @@ - - - junit - junit - 4.13.2 - test - - @@ -202,7 +194,7 @@ com.github.tomakehurst wiremock-standalone - 2.14.0 + 2.27.2 test @@ -252,7 +244,7 @@ com.github.tomakehurst wiremock-jre8 - 2.27.2 + 2.35.2 test @@ -277,18 +269,6 @@ slf4j-jdk14 1.7.32 - - junit - junit - 4.13.1 - test - - - org.junit.vintage - junit-vintage-engine - 5.9.3 - test - org.reactivestreams reactive-streams