diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 591947af..032ed957 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -22,7 +22,7 @@ jobs: - name: Set up JDK 11 uses: actions/setup-java@v2 with: - java-version: '11' + java-version: '21' distribution: 'adopt' - name: Build with Maven run: mvn --batch-mode --update-snapshots verify diff --git a/README.md b/README.md index 5b203e8c..57fba10e 100644 --- a/README.md +++ b/README.md @@ -189,7 +189,7 @@ The preferred flow is somewhat asynchronous and it is crucial to understand it, >_Pay attention, that usually executing time consuming actions within the CI event call effectively means holding the main CI system execution thread, since most of the CI system's events are executing on the main thread. Don't do that._ - + ## Disclamer update Certain versions of software accessible here may contain branding from Hewlett-Packard Company (now HP Inc.) and Hewlett Packard Enterprise Company. This software was acquired by Micro Focus on September 1, 2017, and is now offered by OpenText. diff --git a/appveyor.yml b/appveyor.yml index c42194ff..bcda2298 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -1,26 +1,43 @@ install: -- ps: choco install temurin11 -y -- ps: | - Add-Type -AssemblyName System.IO.Compression.FileSystem - if (!(Test-Path -Path "C:\maven" )) { - (new-object System.Net.WebClient).DownloadFile( - 'https://dlcdn.apache.org/maven/maven-3/3.9.11/binaries/apache-maven-3.9.11-bin.zip', - 'C:\maven-bin.zip' - ) - [System.IO.Compression.ZipFile]::ExtractToDirectory("C:\maven-bin.zip", "C:\maven") - } -- cmd: | - FOR /D %%F IN ("C:\Program Files\Eclipse Adoptium\jdk-11*") DO SET JAVA_HOME=%%F - SET PATH=C:\maven\apache-maven-3.9.11\bin;%JAVA_HOME%\bin;%PATH% - java -version + - ps: | + # Install JDK 21 only if it is not already installed + $jdk = Get-ChildItem "C:\Program Files\Eclipse Adoptium" -Directory -Filter "jdk-21*" -ErrorAction SilentlyContinue + + if (-not $jdk) { + choco install temurin21 -y + } + + - ps: | + Add-Type -AssemblyName System.IO.Compression.FileSystem + + # Install Maven only if it is not already present + if (!(Test-Path "C:\maven\apache-maven-3.9.16\bin\mvn.cmd")) { + Remove-Item "C:\maven" -Recurse -Force -ErrorAction SilentlyContinue + Remove-Item "C:\maven-bin.zip" -Force -ErrorAction SilentlyContinue + + (New-Object System.Net.WebClient).DownloadFile( + "https://dlcdn.apache.org/maven/maven-3/3.9.16/binaries/apache-maven-3.9.16-bin.zip", + "C:\maven-bin.zip" + ) + + [System.IO.Compression.ZipFile]::ExtractToDirectory( + "C:\maven-bin.zip", + "C:\maven" + ) + } + + - cmd: | + FOR /D %%F IN ("C:\Program Files\Eclipse Adoptium\jdk-21*") DO SET JAVA_HOME=%%F + SET PATH=C:\maven\apache-maven-3.9.16\bin;%JAVA_HOME%\bin;%PATH% + java -version + mvn -version build_script: -- mvn compile spotbugs:check -T8 + - mvn compile spotbugs:check -T8 test_script: -- mvn test -T8 -P jacoco-coverage - + - mvn test -T8 -P jacoco-coverage cache: -- C:\maven\ -- C:\Users\appveyor\.m2 + - C:\maven\ + - C:\Users\appveyor\.m2 \ No newline at end of file diff --git a/integrations-dto/pom.xml b/integrations-dto/pom.xml index 4eab70ed..32cd1551 100644 --- a/integrations-dto/pom.xml +++ b/integrations-dto/pom.xml @@ -46,7 +46,12 @@ integrations-dto - 2.14.2 + 21 + 21 + 21 + 21 + 2.22.0 + 6.1.0 @@ -61,13 +66,12 @@ jackson-dataformat-xml ${jackson.version} - - - - junit - junit - test - + + org.junit.jupiter + junit-jupiter + ${junit-jupiter.version} + test + @@ -79,7 +83,14 @@ org.apache.maven.plugins ${basedir}/src/main/java/com/hp/octane/integrations/dto - 8 + ${java.level} + + + + spotbugs-maven-plugin + com.github.spotbugs + + spotbugs-exclude.xml @@ -94,12 +105,13 @@ maven-source-plugin org.apache.maven.plugins + ${maven-source-plugin.version} maven-javadoc-plugin org.apache.maven.plugins - 8 + ${java.level} diff --git a/integrations-dto/spotbugs-exclude.xml b/integrations-dto/spotbugs-exclude.xml new file mode 100644 index 00000000..4a30774b --- /dev/null +++ b/integrations-dto/spotbugs-exclude.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/integrations-dto/src/main/java/com/hp/octane/integrations/dto/general/impl/MbtDataImpl.java b/integrations-dto/src/main/java/com/hp/octane/integrations/dto/general/impl/MbtDataImpl.java index 292f1a0f..a9011d94 100644 --- a/integrations-dto/src/main/java/com/hp/octane/integrations/dto/general/impl/MbtDataImpl.java +++ b/integrations-dto/src/main/java/com/hp/octane/integrations/dto/general/impl/MbtDataImpl.java @@ -75,7 +75,7 @@ public TestingToolType getTestingToolType() { if (getUnits() == null || getUnits().isEmpty()) { return TestingToolType.UNKNOWN; } - return getUnits().get(0).getTestingToolType(); + return getUnits().getFirst().getTestingToolType(); } } diff --git a/integrations-dto/src/test/java/com/hp/octane/integrations/dto/DTOFactoryTest.java b/integrations-dto/src/test/java/com/hp/octane/integrations/dto/DTOFactoryTest.java index 7af075a5..e7ac9c1b 100644 --- a/integrations-dto/src/test/java/com/hp/octane/integrations/dto/DTOFactoryTest.java +++ b/integrations-dto/src/test/java/com/hp/octane/integrations/dto/DTOFactoryTest.java @@ -32,16 +32,16 @@ package com.hp.octane.integrations.dto; import com.hp.octane.integrations.dto.general.CIServerTypes; +import org.junit.jupiter.api.Test; import com.hp.octane.integrations.dto.general.CIPluginInfo; import com.hp.octane.integrations.dto.general.CIServerInfo; -import org.junit.Test; import java.util.ArrayList; import java.util.List; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; /** * Basic tests to verify if every DTO is registered and available for serialization diff --git a/integrations-dto/src/test/java/com/hp/octane/integrations/dto/connectivity/OctaneRequestTest.java b/integrations-dto/src/test/java/com/hp/octane/integrations/dto/connectivity/OctaneRequestTest.java index fba82c2e..d1a2f2a6 100644 --- a/integrations-dto/src/test/java/com/hp/octane/integrations/dto/connectivity/OctaneRequestTest.java +++ b/integrations-dto/src/test/java/com/hp/octane/integrations/dto/connectivity/OctaneRequestTest.java @@ -32,14 +32,15 @@ package com.hp.octane.integrations.dto.connectivity; import com.hp.octane.integrations.dto.DTOFactory; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.nio.charset.Charset; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; /** * OctaneTaskAbridged test @@ -48,20 +49,23 @@ public class OctaneRequestTest { private static final DTOFactory dtoFactory = DTOFactory.getInstance(); - @Test(expected = IllegalArgumentException.class) + @Test public void testA() { - dtoFactory.newDTO(OctaneRequest.class).setUrl(null); - } + assertThrows(IllegalArgumentException.class, () -> + dtoFactory.newDTO(OctaneRequest.class).setUrl(null)); + } - @Test(expected = IllegalArgumentException.class) + @Test public void testB() { - dtoFactory.newDTO(OctaneRequest.class).setUrl(""); - } + assertThrows(IllegalArgumentException.class, () -> + dtoFactory.newDTO(OctaneRequest.class).setUrl("")); + } - @Test(expected = IllegalArgumentException.class) + @Test public void testC() { - dtoFactory.newDTO(OctaneRequest.class).setUrl("some non valid url"); - } + assertThrows(IllegalArgumentException.class, () -> + dtoFactory.newDTO(OctaneRequest.class).setUrl("some non valid url")); + } @Test public void testD() { @@ -70,10 +74,11 @@ public void testD() { assertEquals(validURL, request.getUrl()); } - @Test(expected = IllegalArgumentException.class) + @Test public void testE() { - dtoFactory.newDTO(OctaneRequest.class).setMethod(null); - } + assertThrows(IllegalArgumentException.class, () -> + dtoFactory.newDTO(OctaneRequest.class).setMethod(null)); + } @Test public void testF1() throws IOException { diff --git a/integrations-dto/src/test/java/com/hp/octane/integrations/dto/connectivity/OctaneTaskAbridgedTest.java b/integrations-dto/src/test/java/com/hp/octane/integrations/dto/connectivity/OctaneTaskAbridgedTest.java index f0986d37..924d3d27 100644 --- a/integrations-dto/src/test/java/com/hp/octane/integrations/dto/connectivity/OctaneTaskAbridgedTest.java +++ b/integrations-dto/src/test/java/com/hp/octane/integrations/dto/connectivity/OctaneTaskAbridgedTest.java @@ -32,15 +32,15 @@ package com.hp.octane.integrations.dto.connectivity; import com.hp.octane.integrations.dto.DTOFactory; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.HashMap; import java.util.Map; import java.util.UUID; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; /** * OctaneTaskAbridged test diff --git a/integrations-dto/src/test/java/com/hp/octane/integrations/dto/executor/ExecutorDTOTests.java b/integrations-dto/src/test/java/com/hp/octane/integrations/dto/executor/ExecutorDTOTests.java index 51e9e1a1..be0e107f 100644 --- a/integrations-dto/src/test/java/com/hp/octane/integrations/dto/executor/ExecutorDTOTests.java +++ b/integrations-dto/src/test/java/com/hp/octane/integrations/dto/executor/ExecutorDTOTests.java @@ -35,8 +35,8 @@ import com.hp.octane.integrations.dto.executor.impl.TestingToolType; import com.hp.octane.integrations.dto.scm.SCMRepository; import com.hp.octane.integrations.dto.scm.SCMType; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.ArrayList; @@ -64,7 +64,7 @@ public void testDiscoveryInfo() { .setScmRepository(scm); String json = dtoFactory.dtoToJson(discInfo); - Assert.assertNotNull(json); + Assertions.assertNotNull(json); } } diff --git a/integrations-dto/src/test/java/com/hp/octane/integrations/dto/general/EntityDTOTests.java b/integrations-dto/src/test/java/com/hp/octane/integrations/dto/general/EntityDTOTests.java index 36de1ebc..0a89da86 100644 --- a/integrations-dto/src/test/java/com/hp/octane/integrations/dto/general/EntityDTOTests.java +++ b/integrations-dto/src/test/java/com/hp/octane/integrations/dto/general/EntityDTOTests.java @@ -35,8 +35,8 @@ import com.hp.octane.integrations.dto.entities.*; import com.hp.octane.integrations.dto.pipelines.PipelineContext; import com.hp.octane.integrations.dto.pipelines.PipelineContextList; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; /** * Created by gullery on 03/01/2016. @@ -55,8 +55,8 @@ public void testEntity() { String json = dtoFactory.dtoToJson(entity); - Assert.assertNotNull(json); - Assert.assertTrue(json.length() > 8); + Assertions.assertNotNull(json); + Assertions.assertTrue(json.length() > 8); } @Test @@ -75,12 +75,12 @@ public void testEntityList() { list.addEntity(entity2); String json = dtoFactory.dtoToJson(list); - Assert.assertNotNull(json); - Assert.assertTrue(json.length() > 10); + Assertions.assertNotNull(json); + Assertions.assertTrue(json.length() > 10); EntityList serializedList = dtoFactory.dtoFromJson(json, EntityList.class); - Assert.assertEquals(2, serializedList.getData().size()); + Assertions.assertEquals(2, serializedList.getData().size()); } @Test @@ -99,12 +99,12 @@ public void testResponseEntityList() { list.setTotalCount(2); String json = dtoFactory.dtoToJson(list); - Assert.assertNotNull(json); - Assert.assertTrue(json.length() > 10); + Assertions.assertNotNull(json); + Assertions.assertTrue(json.length() > 10); EntityList serializedList = dtoFactory.dtoFromJson(json, ResponseEntityList.class); - Assert.assertEquals(2, serializedList.getData().size()); + Assertions.assertEquals(2, serializedList.getData().size()); } @@ -112,20 +112,20 @@ public void testResponseEntityList() { public void testParseResponseEntitiyList() { String json = "{\"total_count\":1,\"data\":[{\"type\":\"defect\",\"workspace_id\":1002,\"logical_name\":\"439wn0yylz2j4bgp0r72kegzp\",\"name\":\"def1\",\"id\":\"3001\"}],\"exceeds_total_count\":false}"; ResponseEntityList serializedList = dtoFactory.dtoFromJson(json, ResponseEntityList.class); - Assert.assertEquals(1, serializedList.getData().size()); + Assertions.assertEquals(1, serializedList.getData().size()); } @Test public void testParseOctaneException() { String json = "{\"error_code\":\"platform.web_application\",\"correlation_id\":\"o5jp1yvjo54lxbjmo7dxz12v6\",\"description\":\"HTTP 404 Not Found\",\"description_translated\":\"HTTP 404 Not Found\",\"properties\":null,\"stack_trace\":\"java.ws.rs.NotFoundException: HTTP 404\",\"business_error\":false}\n"; OctaneRestExceptionData octaneRestExceptionData = dtoFactory.dtoFromJson(json, OctaneRestExceptionData.class); - Assert.assertEquals("platform.web_application", octaneRestExceptionData.getErrorCode()); + Assertions.assertEquals("platform.web_application", octaneRestExceptionData.getErrorCode()); } @Test public void testParseOctaneBulkException() { String json = "{\"total_count\":0,\"data\":[],\"exceeds_total_count\":false,\"errors\":[{\"error_code\":\"platform.unknown_field\",\"correlation_id\":\"o5jp1y5576mo0tdyd60g7n2v6\",\"description\":\"The entity type 'defect' does not have a field/s by name/s 'sss'\",\"description_translated\":\"The entity type 'defect' does not have a field/s by name/s 'sss'\",\"properties\":{\"entity_type\":\"defect\",\"field_name\":\"sss\"},\"stack_trace\":\"com.hp.mqm.bl.platform.exception.NonExistingFieldException\",\"business_error\":true}]}"; OctaneBulkExceptionData octaneException = dtoFactory.dtoFromJson(json, OctaneBulkExceptionData.class); - Assert.assertEquals("platform.unknown_field", octaneException.getErrors().get(0).getErrorCode()); + Assertions.assertEquals("platform.unknown_field", octaneException.getErrors().getFirst().getErrorCode()); } @@ -133,14 +133,14 @@ public void testParseOctaneBulkException() { public void testParsePipelineContext() { String json = "{\"contextEntityId\":2014,\"contextEntityName\":\"ss\",\"workspaceId\":1004,\"releaseId\":1013,\"ciJob\":{\"ciServer\":{\"id\":2002,\"workspaceId\":1004,\"instanceId\":\"d7cb541b-c22e-4ed5-a566-65854fb7aae1\",\"url\":\"http://localhost:9192/jenkins\",\"type\":\"jenkins\",\"name\":\"local\",\"sendingTime\":null},\"jobId\":2008,\"workspaceId\":1004,\"jobCiId\":\"ss\",\"name\":\"ss\",\"parameters\":[]},\"ignoreTests\":true,\"rootJobCiId\":\"ss\",\"taxonomies\":[{\"id\":1120,\"parent\":{\"id\":1087,\"name\":\"DB\"}}],\"listFields\":{\"test_tool_type\":[],\"test_level\":[{\"id\":1457}],\"test_type\":[],\"test_framework\":[]},\"contextEntityType\":\"pipeline\",\"pipelineRoot\":true}"; PipelineContext pc = dtoFactory.dtoFromJson(json, PipelineContext.class); - Assert.assertEquals(pc.getContextEntityId(),2014); + Assertions.assertEquals(pc.getContextEntityId(),2014); } @Test public void testParsePipelineContextList() { String json = "{\"data\":[{\"contextEntityId\":2014,\"contextEntityName\":\"ss\",\"workspaceId\":1004,\"releaseId\":null,\"ciJob\":{\"ciServer\":{\"id\":2002,\"workspaceId\":1004,\"instanceId\":\"d7cb541b-c22e-4ed5-a566-65854fb7aae1\",\"url\":\"http://localhost:9192/jenkins\",\"type\":\"jenkins\",\"name\":\"local\",\"sendingTime\":null},\"jobId\":2008,\"workspaceId\":1004,\"jobCiId\":\"ss\",\"name\":\"ss\",\"parameters\":[]},\"ignoreTests\":true,\"rootJobCiId\":\"ss\",\"taxonomies\":[{\"id\":1120,\"parent\":{\"id\":1087,\"name\":\"DB\"}}],\"listFields\":{\"test_tool_type\":[],\"test_level\":[{\"id\":1457}],\"test_type\":[],\"test_framework\":[]},\"contextEntityType\":\"pipeline\",\"pipelineRoot\":true},{\"contextEntityId\":1004,\"contextEntityName\":\"ss\",\"workspaceId\":1003,\"releaseId\":1005,\"ciJob\":{\"ciServer\":{\"id\":1002,\"workspaceId\":1003,\"instanceId\":\"d7cb541b-c22e-4ed5-a566-65854fb7aae1\",\"url\":\"http://localhost:9192/jenkins\",\"type\":\"jenkins\",\"name\":\"LOCAL JENKINS\",\"sendingTime\":null},\"jobId\":1003,\"workspaceId\":1003,\"jobCiId\":\"ss\",\"name\":\"ss\",\"parameters\":[]},\"ignoreTests\":false,\"rootJobCiId\":\"ss\",\"taxonomies\":[{\"id\":1075,\"parent\":{\"id\":1044,\"name\":\"Distribution\"}},{\"id\":1078,\"parent\":{\"id\":1046,\"name\":\"DB\"}}],\"listFields\":{\"test_tool_type\":[{\"id\":1280}],\"test_level\":[{\"id\":1266}],\"test_type\":[{\"id\":1271}],\"test_framework\":[{\"id\":1255}]},\"contextEntityType\":\"pipeline\",\"pipelineRoot\":true}]}"; PipelineContextList serializedList = dtoFactory.dtoFromJson(json, PipelineContextList.class); - Assert.assertEquals(2, serializedList.getData().size()); + Assertions.assertEquals(2, serializedList.getData().size()); } } diff --git a/integrations-dto/src/test/java/com/hp/octane/integrations/dto/tests/TestsDTOsTest.java b/integrations-dto/src/test/java/com/hp/octane/integrations/dto/tests/TestsDTOsTest.java index d60c5ad1..d8f71333 100644 --- a/integrations-dto/src/test/java/com/hp/octane/integrations/dto/tests/TestsDTOsTest.java +++ b/integrations-dto/src/test/java/com/hp/octane/integrations/dto/tests/TestsDTOsTest.java @@ -32,11 +32,14 @@ package com.hp.octane.integrations.dto.tests; import com.hp.octane.integrations.dto.DTOFactory; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.Arrays; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.assertNotNull; /** * Testing Tests DTOs @@ -65,8 +68,8 @@ public void test_A() { String xml = dtoFactory.dtoToXml(tr); assertNotNull(xml); - assertTrue("external_run_id should not be in xml", !xml.contains("external_run_id")); - assertTrue("external_test_id should not be in xml", !xml.contains("external_test_id")); + assertTrue(!xml.contains("external_run_id"), "external_run_id should not be in xml"); + assertTrue(!xml.contains("external_test_id"), "external_test_id should not be in xml"); TestRun backO = dtoFactory.dtoFromXml(xml, TestRun.class); assertNotNull(backO); assertEquals(moduleName, backO.getModuleName()); @@ -160,26 +163,26 @@ public void parsingMqmTestResults() { assertEquals(result.getBuildContext().getBuildId(), "284"); assertEquals(result.getTestFields().size(), 2); - assertEquals(result.getTestFields().get(0).getValue(), "End to End"); - assertEquals(result.getTestFields().get(0).getType(), "Test_Type"); + assertEquals(result.getTestFields().getFirst().getValue(), "End to End"); + assertEquals(result.getTestFields().getFirst().getType(), "Test_Type"); assertEquals(result.getTestFields().get(1).getValue(), "Selenium"); assertEquals(result.getTestFields().get(1).getType(), "Testing_Tool_Type"); - assertEquals(result.getTestRuns().get(0).getModuleName(), "/helloWorld"); - assertEquals(result.getTestRuns().get(0).getPackageName(), "hello"); - assertEquals(result.getTestRuns().get(0).getClassName(), "HelloWorldTest"); - assertEquals(result.getTestRuns().get(0).getTestName(), "testTwo"); - assertEquals(result.getTestRuns().get(0).getResult(), TestRunResult.FAILED); - assertEquals(result.getTestRuns().get(0).getDuration(), 2); - assertEquals(result.getTestRuns().get(0).getStarted(), 1430919316223l); + assertEquals(result.getTestRuns().getFirst().getModuleName(), "/helloWorld"); + assertEquals(result.getTestRuns().getFirst().getPackageName(), "hello"); + assertEquals(result.getTestRuns().getFirst().getClassName(), "HelloWorldTest"); + assertEquals(result.getTestRuns().getFirst().getTestName(), "testTwo"); + assertEquals(result.getTestRuns().getFirst().getResult(), TestRunResult.FAILED); + assertEquals(result.getTestRuns().getFirst().getDuration(), 2); + assertEquals(result.getTestRuns().getFirst().getStarted(), 1430919316223l); - assertEquals(result.getTestRuns().get(0).getError().getErrorType(), "java.lang.AssertionError"); - assertEquals(result.getTestRuns().get(0).getError().getErrorType(), "java.lang.AssertionError"); - assertEquals(result.getTestRuns().get(0).getError().getErrorMessage(), "expected:'111' but was:'222'"); - assertEquals(result.getTestRuns().get(0).getError().getStackTrace(), "java.lang.AssertionError :aaa"); + assertEquals(result.getTestRuns().getFirst().getError().getErrorType(), "java.lang.AssertionError"); + assertEquals(result.getTestRuns().getFirst().getError().getErrorType(), "java.lang.AssertionError"); + assertEquals(result.getTestRuns().getFirst().getError().getErrorMessage(), "expected:'111' but was:'222'"); + assertEquals(result.getTestRuns().getFirst().getError().getStackTrace(), "java.lang.AssertionError :aaa"); - assertEquals(result.getTestRuns().get(0).getDescription(), "My run description"); + assertEquals(result.getTestRuns().getFirst().getDescription(), "My run description"); String converted = dtoFactory.dtoToXml(result); assertEquals(payload, converted); @@ -191,19 +194,19 @@ public void parsingJUnitTestResults() { TestSuite result = dtoFactory.dtoFromXml(payload, TestSuite.class); assertEquals(2, result.getProperties().size()); - assertEquals("nameAAA", result.getProperties().get(0).getPropertyName()); - assertEquals("valueAAA", result.getProperties().get(0).getPropertyValue()); + assertEquals("nameAAA", result.getProperties().getFirst().getPropertyName()); + assertEquals("valueAAA", result.getProperties().getFirst().getPropertyValue()); assertEquals("nameBBB", result.getProperties().get(1).getPropertyName()); assertEquals("valueBBB", result.getProperties().get(1).getPropertyValue()); assertEquals(4, result.getTestCases().size()); - assertEquals("testAppErr", result.getTestCases().get(0).getName()); - assertEquals("MF.simple.tests.AppTest", result.getTestCases().get(0).getClassName()); - assertEquals("0.002", result.getTestCases().get(0).getTime()); - assertNotNull(result.getTestCases().get(0).getFailure()); - assertEquals("junit.framework.AssertionFailedError", result.getTestCases().get(0).getFailure().getType()); - assertEquals("junit.framework.AssertionFailedError at MF.simple.tests.AppTest.testAppC2(AppTest.java:56)", result.getTestCases().get(0).getFailure().getStackTrace()); + assertEquals("testAppErr", result.getTestCases().getFirst().getName()); + assertEquals("MF.simple.tests.AppTest", result.getTestCases().getFirst().getClassName()); + assertEquals("0.002", result.getTestCases().getFirst().getTime()); + assertNotNull(result.getTestCases().getFirst().getFailure()); + assertEquals("junit.framework.AssertionFailedError", result.getTestCases().getFirst().getFailure().getType()); + assertEquals("junit.framework.AssertionFailedError at MF.simple.tests.AppTest.testAppC2(AppTest.java:56)", result.getTestCases().getFirst().getFailure().getStackTrace()); assertEquals("testAppA", result.getTestCases().get(1).getName()); assertEquals("MF.simple.tests.AppTest", result.getTestCases().get(1).getClassName()); diff --git a/integrations-sdk/pom.xml b/integrations-sdk/pom.xml index c4b5bf58..347c7db9 100644 --- a/integrations-sdk/pom.xml +++ b/integrations-sdk/pom.xml @@ -47,12 +47,20 @@ integrations-sdk - 2.17.2 - 4.5.14 - 1.2.3 - - 10.0.14 - 4.1.1 + 21 + 21 + 21 + 21 + + 2.26.0 + 4.5.14 + 1.2.3 + 3.20.0 + 12.1.10 + 5.5.1 + 1.14.1 + 6.3.0 + 6.1.0 @@ -95,7 +103,7 @@ org.apache.commons commons-lang3 - 3.12.0 + ${commons-lang3.version} @@ -109,20 +117,27 @@ org.apache.poi poi ${poi.version} + + + org.apache.logging.log4j + log4j-api + + + commons-io + commons-io + + + commons-codec + commons-codec + + org.apache.commons commons-csv - 1.8 - - - - - junit - junit - test + ${commons-csv.version} easymock @@ -135,12 +150,18 @@ ${jetty-server.version} test + + org.junit.jupiter + junit-jupiter + ${junit-jupiter.version} + test + org.gitlab4j gitlab4j-api - 6.1.0 + ${gitlab4j-api.version} com.fasterxml.jackson.core @@ -172,6 +193,17 @@ + + + + spotbugs-maven-plugin + com.github.spotbugs + + spotbugs-exclude.xml + + + + maven-jar-plugin @@ -197,7 +229,7 @@ org.apache.maven.plugins ${basedir}/src/main/java/com/hp/octane/integrations - 8 + ${java.level} diff --git a/integrations-sdk/spotbugs-exclude.xml b/integrations-sdk/spotbugs-exclude.xml new file mode 100644 index 00000000..c4bf70f0 --- /dev/null +++ b/integrations-sdk/spotbugs-exclude.xml @@ -0,0 +1,31 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/integrations-sdk/src/main/java/com/hp/octane/integrations/exceptions/OctaneBulkException.java b/integrations-sdk/src/main/java/com/hp/octane/integrations/exceptions/OctaneBulkException.java index 4727c618..0f25596d 100644 --- a/integrations-sdk/src/main/java/com/hp/octane/integrations/exceptions/OctaneBulkException.java +++ b/integrations-sdk/src/main/java/com/hp/octane/integrations/exceptions/OctaneBulkException.java @@ -40,7 +40,7 @@ public class OctaneBulkException extends RuntimeException { public OctaneBulkException(int responseStatus, OctaneBulkExceptionData data) { super(data.getErrors().size() == 1 - ? data.getErrors().get(0).getDescription() + ? data.getErrors().getFirst().getDescription() : data.getErrors().size() + " exceptions occurred on Octane side."); this.data = data; this.responseStatus = responseStatus; diff --git a/integrations-sdk/src/main/java/com/hp/octane/integrations/executor/converters/MfMBTConverter.java b/integrations-sdk/src/main/java/com/hp/octane/integrations/executor/converters/MfMBTConverter.java index bf2fa5e8..089c10d8 100644 --- a/integrations-sdk/src/main/java/com/hp/octane/integrations/executor/converters/MfMBTConverter.java +++ b/integrations-sdk/src/main/java/com/hp/octane/integrations/executor/converters/MfMBTConverter.java @@ -114,7 +114,7 @@ public static String decodeTestNameIfRequired(String name) { } private static boolean shouldRetrieveMbtData(List tests) { - return tests.get(0).getParameters().get(MBT_DATA).equals(MBT_DATA_NOT_INCLUDED); + return tests.getFirst().getParameters().get(MBT_DATA).equals(MBT_DATA_NOT_INCLUDED); } private static Map parseSuiteRunDataJson(String responseJson) { diff --git a/integrations-sdk/src/main/java/com/hp/octane/integrations/services/bridge/ServiceState.java b/integrations-sdk/src/main/java/com/hp/octane/integrations/services/bridge/ServiceState.java index f9e3a03f..fc6873d3 100644 --- a/integrations-sdk/src/main/java/com/hp/octane/integrations/services/bridge/ServiceState.java +++ b/integrations-sdk/src/main/java/com/hp/octane/integrations/services/bridge/ServiceState.java @@ -32,5 +32,5 @@ package com.hp.octane.integrations.services.bridge; public enum ServiceState { - Initial, WaitingToOctane, AfterWaitingToOctane, Closed, PostponingOnException, StopTaskPolling, Disabled; + Initial, WaitingToOctane, AfterWaitingToOctane, Closed, PostponingOnException, StopTaskPolling, Disabled } diff --git a/integrations-sdk/src/main/java/com/hp/octane/integrations/services/events/EventsServiceImpl.java b/integrations-sdk/src/main/java/com/hp/octane/integrations/services/events/EventsServiceImpl.java index c99cc4d3..51cc6209 100644 --- a/integrations-sdk/src/main/java/com/hp/octane/integrations/services/events/EventsServiceImpl.java +++ b/integrations-sdk/src/main/java/com/hp/octane/integrations/services/events/EventsServiceImpl.java @@ -143,7 +143,7 @@ public void publishEvent(CIEvent event) { if (eventsSize > MAX_EVENTS_TO_KEEP) { logger.warn(configurer.octaneConfiguration.getLocationForLog() + "reached MAX amount of events to keep in queue (max - " + MAX_EVENTS_TO_KEEP + ", found - " + eventsSize + "), capping the head"); while (events.size() > MAX_EVENTS_TO_KEEP) { // in this case we need to read the real-time size of the list - events.remove(0); + events.removeFirst(); } } workerPreflight.itemAddedToQueue(); diff --git a/integrations-sdk/src/main/java/com/hp/octane/integrations/services/pullrequestsandbranches/PullRequestAndBranchServiceImpl.java b/integrations-sdk/src/main/java/com/hp/octane/integrations/services/pullrequestsandbranches/PullRequestAndBranchServiceImpl.java index c780504f..7aa4b2fd 100644 --- a/integrations-sdk/src/main/java/com/hp/octane/integrations/services/pullrequestsandbranches/PullRequestAndBranchServiceImpl.java +++ b/integrations-sdk/src/main/java/com/hp/octane/integrations/services/pullrequestsandbranches/PullRequestAndBranchServiceImpl.java @@ -150,7 +150,7 @@ public void sendPullRequests(List pullRequests, String workspaceId, if (!repositoryRootsList.isEmpty()) { - Entity rootRepoForSearch = repositoryRootsList.get(0); + Entity rootRepoForSearch = repositoryRootsList.getFirst(); String rootRepoURL = rootRepoForSearch.getField(EntityConstants.ScmRepositoryRoot.URL_FIELD).toString(); logConsumer.accept( String.format("Checking branches that already exist in the root repository with the configured id: %s", @@ -236,7 +236,7 @@ public BranchSyncResult syncBranchesToOctane(FetchHandler fetcherHandler, Branch List rootRepositoryForSearchList = getRepositoryRootsById(fp.getSearchBranchOctaneRootRepositoryId(), workspaceId); if(!rootRepositoryForSearchList.isEmpty()){ - Entity rootRepoForSearch = rootRepositoryForSearchList.get(0); + Entity rootRepoForSearch = rootRepositoryForSearchList.getFirst(); logConsumer.accept(String.format( "Filtering out the branches that already exist in the root repository with the configured id: %s", rootRepoForSearch.getId())); @@ -270,7 +270,7 @@ public BranchSyncResult syncBranchesToOctane(FetchHandler fetcherHandler, Branch String rootId = ""; if (!roots.isEmpty()) { - rootId = roots.get(0).getId(); + rootId = roots.getFirst().getId(); octaneBranches = getRepositoryBranches(rootId, workspaceId, false); logConsumer.accept("Found repository root with id " + rootId); } @@ -432,7 +432,7 @@ private Entity createRepositoryRoot(String repoUrlForOctane, String repoShortNam entity.setField(EntityConstants.ScmRepositoryRoot.SCM_TYPE_FIELD, SCMType.GIT.getOctaneId()); List results = entitiesService.postEntities(workspaceId, EntityConstants.ScmRepositoryRoot.COLLECTION_NAME, Arrays.asList(entity)); - return results.get(0); + return results.getFirst(); } @Override @@ -450,7 +450,7 @@ public boolean updateRepoTemplates(String repoUrl, Long workspaceId, RepoTemplat return false; } - Entity repo = roots.get(0); + Entity repo = roots.getFirst(); Entity entity = DTOFactory.getInstance().newDTO(Entity.class); entity.setField(EntityConstants.ScmRepositoryRoot.ID_FIELD, repo.getId()); diff --git a/integrations-sdk/src/main/java/com/hp/octane/integrations/services/pullrequestsandbranches/bitbucketserver/BitbucketServerFetchHandler.java b/integrations-sdk/src/main/java/com/hp/octane/integrations/services/pullrequestsandbranches/bitbucketserver/BitbucketServerFetchHandler.java index d5b7749d..8c10b8bb 100644 --- a/integrations-sdk/src/main/java/com/hp/octane/integrations/services/pullrequestsandbranches/bitbucketserver/BitbucketServerFetchHandler.java +++ b/integrations-sdk/src/main/java/com/hp/octane/integrations/services/pullrequestsandbranches/bitbucketserver/BitbucketServerFetchHandler.java @@ -102,7 +102,7 @@ public List fetchPullRequests(Pu .setUser(getUserName(commit.getCommitter().getEmailAddress(), commit.getCommitter().getName())) .setUserEmail(commit.getCommitter().getEmailAddress()) .setTime(commit.getCommitterTimestamp()) - .setParentRevId(commit.getParents().get(0).getId()); + .setParentRevId(commit.getParents().getFirst().getId()); dtoCommits.add(dtoCommit); } @@ -122,7 +122,7 @@ public List fetchPullRequests(Pu .setAuthorName(userId) .setAuthorEmail(pr.getAuthor().getUser().getEmailAddress()) .setClosedTime(pr.getClosedDate()) - .setSelfUrl(pr.getLinks().getSelf().get(0).getHref()) + .setSelfUrl(pr.getLinks().getSelf().getFirst().getHref()) .setSourceRepository(sourceRepository) .setTargetRepository(targetRepository) .setCommits(dtoCommits) @@ -185,7 +185,7 @@ private SCMRepository buildScmRepository(boolean useSSHFormat, Ref ref) { Stream links = ref.getRepository().getLinks().getClone().stream(); Optional optLink = useSSHFormat ? links.filter(l -> l.getName().equalsIgnoreCase("ssh")).findFirst() : links.filter(l -> !l.getName().equalsIgnoreCase("ssh")).findFirst(); - String url = optLink.isPresent() ? optLink.get().getHref() : ref.getRepository().getLinks().getClone().get(0).getHref(); + String url = optLink.isPresent() ? optLink.get().getHref() : ref.getRepository().getLinks().getClone().getFirst().getHref(); return dtoFactory.newDTO(SCMRepository.class) .setUrl(url) .setBranch(ref.getDisplayId()) @@ -227,7 +227,7 @@ private List getPagedEntities(String //remove exceeded items while (result.size() > maxTotal) { - result.remove(result.size() - 1); + result.removeLast(); } return result; } catch (RuntimeException e) { @@ -265,7 +265,7 @@ public String getRepoApiPath(String repoHttpCloneUrl) { } //add repo name without .git - String repoPart = parts.get(parts.size() - 1); + String repoPart = parts.getLast(); if (repoPart.toLowerCase().endsWith(".git")) { repoPart = repoPart.substring(0, repoPart.length() - 4);//remove ".git" } @@ -301,7 +301,7 @@ private String getSelfUrl(String repoHttpCloneUrl) { } //add repo name without .git - String repoPart = parts.get(parts.size() - 1); + String repoPart = parts.getLast(); if (repoPart.toLowerCase().endsWith(".git")) { repoPart = repoPart.substring(0, repoPart.length() - 4);//remove ".git" } diff --git a/integrations-sdk/src/main/java/com/hp/octane/integrations/services/pullrequestsandbranches/factory/FetchFactory.java b/integrations-sdk/src/main/java/com/hp/octane/integrations/services/pullrequestsandbranches/factory/FetchFactory.java index 3d8754eb..b17bf85c 100644 --- a/integrations-sdk/src/main/java/com/hp/octane/integrations/services/pullrequestsandbranches/factory/FetchFactory.java +++ b/integrations-sdk/src/main/java/com/hp/octane/integrations/services/pullrequestsandbranches/factory/FetchFactory.java @@ -41,30 +41,20 @@ public class FetchFactory { public static FetchHandler getHandler(ScmTool scmTool, AuthenticationStrategy authenticationStrategy){ - switch (scmTool){ - case BitbucketServer: - return new BitbucketServerFetchHandler(authenticationStrategy); - case GithubCloud: - return new GithubCloudFetchHandler(authenticationStrategy); - case GithubServer: - return new GithubServerFetchHandler(authenticationStrategy); - case GitLabServer: - return null; - } - return null; + return switch (scmTool){ + case BitbucketServer -> new BitbucketServerFetchHandler(authenticationStrategy); + case GithubCloud -> new GithubCloudFetchHandler(authenticationStrategy); + case GithubServer -> new GithubServerFetchHandler(authenticationStrategy); + case GitLabServer -> null; + }; } public static FetchHandler getHandler(ScmTool scmTool, AuthenticationStrategy authenticationStrategy, String secret){ - switch (scmTool){ - case BitbucketServer: - return new BitbucketServerFetchHandler(authenticationStrategy); - case GithubCloud: - return new GithubCloudFetchHandler(authenticationStrategy); - case GithubServer: - return new GithubServerFetchHandler(authenticationStrategy); - case GitLabServer: - return new GitlabServerFetchHandler(authenticationStrategy, secret); - } - return null; + return switch (scmTool){ + case BitbucketServer -> new BitbucketServerFetchHandler(authenticationStrategy); + case GithubCloud -> new GithubCloudFetchHandler(authenticationStrategy); + case GithubServer -> new GithubServerFetchHandler(authenticationStrategy); + case GitLabServer -> new GitlabServerFetchHandler(authenticationStrategy, secret); + }; } } diff --git a/integrations-sdk/src/main/java/com/hp/octane/integrations/services/pullrequestsandbranches/github/GithubCloudFetchHandler.java b/integrations-sdk/src/main/java/com/hp/octane/integrations/services/pullrequestsandbranches/github/GithubCloudFetchHandler.java index ac842e43..918242fb 100644 --- a/integrations-sdk/src/main/java/com/hp/octane/integrations/services/pullrequestsandbranches/github/GithubCloudFetchHandler.java +++ b/integrations-sdk/src/main/java/com/hp/octane/integrations/services/pullrequestsandbranches/github/GithubCloudFetchHandler.java @@ -59,7 +59,7 @@ public String getRepoApiPath(String repoHttpCloneUrl) { } String user = parts.get(parts.size() - 2); - String repoName = parts.get(parts.size() - 1); + String repoName = parts.getLast(); repoName = repoName.substring(0, repoName.length() - ".git".length()); return String.format("https://api.github.com/repos/%s/%s", user, repoName); } diff --git a/integrations-sdk/src/main/java/com/hp/octane/integrations/services/pullrequestsandbranches/github/GithubV3FetchHandler.java b/integrations-sdk/src/main/java/com/hp/octane/integrations/services/pullrequestsandbranches/github/GithubV3FetchHandler.java index 4ba1d812..f46c81d6 100644 --- a/integrations-sdk/src/main/java/com/hp/octane/integrations/services/pullrequestsandbranches/github/GithubV3FetchHandler.java +++ b/integrations-sdk/src/main/java/com/hp/octane/integrations/services/pullrequestsandbranches/github/GithubV3FetchHandler.java @@ -218,7 +218,7 @@ public List fetchPullRequests(Pu .setUser(getUserName(commit.getCommit().getCommitter().getEmail(), commit.getCommit().getCommitter().getName())) .setUserEmail(commit.getCommit().getCommitter().getEmail()) .setTime(FetchUtils.convertISO8601DateStringToLong(commit.getCommit().getCommitter().getDate())) - .setParentRevId(commit.getParents().get(0).getSha()); + .setParentRevId(commit.getParents().getFirst().getSha()); dtoCommits.add(dtoCommit); } @@ -365,7 +365,7 @@ private List getPagedEntities(String //remove exceeding items while (result.size() > maxTotal) { - result.remove(result.size() - 1); + result.removeLast(); finished = true; } } while (!finished); diff --git a/integrations-sdk/src/main/java/com/hp/octane/integrations/services/pullrequestsandbranches/gitlab/GitlabServerFetchHandler.java b/integrations-sdk/src/main/java/com/hp/octane/integrations/services/pullrequestsandbranches/gitlab/GitlabServerFetchHandler.java index c094656e..8ba642e4 100644 --- a/integrations-sdk/src/main/java/com/hp/octane/integrations/services/pullrequestsandbranches/gitlab/GitlabServerFetchHandler.java +++ b/integrations-sdk/src/main/java/com/hp/octane/integrations/services/pullrequestsandbranches/gitlab/GitlabServerFetchHandler.java @@ -122,7 +122,7 @@ public List fetchPullRequests(PullRequestFetchParameters parameters //remove exceeding items while (mergeRequests.size() > parameters.getMaxPRsToFetch()) { - mergeRequests.remove(0); + mergeRequests.removeFirst(); } List sourcePatterns = FetchUtils.buildPatterns(parameters.getSourceBranchFilter()); @@ -161,7 +161,7 @@ public List fetchPullRequests(PullRequestFetchParameters parameters .setTime(commit.getTimestamp() != null ? commit.getTimestamp().getTime() : new Date().getTime()) .setParentRevId(Objects.isNull(commit.getParentIds()) ? null - : (commit.getParentIds().isEmpty() ? null : commit.getParentIds().get(0))); + : (commit.getParentIds().isEmpty() ? null : commit.getParentIds().getFirst())); dtoCommits.add(dtoCommit); }); @@ -294,7 +294,7 @@ public String getRepoApiPath(String repoHttpCloneUrl) { int i = rest.indexOf('/'); String encoded = rest.substring(i + 1).replace("/", "%2F"); StringBuffer sb = new StringBuffer(); - sb.append(list.get(0)).append("//").append(rest, 0, i).append("/api/v4/projects/").append(encoded); + sb.append(list.getFirst()).append("//").append(rest, 0, i).append("/api/v4/projects/").append(encoded); return sb.toString(); } else { throw new Exception(); diff --git a/integrations-sdk/src/main/java/com/hp/octane/integrations/services/rest/OctaneRestClientImpl.java b/integrations-sdk/src/main/java/com/hp/octane/integrations/services/rest/OctaneRestClientImpl.java index 52b64258..3e6b6c13 100644 --- a/integrations-sdk/src/main/java/com/hp/octane/integrations/services/rest/OctaneRestClientImpl.java +++ b/integrations-sdk/src/main/java/com/hp/octane/integrations/services/rest/OctaneRestClientImpl.java @@ -431,8 +431,7 @@ private TrustManager[] getTrustManagers() throws NoSuchAlgorithmException, KeySt TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init((KeyStore) null); TrustManager[] tmArr = tmf.getTrustManagers(); - if (tmArr.length == 1 && tmArr[0] instanceof X509TrustManager) { - X509TrustManager defaultTm = (X509TrustManager) tmArr[0]; + if (tmArr.length == 1 && tmArr[0] instanceof X509TrustManager defaultTm) { TrustManager myTM = new X509TrustManager() { public X509Certificate[] getAcceptedIssuers() { return defaultTm.getAcceptedIssuers(); diff --git a/integrations-sdk/src/main/java/com/hp/octane/integrations/services/testexecution/TestExecutionServiceImpl.java b/integrations-sdk/src/main/java/com/hp/octane/integrations/services/testexecution/TestExecutionServiceImpl.java index bf3861c2..dbb3e12b 100644 --- a/integrations-sdk/src/main/java/com/hp/octane/integrations/services/testexecution/TestExecutionServiceImpl.java +++ b/integrations-sdk/src/main/java/com/hp/octane/integrations/services/testexecution/TestExecutionServiceImpl.java @@ -185,7 +185,7 @@ private Entity getReleaseOrThrow(Long workspaceId, Long optionalReleaseId) { Entity release; if (optionalReleaseId == null) { Optional defaultRelease = this.getDefaultRelease(workspaceId); - if (!defaultRelease.isPresent()) { + if (defaultRelease.isEmpty()) { throw new RuntimeException("Failed to find default release "); } release = defaultRelease.get(); diff --git a/integrations-sdk/src/main/java/com/hp/octane/integrations/services/tests/TestsServiceImpl.java b/integrations-sdk/src/main/java/com/hp/octane/integrations/services/tests/TestsServiceImpl.java index 69025590..e45109bf 100644 --- a/integrations-sdk/src/main/java/com/hp/octane/integrations/services/tests/TestsServiceImpl.java +++ b/integrations-sdk/src/main/java/com/hp/octane/integrations/services/tests/TestsServiceImpl.java @@ -311,7 +311,7 @@ private void doPreflightAndPushTestResult(TestsResultQueueItem queueItem) { logger.warn(configurer.octaneConfiguration.getLocationForLog() + "test result of " + queueItem + " resolved to be NULL, skipping"); return; } - try { + try (testsResultA) { // preflight InputStream testsResultB; boolean isRelevant = isTestsResultRelevant(queueItem.jobId, queueItem.rootJobId); @@ -357,12 +357,8 @@ private void doPreflightAndPushTestResult(TestsResultQueueItem queueItem) { logger.warn(configurer.octaneConfiguration.getLocationForLog() + "failed to close test result file after push test for " + queueItem); } } - } finally { - try { - testsResultA.close(); - } catch (IOException e) { - logger.warn(configurer.octaneConfiguration.getLocationForLog() + "failed to close test result file after push test for " + queueItem); - } + } catch (IOException e) { + logger.warn(configurer.octaneConfiguration.getLocationForLog() + "failed to close test result file for " + queueItem); } } diff --git a/integrations-sdk/src/main/java/com/hp/octane/integrations/services/vulnerabilities/ToolType.java b/integrations-sdk/src/main/java/com/hp/octane/integrations/services/vulnerabilities/ToolType.java index 233d2a9f..f2cd31e7 100644 --- a/integrations-sdk/src/main/java/com/hp/octane/integrations/services/vulnerabilities/ToolType.java +++ b/integrations-sdk/src/main/java/com/hp/octane/integrations/services/vulnerabilities/ToolType.java @@ -32,5 +32,5 @@ package com.hp.octane.integrations.services.vulnerabilities; public enum ToolType { - SONAR, SSC, FOD; + SONAR, SSC, FOD } diff --git a/integrations-sdk/src/main/java/com/hp/octane/integrations/services/vulnerabilities/fod/FODValuesConverter.java b/integrations-sdk/src/main/java/com/hp/octane/integrations/services/vulnerabilities/fod/FODValuesConverter.java index 96f39ff4..90bf89d4 100644 --- a/integrations-sdk/src/main/java/com/hp/octane/integrations/services/vulnerabilities/fod/FODValuesConverter.java +++ b/integrations-sdk/src/main/java/com/hp/octane/integrations/services/vulnerabilities/fod/FODValuesConverter.java @@ -228,31 +228,22 @@ private void setStatus(OctaneIssue entity, String status) { } private String mapFODStatusToLogicalName(String status) { - switch (status) { - case "New": - return ISSUE_STATE_NEW; - case "Existing": - return ISSUE_STATE_EXISTING; - case "close": - return ISSUE_STATE_CLOSED; - default: - return null; - } + return switch (status) { + case "New" -> ISSUE_STATE_NEW; + case "Existing" -> ISSUE_STATE_EXISTING; + case "close" -> ISSUE_STATE_CLOSED; + default -> null; + }; } private String mapFODAnalysisToLogicalName(String analysis) { - switch (analysis) { - case "Waiting for review": - return MAYBE_AN_ISSUE; - case "Reviewed": - return REVIEWED; - case "bug submitted": - return BUG_SUBMITTED; - case "Not an issue": - return NOT_AN_ISSUE; - default: - return null; - } + return switch (analysis) { + case "Waiting for review" -> MAYBE_AN_ISSUE; + case "Reviewed" -> REVIEWED; + case "bug submitted" -> BUG_SUBMITTED; + case "Not an issue" -> NOT_AN_ISSUE; + default -> null; + }; } private String mapAuditorStatusToAnalysis(String auditorStatus) { diff --git a/integrations-sdk/src/main/java/com/hp/octane/integrations/services/vulnerabilities/fod/dto/FODConnector.java b/integrations-sdk/src/main/java/com/hp/octane/integrations/services/vulnerabilities/fod/dto/FODConnector.java index 597ce921..4a5b57ea 100644 --- a/integrations-sdk/src/main/java/com/hp/octane/integrations/services/vulnerabilities/fod/dto/FODConnector.java +++ b/integrations-sdk/src/main/java/com/hp/octane/integrations/services/vulnerabilities/fod/dto/FODConnector.java @@ -143,7 +143,7 @@ public T getAllFODEntities(String rawURL, Class< public T getSpeceficFODEntity(String rawURL, Class targetClass) { try { - T fetchedEntityInstance = targetClass.newInstance(); + T fetchedEntityInstance = targetClass.getDeclaredConstructor().newInstance(); String rawResponse = getRawResponseFromFOD(rawURL); //Deserialize. diff --git a/integrations-sdk/src/main/java/com/hp/octane/integrations/services/vulnerabilities/ssc/SSCProjectConnector.java b/integrations-sdk/src/main/java/com/hp/octane/integrations/services/vulnerabilities/ssc/SSCProjectConnector.java index e9d3b7ce..d18766a1 100644 --- a/integrations-sdk/src/main/java/com/hp/octane/integrations/services/vulnerabilities/ssc/SSCProjectConnector.java +++ b/integrations-sdk/src/main/java/com/hp/octane/integrations/services/vulnerabilities/ssc/SSCProjectConnector.java @@ -91,7 +91,7 @@ public ProjectVersions.ProjectVersion getProjectVersion() { if (projectVersions.getCount() == 0) { return null; } - return projectVersions.getData().get(0); + return projectVersions.getData().getFirst(); } private Integer getProjectId() { @@ -101,7 +101,7 @@ private Integer getProjectId() { if (projects.getCount() == 0) { return null; } - return projects.getData().get(0).id; + return projects.getData().getFirst().id; } public static T stringToObject(String response, Class type) { diff --git a/integrations-sdk/src/main/java/com/hp/octane/integrations/services/vulnerabilities/ssc/SSCServiceImpl.java b/integrations-sdk/src/main/java/com/hp/octane/integrations/services/vulnerabilities/ssc/SSCServiceImpl.java index cd57d1c8..fa50e57d 100644 --- a/integrations-sdk/src/main/java/com/hp/octane/integrations/services/vulnerabilities/ssc/SSCServiceImpl.java +++ b/integrations-sdk/src/main/java/com/hp/octane/integrations/services/vulnerabilities/ssc/SSCServiceImpl.java @@ -172,7 +172,7 @@ private List getNonCacheVulnerabilitiesScanResultStream(Vulnerabili private List getIssuesFromSSC(SSCHandler sscHandler, VulnerabilitiesQueueItem vulnerabilitiesQueueItem) { Optional allIssues = sscHandler.getIssuesIfScanCompleted(); - if (!allIssues.isPresent()) { + if (allIssues.isEmpty()) { logger.debug( vulnerabilitiesQueueItem.toString() + " not completed yet"); return null; } diff --git a/integrations-sdk/src/main/java/com/hp/octane/integrations/testresults/GherkinXmlWritableTestResult.java b/integrations-sdk/src/main/java/com/hp/octane/integrations/testresults/GherkinXmlWritableTestResult.java index 0e845a55..7c4e8261 100644 --- a/integrations-sdk/src/main/java/com/hp/octane/integrations/testresults/GherkinXmlWritableTestResult.java +++ b/integrations-sdk/src/main/java/com/hp/octane/integrations/testresults/GherkinXmlWritableTestResult.java @@ -84,8 +84,8 @@ private void writeXmlElement(XMLStreamWriter writer, Element rootElement) throws NodeList childNodes = rootElement.getChildNodes(); for (int c = 0; c < childNodes.getLength(); c++) { Node child = childNodes.item(c); - if (child instanceof Element) { - writeXmlElement(writer, (Element) child); + if (child instanceof Element element) { + writeXmlElement(writer, element); } else if (child.getNodeType() == Node.CDATA_SECTION_NODE) { if(child.getParentNode() != null && "error_message".equals(child.getParentNode().getNodeName())){ String errorMassage = child.getNodeValue(); diff --git a/integrations-sdk/src/main/java/com/hp/octane/integrations/uft/UftDiscoveryResultPreparerImpl.java b/integrations-sdk/src/main/java/com/hp/octane/integrations/uft/UftDiscoveryResultPreparerImpl.java index a0710b2f..2a23283f 100644 --- a/integrations-sdk/src/main/java/com/hp/octane/integrations/uft/UftDiscoveryResultPreparerImpl.java +++ b/integrations-sdk/src/main/java/com/hp/octane/integrations/uft/UftDiscoveryResultPreparerImpl.java @@ -274,7 +274,7 @@ private String getOctaneVersion(EntitiesService entitiesService) { List entities = entitiesService.getEntities(null, "server_version", null, null); if (entities.size() == 1) { - Entity entity = entities.get(0); + Entity entity = entities.getFirst(); octaneVersion = entity.getStringValue("version"); logger.debug("Received Octane version - " + octaneVersion); @@ -369,7 +369,7 @@ private void handleMovedTestsWithBulkTestRename(UftTestDiscoveryResult result) { String key = deletedTest.getChangeSetDst(); if (dst2Test.containsKey(key)) { if (dst2Test.get(key).size() == 1) { - AutomatedTest newTest = dst2Test.get(key).get(0); + AutomatedTest newTest = dst2Test.get(key).getFirst(); deleted2newMovedTests.add(new AbstractMap.SimpleEntry(deletedTest, newTest)); } else { AbstractMap.SimpleEntry pairsDeletedNew = createPairsDeletedNew(dst2Test.get(key), deletedTest, result); @@ -466,7 +466,7 @@ private AbstractMap.SimpleEntry createPairsDeleted }); if (deletedTestsList.size() == 1 && newTestsList.size() == 1) { - return new AbstractMap.SimpleEntry<>(deletedTestsList.get(0), newTestsList.get(0)); + return new AbstractMap.SimpleEntry<>(deletedTestsList.getFirst(), newTestsList.getFirst()); } else { return null; } diff --git a/integrations-sdk/src/main/java/com/hp/octane/integrations/uft/UftTestDiscoveryUtils.java b/integrations-sdk/src/main/java/com/hp/octane/integrations/uft/UftTestDiscoveryUtils.java index e632efec..6c3c981f 100644 --- a/integrations-sdk/src/main/java/com/hp/octane/integrations/uft/UftTestDiscoveryUtils.java +++ b/integrations-sdk/src/main/java/com/hp/octane/integrations/uft/UftTestDiscoveryUtils.java @@ -329,8 +329,8 @@ public static String extractXmlContentFromTspFile(InputStream stream) throws IOE if ("ComponentInfo".equals(name)) { if (entry instanceof DirectoryEntry) { System.out.println(entry); - } else if (entry instanceof DocumentEntry) { - byte[] content = new byte[((DocumentEntry) entry).getSize()]; + } else if (entry instanceof DocumentEntry documentEntry) { + byte[] content = new byte[documentEntry.getSize()]; int readBytes = poiFS.createDocumentInputStream("ComponentInfo").read(content); if (readBytes < content.length) { // [YG] probably should handle this case and continue to read diff --git a/integrations-sdk/src/main/java/com/hp/octane/integrations/uft/ufttestresults/UftTestResultsUtils.java b/integrations-sdk/src/main/java/com/hp/octane/integrations/uft/ufttestresults/UftTestResultsUtils.java index 3682812a..4533b119 100644 --- a/integrations-sdk/src/main/java/com/hp/octane/integrations/uft/ufttestresults/UftTestResultsUtils.java +++ b/integrations-sdk/src/main/java/com/hp/octane/integrations/uft/ufttestresults/UftTestResultsUtils.java @@ -88,8 +88,8 @@ private static void getErrorDataInternal(ReportNode node, List parents, .trim(); //last parent name might be as error message - in this case - don't show last parent - if (!parents.isEmpty() && error.startsWith(parents.get(parents.size() - 1))) { - parents.remove(parents.size() - 1); + if (!parents.isEmpty() && error.startsWith(parents.getLast())) { + parents.removeLast(); } errors.add(new UftResultStepData(parents, node.getType(), node.getData().getResult(), error, node.getData().getDuration())); } diff --git a/integrations-sdk/src/main/java/com/hp/octane/integrations/utils/CIPluginSDKUtils.java b/integrations-sdk/src/main/java/com/hp/octane/integrations/utils/CIPluginSDKUtils.java index 1bc224f0..d987bc51 100644 --- a/integrations-sdk/src/main/java/com/hp/octane/integrations/utils/CIPluginSDKUtils.java +++ b/integrations-sdk/src/main/java/com/hp/octane/integrations/utils/CIPluginSDKUtils.java @@ -164,7 +164,7 @@ public static CIProxyConfiguration getProxyConfiguration(String url, OctaneSDK.S if (configurer != null) { proxySupplier = configurer.pluginServices::getProxyConfiguration; } else if (OctaneSDK.hasClients()) { - proxySupplier = OctaneSDK.getClients().get(0).getRestService().getProxySupplier(); + proxySupplier = OctaneSDK.getClients().getFirst().getRestService().getProxySupplier(); } else { return null; } diff --git a/integrations-sdk/src/test/java/com/hp/octane/integrations/OctaneConfigurationTests.java b/integrations-sdk/src/test/java/com/hp/octane/integrations/OctaneConfigurationTests.java index 6e9f9973..6ee750bf 100644 --- a/integrations-sdk/src/test/java/com/hp/octane/integrations/OctaneConfigurationTests.java +++ b/integrations-sdk/src/test/java/com/hp/octane/integrations/OctaneConfigurationTests.java @@ -31,74 +31,90 @@ */ package com.hp.octane.integrations; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.util.UUID; +import static org.junit.jupiter.api.Assertions.assertThrows; + public class OctaneConfigurationTests { // illegal instance ID - @Test(expected = IllegalArgumentException.class) + @Test public void testA1() { - new OctaneConfigurationIntern(null, null, null); - } + assertThrows(IllegalArgumentException.class, () -> { + new OctaneConfigurationIntern(null, null, null); + }); + } - @Test(expected = IllegalArgumentException.class) + @Test public void testA2() { - new OctaneConfigurationIntern("", null, null); - } + assertThrows(IllegalArgumentException.class, () -> { + new OctaneConfigurationIntern("", null, null); + }); + } // illegal URL - @Test(expected = IllegalArgumentException.class) + @Test public void testB1() { - new OctaneConfigurationIntern(UUID.randomUUID().toString(), null, null); - } + assertThrows(IllegalArgumentException.class, () -> { + new OctaneConfigurationIntern(UUID.randomUUID().toString(), null, null); + }); + } - @Test(expected = IllegalArgumentException.class) + @Test public void testB2() { - new OctaneConfigurationIntern(UUID.randomUUID().toString(), "", null); - } + assertThrows(IllegalArgumentException.class, () -> { + new OctaneConfigurationIntern(UUID.randomUUID().toString(), "", null); + }); + } - @Test(expected = IllegalArgumentException.class) + @Test public void testB3() { - new OctaneConfigurationIntern(UUID.randomUUID().toString(), "non-valid-url", null); - } + assertThrows(IllegalArgumentException.class, () -> { + new OctaneConfigurationIntern(UUID.randomUUID().toString(), "non-valid-url", null); + }); + } // illegal shared space ID - @Test(expected = IllegalArgumentException.class) + @Test public void testC1() { - new OctaneConfigurationIntern(UUID.randomUUID().toString(), "http://localhost:9999", null); - } + assertThrows(IllegalArgumentException.class, () -> { + new OctaneConfigurationIntern(UUID.randomUUID().toString(), "http://localhost:9999", null); + }); + } - @Test(expected = IllegalArgumentException.class) + @Test public void testC2() { - new OctaneConfigurationIntern(UUID.randomUUID().toString(), "http://localhost:9999", ""); - } + assertThrows(IllegalArgumentException.class, () -> { + new OctaneConfigurationIntern(UUID.randomUUID().toString(), "http://localhost:9999", ""); + }); + } @Test public void testD() { OctaneConfiguration oc = new OctaneConfigurationIntern(UUID.randomUUID().toString(), "http://localhost:9999/some/path?query=false", "1002"); - Assert.assertNotNull(oc); - Assert.assertEquals("http://localhost:9999/some/path", oc.getUrl()); - Assert.assertNotNull(oc.toString()); - Assert.assertFalse(oc.toString().isEmpty()); - Assert.assertFalse(oc.attached); + Assertions.assertNotNull(oc); + Assertions.assertEquals("http://localhost:9999/some/path", oc.getUrl()); + Assertions.assertNotNull(oc.toString()); + Assertions.assertFalse(oc.toString().isEmpty()); + Assertions.assertFalse(oc.attached); } @Test public void testE() { OctaneConfiguration oc = new OctaneConfigurationIntern(UUID.randomUUID().toString(), "http://localhost:9999/some/path?query=false", "1002"); - Assert.assertNotNull(oc); + Assertions.assertNotNull(oc); oc.setUiLocation("https://some.host.com/some/path/ui?query=false&p=1002"); - Assert.assertEquals("https://some.host.com/some/path", oc.getUrl()); + Assertions.assertEquals("https://some.host.com/some/path", oc.getUrl()); oc.setUiLocation("http://localhost.end/ui?&p=1002"); - Assert.assertEquals("http://localhost.end", oc.getUrl()); + Assertions.assertEquals("http://localhost.end", oc.getUrl()); oc.setUiLocation("http://localhost.end:9999/ui?&p=1003"); - Assert.assertEquals("http://localhost.end:9999", oc.getUrl()); - Assert.assertEquals("1003", oc.getSharedSpace()); + Assertions.assertEquals("http://localhost.end:9999", oc.getUrl()); + Assertions.assertEquals("1003", oc.getSharedSpace()); } } diff --git a/integrations-sdk/src/test/java/com/hp/octane/integrations/OctaneSDKNegativeTests.java b/integrations-sdk/src/test/java/com/hp/octane/integrations/OctaneSDKNegativeTests.java index 6ec62f0d..fae5baae 100644 --- a/integrations-sdk/src/test/java/com/hp/octane/integrations/OctaneSDKNegativeTests.java +++ b/integrations-sdk/src/test/java/com/hp/octane/integrations/OctaneSDKNegativeTests.java @@ -34,13 +34,15 @@ import com.hp.octane.integrations.dto.DTOFactory; import com.hp.octane.integrations.dto.general.CIPluginInfo; import com.hp.octane.integrations.dto.general.CIServerInfo; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.util.UUID; +import static org.junit.jupiter.api.Assertions.assertThrows; + /** * Octane SDK tests */ @@ -48,134 +50,159 @@ public class OctaneSDKNegativeTests { private static DTOFactory dtoFactory = DTOFactory.getInstance(); - @Test(expected = IllegalArgumentException.class) + @Test public void sdkTestNegativeA() { - OctaneSDK.addClient(null, null); + assertThrows(IllegalArgumentException.class, () -> + OctaneSDK.addClient(null, null)); } // bad plugin services class - @Test(expected = IllegalArgumentException.class) + @Test public void sdkTestNegativeC() { - OctaneConfiguration oc = new OctaneConfigurationIntern(UUID.randomUUID().toString(), "http://localhost", UUID.randomUUID().toString(), null, null); - OctaneSDK.addClient(oc, null); + assertThrows(IllegalArgumentException.class, () -> { + OctaneConfiguration oc = new OctaneConfigurationIntern(UUID.randomUUID().toString(), "http://localhost", UUID.randomUUID().toString(), null, null); + OctaneSDK.addClient(oc, null); + }); } - @Test(expected = IllegalArgumentException.class) + @Test public void sdkTestNegativeC1() { - OctaneConfiguration oc = new OctaneConfigurationIntern(UUID.randomUUID().toString(), "http://localhost", UUID.randomUUID().toString(), null, null); - OctaneSDK.addClient(oc, PluginServices1.class); + assertThrows(IllegalArgumentException.class, () -> { + OctaneConfiguration oc = new OctaneConfigurationIntern(UUID.randomUUID().toString(), "http://localhost", UUID.randomUUID().toString(), null, null); + OctaneSDK.addClient(oc, PluginServices1.class); + }); } - @Test(expected = IllegalArgumentException.class) + @Test public void sdkTestNegativeC2() { - OctaneConfiguration oc = new OctaneConfigurationIntern(UUID.randomUUID().toString(), "http://localhost", UUID.randomUUID().toString(), null, null); - OctaneSDK.addClient(oc, PluginServices2.class); + assertThrows(IllegalArgumentException.class, () -> { + OctaneConfiguration oc = new OctaneConfigurationIntern(UUID.randomUUID().toString(), "http://localhost", UUID.randomUUID().toString(), null, null); + OctaneSDK.addClient(oc, PluginServices2.class); + }); } - @Test(expected = IllegalArgumentException.class) + @Test public void sdkTestNegativeC3() { - OctaneConfiguration oc = new OctaneConfigurationIntern(UUID.randomUUID().toString(), "http://localhost", UUID.randomUUID().toString(), null, null); - OctaneSDK.addClient(oc, PluginServices3.class); + assertThrows(IllegalArgumentException.class, () -> { + OctaneConfiguration oc = new OctaneConfigurationIntern(UUID.randomUUID().toString(), "http://localhost", UUID.randomUUID().toString(), null, null); + OctaneSDK.addClient(oc, PluginServices3.class); + }); } // duplicate OctaneConfiguration instance - @Test(expected = IllegalStateException.class) + @Test public void sdkTestNegativeE1() { - OctaneConfiguration oc = new OctaneConfigurationIntern(UUID.randomUUID().toString(), "http://localhost", UUID.randomUUID().toString(), null, null); - OctaneClient successfulOne = OctaneSDK.addClient(oc, PluginServices.class); - try { - OctaneSDK.addClient(oc, PluginServices.class); - } finally { - Assert.assertNotNull(OctaneSDK.removeClient(successfulOne)); - } + assertThrows(IllegalStateException.class, () -> { + OctaneConfiguration oc = new OctaneConfigurationIntern(UUID.randomUUID().toString(), "http://localhost", UUID.randomUUID().toString(), null, null); + OctaneClient successfulOne = OctaneSDK.addClient(oc, PluginServices.class); + try { + OctaneSDK.addClient(oc, PluginServices.class); + } finally { + Assertions.assertNotNull(OctaneSDK.removeClient(successfulOne)); + } + }); } // duplicate instance ID - @Test(expected = IllegalStateException.class) + @Test public void sdkTestNegativeE2() { - String sp1 = UUID.randomUUID().toString(); - String sp2 = UUID.randomUUID().toString(); - OctaneConfiguration oc1 = new OctaneConfigurationIntern(UUID.randomUUID().toString(), "http://localhost", sp1, null, null); - OctaneConfiguration oc2 = new OctaneConfigurationIntern(oc1.getInstanceId(), "http://localhost", sp2, null, null); - OctaneClient successfulOne = OctaneSDK.addClient(oc1, PluginServices.class); - try { - OctaneSDK.addClient(oc2, PluginServices.class); - } finally { - Assert.assertNotNull(OctaneSDK.removeClient(successfulOne)); - } + assertThrows(IllegalStateException.class, () -> { + String sp1 = UUID.randomUUID().toString(); + String sp2 = UUID.randomUUID().toString(); + OctaneConfiguration oc1 = new OctaneConfigurationIntern(UUID.randomUUID().toString(), "http://localhost", sp1, null, null); + OctaneConfiguration oc2 = new OctaneConfigurationIntern(oc1.getInstanceId(), "http://localhost", sp2, null, null); + OctaneClient successfulOne = OctaneSDK.addClient(oc1, PluginServices.class); + try { + OctaneSDK.addClient(oc2, PluginServices.class); + } finally { + Assertions.assertNotNull(OctaneSDK.removeClient(successfulOne)); + } + }); } // duplicate shared space ID - @Test(expected = IllegalStateException.class) + @Test public void sdkTestNegativeE3() { - String sp = UUID.randomUUID().toString(); - OctaneConfiguration oc1 = new OctaneConfigurationIntern(UUID.randomUUID().toString(), "http://localhost", sp, null, null); - OctaneConfiguration oc2 = new OctaneConfigurationIntern(UUID.randomUUID().toString(), "http://localhost", sp, null, null); - OctaneClient successfulOne = OctaneSDK.addClient(oc1, PluginServices.class); - try { - OctaneSDK.addClient(oc2, PluginServices.class); - } finally { - Assert.assertNotNull(OctaneSDK.removeClient(successfulOne)); - } + assertThrows(IllegalStateException.class, () -> { + String sp = UUID.randomUUID().toString(); + OctaneConfiguration oc1 = new OctaneConfigurationIntern(UUID.randomUUID().toString(), "http://localhost", sp, null, null); + OctaneConfiguration oc2 = new OctaneConfigurationIntern(UUID.randomUUID().toString(), "http://localhost", sp, null, null); + OctaneClient successfulOne = OctaneSDK.addClient(oc1, PluginServices.class); + try { + OctaneSDK.addClient(oc2, PluginServices.class); + } finally { + Assertions.assertNotNull(OctaneSDK.removeClient(successfulOne)); + } + }); } // instance ID on plugin service - @Test(expected = IllegalArgumentException.class) + @Test public void sdkTestNegativeF1() { - CIPluginServices ps = new PluginServices(); - Assert.assertNull(ps.getInstanceId()); - ps.setInstanceId(null); + assertThrows(IllegalArgumentException.class, () -> { + CIPluginServices ps = new PluginServices(); + Assertions.assertNull(ps.getInstanceId()); + ps.setInstanceId(null); + }); } - @Test(expected = IllegalArgumentException.class) + @Test public void sdkTestNegativeF2() { - CIPluginServices ps = new PluginServices(); - Assert.assertNull(ps.getInstanceId()); - ps.setInstanceId(""); + assertThrows(IllegalArgumentException.class, () -> { + CIPluginServices ps = new PluginServices(); + Assertions.assertNull(ps.getInstanceId()); + ps.setInstanceId(""); + }); } - @Test(expected = IllegalStateException.class) + @Test public void sdkTestNegativeF3() { - String instanceId = UUID.randomUUID().toString(); - String sp = UUID.randomUUID().toString(); - OctaneConfiguration oc = new OctaneConfigurationIntern(instanceId, "http://localhost", sp, null, null); - OctaneClient client = OctaneSDK.addClient(oc, PluginServices4.class); - try { - // verify existing - Assert.assertNotNull(PluginServices4.proxyGetInstanceId()); - Assert.assertEquals(instanceId, PluginServices4.proxyGetInstanceId()); - - // set to the same does nothing and not throws - PluginServices4.proxySetInstanceId(instanceId); - Assert.assertEquals(instanceId, PluginServices4.proxyGetInstanceId()); - - // set to something else throws IllegalStateException - PluginServices4.proxySetInstanceId(UUID.randomUUID().toString()); - } finally { - Assert.assertNotNull(OctaneSDK.removeClient(client)); - } + assertThrows(IllegalStateException.class, () -> { + String instanceId = UUID.randomUUID().toString(); + String sp = UUID.randomUUID().toString(); + OctaneConfiguration oc = new OctaneConfigurationIntern(instanceId, "http://localhost", sp, null, null); + OctaneClient client = OctaneSDK.addClient(oc, PluginServices4.class); + try { + // verify existing + Assertions.assertNotNull(PluginServices4.proxyGetInstanceId()); + Assertions.assertEquals(instanceId, PluginServices4.proxyGetInstanceId()); + + // set to the same does nothing and not throws + PluginServices4.proxySetInstanceId(instanceId); + Assertions.assertEquals(instanceId, PluginServices4.proxyGetInstanceId()); + + // set to something else throws IllegalStateException + PluginServices4.proxySetInstanceId(UUID.randomUUID().toString()); + } finally { + Assertions.assertNotNull(OctaneSDK.removeClient(client)); + } + }); } // get client by instance ID - @Test(expected = IllegalArgumentException.class) + @Test public void sdkTestNegativeG() { - OctaneSDK.getClientByInstanceId(null); + assertThrows(IllegalArgumentException.class, () -> + OctaneSDK.getClientByInstanceId(null)); } - @Test(expected = IllegalArgumentException.class) + @Test public void sdkTestNegativeH() { - OctaneSDK.getClientByInstanceId(""); + assertThrows(IllegalArgumentException.class, () -> + OctaneSDK.getClientByInstanceId("")); } - @Test(expected = IllegalStateException.class) + @Test public void sdkTestNegativeI() { - OctaneSDK.getClientByInstanceId("none-existing-one"); + assertThrows(IllegalStateException.class, () -> + OctaneSDK.getClientByInstanceId("none-existing-one")); } // remove client - @Test(expected = IllegalArgumentException.class) + @Test public void sdkTestNegativeL() { - OctaneSDK.removeClient(null); + assertThrows(IllegalArgumentException.class, () -> + OctaneSDK.removeClient(null)); } @Test @@ -187,8 +214,8 @@ public void sdkTestNegativeM() { OctaneClient successfulOne = OctaneSDK.addClient(oc1, PluginServices.class); OctaneClient successfulTwo = OctaneSDK.addClient(oc2, PluginServices.class); OctaneClient removed = OctaneSDK.removeClient(successfulOne); - Assert.assertNull(OctaneSDK.removeClient(removed)); - Assert.assertNotNull(OctaneSDK.removeClient(successfulTwo)); + Assertions.assertNull(OctaneSDK.removeClient(removed)); + Assertions.assertNotNull(OctaneSDK.removeClient(successfulTwo)); } @Test @@ -196,162 +223,182 @@ public void sdkTestNegativeN() { String sp = UUID.randomUUID().toString(); OctaneConfiguration oc = new OctaneConfigurationIntern(UUID.randomUUID().toString(), "http://localhost", sp, null, null); OctaneClient successfulOne = OctaneSDK.addClient(oc, PluginServices.class); - Assert.assertNotNull(OctaneSDK.removeClient(successfulOne)); - Assert.assertNull(OctaneSDK.removeClient(successfulOne)); + Assertions.assertNotNull(OctaneSDK.removeClient(successfulOne)); + Assertions.assertNull(OctaneSDK.removeClient(successfulOne)); } // client dynamically breaks unique instanceId/farm/sharedSpaceId contract - @Test(expected = IllegalArgumentException.class) + @Test public void sdkTestNegativeO1() { - String sp1 = UUID.randomUUID().toString(); - String sp2 = UUID.randomUUID().toString(); - OctaneConfiguration oc1 = new OctaneConfigurationIntern(UUID.randomUUID().toString(), "http://localhost", sp1, null, null); - OctaneConfiguration oc2 = new OctaneConfigurationIntern(UUID.randomUUID().toString(), "http://localhost", sp2, null, null); - OctaneClient clientA = OctaneSDK.addClient(oc1, PluginServices.class); - OctaneClient clientB = OctaneSDK.addClient(oc2, PluginServices.class); - Assert.assertNotNull(clientA); - Assert.assertNotNull(clientB); - - try { - oc1.setUrlAndSpace(oc2.getUrl(), oc2.getSharedSpace()); - } finally { - Assert.assertNotNull(OctaneSDK.removeClient(clientA)); - Assert.assertNotNull(OctaneSDK.removeClient(clientB)); - } + assertThrows(IllegalArgumentException.class, () -> { + String sp1 = UUID.randomUUID().toString(); + String sp2 = UUID.randomUUID().toString(); + OctaneConfiguration oc1 = new OctaneConfigurationIntern(UUID.randomUUID().toString(), "http://localhost", sp1, null, null); + OctaneConfiguration oc2 = new OctaneConfigurationIntern(UUID.randomUUID().toString(), "http://localhost", sp2, null, null); + OctaneClient clientA = OctaneSDK.addClient(oc1, PluginServices.class); + OctaneClient clientB = OctaneSDK.addClient(oc2, PluginServices.class); + Assertions.assertNotNull(clientA); + Assertions.assertNotNull(clientB); + + try { + oc1.setUrlAndSpace(oc2.getUrl(), oc2.getSharedSpace()); + } finally { + Assertions.assertNotNull(OctaneSDK.removeClient(clientA)); + Assertions.assertNotNull(OctaneSDK.removeClient(clientB)); + } + }); } - @Test(expected = IllegalArgumentException.class) + @Test public void sdkTestNegativeO2() { - String url1 = "http://localhost"; - String url2 = "http://localhost1"; - String sp = UUID.randomUUID().toString(); - OctaneConfiguration oc1 = new OctaneConfigurationIntern(UUID.randomUUID().toString(), url1, sp, null, null); - OctaneConfiguration oc2 = new OctaneConfigurationIntern(UUID.randomUUID().toString(), url2, sp, null, null); - OctaneClient clientA = OctaneSDK.addClient(oc1, PluginServices.class); - OctaneClient clientB = OctaneSDK.addClient(oc2, PluginServices.class); - Assert.assertNotNull(clientA); - Assert.assertNotNull(clientB); - - try { - oc1.setUrlAndSpace(oc2.getUrl(), oc2.getSharedSpace()); - } finally { - Assert.assertNotNull(OctaneSDK.removeClient(clientA)); - Assert.assertNotNull(OctaneSDK.removeClient(clientB)); - } + assertThrows(IllegalArgumentException.class, () -> { + String url1 = "http://localhost"; + String url2 = "http://localhost1"; + String sp = UUID.randomUUID().toString(); + OctaneConfiguration oc1 = new OctaneConfigurationIntern(UUID.randomUUID().toString(), url1, sp, null, null); + OctaneConfiguration oc2 = new OctaneConfigurationIntern(UUID.randomUUID().toString(), url2, sp, null, null); + OctaneClient clientA = OctaneSDK.addClient(oc1, PluginServices.class); + OctaneClient clientB = OctaneSDK.addClient(oc2, PluginServices.class); + Assertions.assertNotNull(clientA); + Assertions.assertNotNull(clientB); + + try { + oc1.setUrlAndSpace(oc2.getUrl(), oc2.getSharedSpace()); + } finally { + Assertions.assertNotNull(OctaneSDK.removeClient(clientA)); + Assertions.assertNotNull(OctaneSDK.removeClient(clientB)); + } + }); } - @Test(expected = IllegalArgumentException.class) + @Test public void sdkTestNegativeO3() { - String url1 = "http://localhost:8080"; - String url2 = "http://localhost:8081"; - String sp = UUID.randomUUID().toString(); - OctaneConfiguration oc1 = new OctaneConfigurationIntern(UUID.randomUUID().toString(), url1, sp, null, null); - OctaneConfiguration oc2 = new OctaneConfigurationIntern(UUID.randomUUID().toString(), url2, sp, null, null); - OctaneClient clientA = OctaneSDK.addClient(oc1, PluginServices.class); - OctaneClient clientB = OctaneSDK.addClient(oc2, PluginServices.class); - Assert.assertNotNull(clientA); - Assert.assertNotNull(clientB); - - try { - oc1.setUrlAndSpace(oc2.getUrl(), oc2.getSharedSpace()); - } finally { - Assert.assertNotNull(OctaneSDK.removeClient(clientA)); - Assert.assertNotNull(OctaneSDK.removeClient(clientB)); - } + assertThrows(IllegalArgumentException.class, () -> { + String url1 = "http://localhost:8080"; + String url2 = "http://localhost:8081"; + String sp = UUID.randomUUID().toString(); + OctaneConfiguration oc1 = new OctaneConfigurationIntern(UUID.randomUUID().toString(), url1, sp, null, null); + OctaneConfiguration oc2 = new OctaneConfigurationIntern(UUID.randomUUID().toString(), url2, sp, null, null); + OctaneClient clientA = OctaneSDK.addClient(oc1, PluginServices.class); + OctaneClient clientB = OctaneSDK.addClient(oc2, PluginServices.class); + Assertions.assertNotNull(clientA); + Assertions.assertNotNull(clientB); + + try { + oc1.setUrlAndSpace(oc2.getUrl(), oc2.getSharedSpace()); + } finally { + Assertions.assertNotNull(OctaneSDK.removeClient(clientA)); + Assertions.assertNotNull(OctaneSDK.removeClient(clientB)); + } + }); } - @Test(expected = IllegalArgumentException.class) + @Test public void sdkTestNegativeO4() { - String url1 = "http://localhost:8080"; - String url2 = "http://localhost:8081"; - String sp = UUID.randomUUID().toString(); - OctaneConfiguration oc1 = new OctaneConfigurationIntern(UUID.randomUUID().toString(), url1, sp, null, null); - OctaneConfiguration oc2 = new OctaneConfigurationIntern(UUID.randomUUID().toString(), url2, sp, null, null); - OctaneClient clientA = OctaneSDK.addClient(oc1, PluginServices.class); - OctaneClient clientB = OctaneSDK.addClient(oc2, PluginServices.class); - Assert.assertNotNull(clientA); - Assert.assertNotNull(clientB); - - try { - oc1.setUrlAndSpace(oc2.getUrl(), oc2.getSharedSpace()); - } finally { - Assert.assertNotNull(OctaneSDK.removeClient(clientA)); - Assert.assertNotNull(OctaneSDK.removeClient(clientB)); - } + assertThrows(IllegalArgumentException.class, () -> { + String url1 = "http://localhost:8080"; + String url2 = "http://localhost:8081"; + String sp = UUID.randomUUID().toString(); + OctaneConfiguration oc1 = new OctaneConfigurationIntern(UUID.randomUUID().toString(), url1, sp, null, null); + OctaneConfiguration oc2 = new OctaneConfigurationIntern(UUID.randomUUID().toString(), url2, sp, null, null); + OctaneClient clientA = OctaneSDK.addClient(oc1, PluginServices.class); + OctaneClient clientB = OctaneSDK.addClient(oc2, PluginServices.class); + Assertions.assertNotNull(clientA); + Assertions.assertNotNull(clientB); + + try { + oc1.setUrlAndSpace(oc2.getUrl(), oc2.getSharedSpace()); + } finally { + Assertions.assertNotNull(OctaneSDK.removeClient(clientA)); + Assertions.assertNotNull(OctaneSDK.removeClient(clientB)); + } + }); } - @Test(expected = IllegalArgumentException.class) + @Test public void sdkTestNegativeO5() { - String sp = UUID.randomUUID().toString(); - OctaneConfiguration oc = new OctaneConfigurationIntern(UUID.randomUUID().toString(), "http://localhost", sp, null, null); - OctaneClient client = OctaneSDK.addClient(oc, PluginServices.class); - Assert.assertNotNull(client); + assertThrows(IllegalArgumentException.class, () -> { + String sp = UUID.randomUUID().toString(); + OctaneConfiguration oc = new OctaneConfigurationIntern(UUID.randomUUID().toString(), "http://localhost", sp, null, null); + OctaneClient client = OctaneSDK.addClient(oc, PluginServices.class); + Assertions.assertNotNull(client); - try { - oc.setUrlAndSpace(oc.getUrl(), null); - } finally { - Assert.assertNotNull(OctaneSDK.removeClient(client)); - } + try { + oc.setUrlAndSpace(oc.getUrl(), null); + } finally { + Assertions.assertNotNull(OctaneSDK.removeClient(client)); + } + }); } - @Test(expected = IllegalArgumentException.class) + @Test public void sdkTestNegativeO6() { - String sp = UUID.randomUUID().toString(); - OctaneConfiguration oc = new OctaneConfigurationIntern(UUID.randomUUID().toString(), "http://localhost", sp, null, null); - OctaneClient client = OctaneSDK.addClient(oc, PluginServices.class); - Assert.assertNotNull(client); + assertThrows(IllegalArgumentException.class, () -> { + String sp = UUID.randomUUID().toString(); + OctaneConfiguration oc = new OctaneConfigurationIntern(UUID.randomUUID().toString(), "http://localhost", sp, null, null); + OctaneClient client = OctaneSDK.addClient(oc, PluginServices.class); + Assertions.assertNotNull(client); - try { - oc.setUrlAndSpace(oc.getUrl(), ""); - } finally { - Assert.assertNotNull(OctaneSDK.removeClient(client)); - } + try { + oc.setUrlAndSpace(oc.getUrl(), ""); + } finally { + Assertions.assertNotNull(OctaneSDK.removeClient(client)); + } + }); } // illegal OctaneConfiguration properties for test Octane configuration - @Test(expected = IllegalArgumentException.class) + @Test public void sdkTestNegativeQ1() throws IOException { - OctaneSDK.testOctaneConfigurationAndFetchAvailableWorkspaces(null, null, null, null, null); + assertThrows(IllegalArgumentException.class, () -> + OctaneSDK.testOctaneConfigurationAndFetchAvailableWorkspaces(null, null, null, null, null)); } - @Test(expected = IllegalArgumentException.class) + @Test public void sdkTestNegativeQ2() throws IOException { - OctaneSDK.testOctaneConfigurationAndFetchAvailableWorkspaces("non-valid-url", null, null, null, null); + assertThrows(IllegalArgumentException.class, () -> + OctaneSDK.testOctaneConfigurationAndFetchAvailableWorkspaces("non-valid-url", null, null, null, null)); } - @Test(expected = IllegalArgumentException.class) + @Test public void sdkTestNegativeQ3() throws IOException { - OctaneSDK.testOctaneConfigurationAndFetchAvailableWorkspaces("http://localhost:9999", null, null, null, null); + assertThrows(IllegalArgumentException.class, () -> + OctaneSDK.testOctaneConfigurationAndFetchAvailableWorkspaces("http://localhost:9999", null, null, null, null)); } - @Test(expected = IllegalArgumentException.class) + @Test public void sdkTestNegativeQ4() throws IOException { - OctaneSDK.testOctaneConfigurationAndFetchAvailableWorkspaces("http://localhost:9999", "", null, null, null); + assertThrows(IllegalArgumentException.class, () -> + OctaneSDK.testOctaneConfigurationAndFetchAvailableWorkspaces("http://localhost:9999", "", null, null, null)); } - @Test(expected = IllegalArgumentException.class) + @Test public void sdkTestNegativeQ5() throws IOException { - OctaneSDK.testOctaneConfigurationAndFetchAvailableWorkspaces("http://localhost:9999", "1001", null, null, null); + assertThrows(IllegalArgumentException.class, () -> + OctaneSDK.testOctaneConfigurationAndFetchAvailableWorkspaces("http://localhost:9999", "1001", null, null, null)); } - @Test(expected = IllegalArgumentException.class) + @Test public void sdkTestNegativeQ6() throws IOException { - OctaneSDK.testOctaneConfigurationAndFetchAvailableWorkspaces("http://localhost:9999", "1001", null, null, PluginServices3.class); + assertThrows(IllegalArgumentException.class, () -> + OctaneSDK.testOctaneConfigurationAndFetchAvailableWorkspaces("http://localhost:9999", "1001", null, null, PluginServices3.class)); } // illegal OctaneClient creation - @Test(expected = IllegalArgumentException.class) + @Test public void sdkTestNegativeR() { - new OctaneClientImpl(null); + assertThrows(IllegalArgumentException.class, () -> { + new OctaneClientImpl(null); + }); } @Test public void sdkTestNegativeS() { try { OctaneSDK.SDKServicesConfigurer.class.getConstructor(OctaneConfiguration.class, CIPluginServices.class).newInstance(null, null); - Assert.fail("should not be able to create"); + Assertions.fail("should not be able to create"); } catch (InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e) { - Assert.assertNotNull(e); + Assertions.assertNotNull(e); } } diff --git a/integrations-sdk/src/test/java/com/hp/octane/integrations/OctaneSDKPositiveTests.java b/integrations-sdk/src/test/java/com/hp/octane/integrations/OctaneSDKPositiveTests.java index bd81fecc..e801c63b 100644 --- a/integrations-sdk/src/test/java/com/hp/octane/integrations/OctaneSDKPositiveTests.java +++ b/integrations-sdk/src/test/java/com/hp/octane/integrations/OctaneSDKPositiveTests.java @@ -34,8 +34,8 @@ import com.hp.octane.integrations.dto.DTOFactory; import com.hp.octane.integrations.dto.general.CIPluginInfo; import com.hp.octane.integrations.dto.general.CIServerInfo; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.io.File; import java.util.List; @@ -51,7 +51,7 @@ public class OctaneSDKPositiveTests { @Test public void sdkTestA() { List octaneClients = OctaneSDK.getClients(); - Assert.assertNotNull(octaneClients); + Assertions.assertNotNull(octaneClients); String instance1 = UUID.randomUUID().toString(); String instance2 = UUID.randomUUID().toString(); OctaneConfiguration oc1 = new OctaneConfigurationIntern(instance1, "http://localhost", "1001", null, null); @@ -61,18 +61,18 @@ public void sdkTestA() { OctaneSDK.addClient(oc2, PluginServices.class); octaneClients = OctaneSDK.getClients(); - Assert.assertNotNull(octaneClients); - Assert.assertFalse(octaneClients.isEmpty()); + Assertions.assertNotNull(octaneClients); + Assertions.assertFalse(octaneClients.isEmpty()); OctaneClient client = OctaneSDK.getClientByInstanceId(oc1.getInstanceId()); - Assert.assertNotNull(client); - Assert.assertEquals(instance1, client.getInstanceId()); - Assert.assertEquals(oc1, client.getConfigurationService().getConfiguration()); + Assertions.assertNotNull(client); + Assertions.assertEquals(instance1, client.getInstanceId()); + Assertions.assertEquals(oc1, client.getConfigurationService().getConfiguration()); client = OctaneSDK.getClientByInstanceId(oc2.getInstanceId()); - Assert.assertNotNull(client); - Assert.assertEquals(instance2, client.getInstanceId()); - Assert.assertEquals(oc2, client.getConfigurationService().getConfiguration()); + Assertions.assertNotNull(client); + Assertions.assertEquals(instance2, client.getInstanceId()); + Assertions.assertEquals(oc2, client.getConfigurationService().getConfiguration()); OctaneSDK.getClients().forEach(OctaneSDK::removeClient); } @@ -87,22 +87,22 @@ public void sdkTestB() { OctaneSDK.addClient(oc, PluginServices.class); OctaneClient client = OctaneSDK.getClientByInstanceId(oc.getInstanceId()); - Assert.assertNotNull(client); - Assert.assertEquals(instance, client.getInstanceId()); - Assert.assertEquals(url, client.getConfigurationService().getConfiguration().getUrl()); - Assert.assertEquals(sp, client.getConfigurationService().getConfiguration().getSharedSpace()); + Assertions.assertNotNull(client); + Assertions.assertEquals(instance, client.getInstanceId()); + Assertions.assertEquals(url, client.getConfigurationService().getConfiguration().getUrl()); + Assertions.assertEquals(sp, client.getConfigurationService().getConfiguration().getSharedSpace()); // same values should work smooth oc.setUrlAndSpace(url, sp); - Assert.assertEquals(url, client.getConfigurationService().getConfiguration().getUrl()); - Assert.assertEquals(sp, client.getConfigurationService().getConfiguration().getSharedSpace()); + Assertions.assertEquals(url, client.getConfigurationService().getConfiguration().getUrl()); + Assertions.assertEquals(sp, client.getConfigurationService().getConfiguration().getSharedSpace()); // new unique values should work as well url = "http://localhost:8081"; sp = UUID.randomUUID().toString(); oc.setUrlAndSpace(url, sp); - Assert.assertEquals(url, client.getConfigurationService().getConfiguration().getUrl()); - Assert.assertEquals(sp, client.getConfigurationService().getConfiguration().getSharedSpace()); + Assertions.assertEquals(url, client.getConfigurationService().getConfiguration().getUrl()); + Assertions.assertEquals(sp, client.getConfigurationService().getConfiguration().getSharedSpace()); OctaneSDK.getClients().forEach(OctaneSDK::removeClient); } @@ -115,50 +115,50 @@ public void sdkTestD() { OctaneClient clientB = OctaneSDK.addClient(oc2, PluginServices.class); try { - Assert.assertNotNull(clientA); - Assert.assertNotNull(clientB); - - Assert.assertNotNull(clientA.getConfigurationService()); - Assert.assertNotNull(clientA.getCoverageService()); - Assert.assertNotNull(clientA.getSonarService()); - Assert.assertNotNull(clientA.getEntitiesService()); - Assert.assertNotNull(clientA.getEventsService()); - Assert.assertNotNull(clientA.getLogsService()); - Assert.assertNotNull(clientA.getPipelineContextService()); - Assert.assertNotNull(clientA.getRestService()); - Assert.assertNotNull(clientA.getTasksProcessor()); - Assert.assertNotNull(clientA.getTestsService()); - Assert.assertNotNull(clientA.getRestService()); - Assert.assertNotNull(clientA.getVulnerabilitiesService()); - - Assert.assertNotNull(clientB.getConfigurationService()); - Assert.assertNotNull(clientB.getCoverageService()); - Assert.assertNotNull(clientB.getSonarService()); - Assert.assertNotNull(clientB.getEntitiesService()); - Assert.assertNotNull(clientB.getEventsService()); - Assert.assertNotNull(clientB.getLogsService()); - Assert.assertNotNull(clientB.getPipelineContextService()); - Assert.assertNotNull(clientB.getRestService()); - Assert.assertNotNull(clientB.getTasksProcessor()); - Assert.assertNotNull(clientB.getTestsService()); - Assert.assertNotNull(clientB.getRestService()); - Assert.assertNotNull(clientB.getVulnerabilitiesService()); - - Assert.assertNotEquals(clientA.getConfigurationService(), clientB.getConfigurationService()); - Assert.assertNotEquals(clientA.getCoverageService(), clientB.getCoverageService()); - Assert.assertNotEquals(clientA.getSonarService(), clientB.getSonarService()); - Assert.assertNotEquals(clientA.getEntitiesService(), clientB.getEntitiesService()); - Assert.assertNotEquals(clientA.getEventsService(), clientB.getEventsService()); - Assert.assertNotEquals(clientA.getLogsService(), clientB.getLogsService()); - Assert.assertNotEquals(clientA.getPipelineContextService(), clientB.getPipelineContextService()); - Assert.assertNotEquals(clientA.getRestService(), clientB.getRestService()); - Assert.assertNotEquals(clientA.getTasksProcessor(), clientB.getTasksProcessor()); - Assert.assertNotEquals(clientA.getTestsService(), clientB.getTestsService()); - Assert.assertNotEquals(clientA.getRestService(), clientB.getRestService()); - Assert.assertNotEquals(clientA.getVulnerabilitiesService(), clientB.getVulnerabilitiesService()); + Assertions.assertNotNull(clientA); + Assertions.assertNotNull(clientB); + + Assertions.assertNotNull(clientA.getConfigurationService()); + Assertions.assertNotNull(clientA.getCoverageService()); + Assertions.assertNotNull(clientA.getSonarService()); + Assertions.assertNotNull(clientA.getEntitiesService()); + Assertions.assertNotNull(clientA.getEventsService()); + Assertions.assertNotNull(clientA.getLogsService()); + Assertions.assertNotNull(clientA.getPipelineContextService()); + Assertions.assertNotNull(clientA.getRestService()); + Assertions.assertNotNull(clientA.getTasksProcessor()); + Assertions.assertNotNull(clientA.getTestsService()); + Assertions.assertNotNull(clientA.getRestService()); + Assertions.assertNotNull(clientA.getVulnerabilitiesService()); + + Assertions.assertNotNull(clientB.getConfigurationService()); + Assertions.assertNotNull(clientB.getCoverageService()); + Assertions.assertNotNull(clientB.getSonarService()); + Assertions.assertNotNull(clientB.getEntitiesService()); + Assertions.assertNotNull(clientB.getEventsService()); + Assertions.assertNotNull(clientB.getLogsService()); + Assertions.assertNotNull(clientB.getPipelineContextService()); + Assertions.assertNotNull(clientB.getRestService()); + Assertions.assertNotNull(clientB.getTasksProcessor()); + Assertions.assertNotNull(clientB.getTestsService()); + Assertions.assertNotNull(clientB.getRestService()); + Assertions.assertNotNull(clientB.getVulnerabilitiesService()); + + Assertions.assertNotEquals(clientA.getConfigurationService(), clientB.getConfigurationService()); + Assertions.assertNotEquals(clientA.getCoverageService(), clientB.getCoverageService()); + Assertions.assertNotEquals(clientA.getSonarService(), clientB.getSonarService()); + Assertions.assertNotEquals(clientA.getEntitiesService(), clientB.getEntitiesService()); + Assertions.assertNotEquals(clientA.getEventsService(), clientB.getEventsService()); + Assertions.assertNotEquals(clientA.getLogsService(), clientB.getLogsService()); + Assertions.assertNotEquals(clientA.getPipelineContextService(), clientB.getPipelineContextService()); + Assertions.assertNotEquals(clientA.getRestService(), clientB.getRestService()); + Assertions.assertNotEquals(clientA.getTasksProcessor(), clientB.getTasksProcessor()); + Assertions.assertNotEquals(clientA.getTestsService(), clientB.getTestsService()); + Assertions.assertNotEquals(clientA.getRestService(), clientB.getRestService()); + Assertions.assertNotEquals(clientA.getVulnerabilitiesService(), clientB.getVulnerabilitiesService()); } finally { - Assert.assertNotNull(OctaneSDK.removeClient(clientA)); - Assert.assertNotNull(OctaneSDK.removeClient(clientB)); + Assertions.assertNotNull(OctaneSDK.removeClient(clientA)); + Assertions.assertNotNull(OctaneSDK.removeClient(clientB)); } } @@ -167,9 +167,9 @@ public void sdkTestE() { OctaneConfiguration oc = new OctaneConfigurationIntern(UUID.randomUUID().toString(), "http://localhost", "1001", null, null); OctaneClient client = OctaneSDK.addClient(oc, PluginServices.class); - Assert.assertEquals("OctaneClientImpl{ instanceId: " + oc.getInstanceId() + " }", client.toString()); + Assertions.assertEquals("OctaneClientImpl{ instanceId: " + oc.getInstanceId() + " }", client.toString()); - Assert.assertNotNull(OctaneSDK.removeClient(client)); + Assertions.assertNotNull(OctaneSDK.removeClient(client)); } @Test @@ -178,10 +178,10 @@ public void sdkTestF() { OctaneConfiguration oc2 = new OctaneConfigurationIntern(UUID.randomUUID().toString(), "http://localhost", "1002", null, null); OctaneClient clientA = OctaneSDK.addClient(oc1, OctaneSDKNegativeTests.PluginServices.class); OctaneClient clientB = OctaneSDK.addClient(oc2, OctaneSDKNegativeTests.PluginServices.class); - Assert.assertNotNull(clientA); - Assert.assertNotNull(clientB); + Assertions.assertNotNull(clientA); + Assertions.assertNotNull(clientB); - Assert.assertNotNull(OctaneSDK.removeClient(clientB)); + Assertions.assertNotNull(OctaneSDK.removeClient(clientB)); oc2.setUrlAndSpace(oc2.getUrl(), oc1.getSharedSpace()); } diff --git a/integrations-sdk/src/test/java/com/hp/octane/integrations/OctaneSDKTestConfigurationTests.java b/integrations-sdk/src/test/java/com/hp/octane/integrations/OctaneSDKTestConfigurationTests.java index 518b9560..6ac06ba5 100644 --- a/integrations-sdk/src/test/java/com/hp/octane/integrations/OctaneSDKTestConfigurationTests.java +++ b/integrations-sdk/src/test/java/com/hp/octane/integrations/OctaneSDKTestConfigurationTests.java @@ -35,12 +35,14 @@ import com.hp.octane.integrations.dto.general.CIPluginInfo; import com.hp.octane.integrations.dto.general.CIServerInfo; import com.hp.octane.integrations.testhelpers.OctaneSPEndpointSimulator; +import org.apache.http.HttpStatus; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.eclipse.jetty.http.HttpMethod; -import org.junit.Test; +import org.eclipse.jetty.io.Content; +import org.eclipse.jetty.util.Callback; +import org.junit.jupiter.api.Test; -import javax.servlet.http.HttpServletResponse; import java.io.IOException; public class OctaneSDKTestConfigurationTests { @@ -51,22 +53,22 @@ public class OctaneSDKTestConfigurationTests { public void testA1() throws IOException { String spId = "1001"; OctaneSPEndpointSimulator simulator = OctaneSPEndpointSimulator.addInstance(spId); - simulator.installApiHandler(HttpMethod.GET, "^.*/analytics/ci/servers/connectivity/status$", request -> { - request.getResponse().setStatus(HttpServletResponse.SC_OK); + simulator.installApiHandler(HttpMethod.GET, "^.*/analytics/ci/servers/connectivity/status$", (request, response) -> { + response.setStatus(HttpStatus.SC_OK); try { - request.getResponse().getWriter().write("{}"); - request.getResponse().flushBuffer(); - } catch (IOException ioe) { - logger.error("failed to process status request in MOCK server", ioe); + response.getHeaders().put("Content-Type", "application/json"); + Content.Sink.write(response, true, "{}", Callback.NOOP); + } catch (Exception e) { + logger.error("failed to process status request in MOCK server", e); } }); - simulator.installApiHandler(HttpMethod.GET, "^.*/workspaces?.*$", request -> { - request.getResponse().setStatus(HttpServletResponse.SC_OK); + simulator.installApiHandler(HttpMethod.GET, "^.*/workspaces?.*$", (request, response) -> { + response.setStatus(HttpStatus.SC_OK); try { - request.getResponse().getWriter().write("{\"total_count\":1,\"data\":[{\"type\":\"workspace\",\"id\":\"1002\"}],\"exceeds_total_count\":false}"); - request.getResponse().flushBuffer(); - } catch (IOException ioe) { - logger.error("failed to process status request in MOCK server", ioe); + response.getHeaders().put("Content-Type", "application/json"); + Content.Sink.write(response, true, "{\"total_count\":1,\"data\":[{\"type\":\"workspace\",\"id\":\"1002\"}],\"exceeds_total_count\":false}", Callback.NOOP); + } catch (Exception e) { + logger.error("failed to process status request in MOCK server", e); } }); @@ -85,4 +87,4 @@ public CIPluginInfo getPluginInfo() { return dtoFactory.newDTO(CIPluginInfo.class); } } -} +} \ No newline at end of file diff --git a/integrations-sdk/src/test/java/com/hp/octane/integrations/dto/StatusInfoTest.java b/integrations-sdk/src/test/java/com/hp/octane/integrations/dto/StatusInfoTest.java index 12360f59..dc223ccf 100644 --- a/integrations-sdk/src/test/java/com/hp/octane/integrations/dto/StatusInfoTest.java +++ b/integrations-sdk/src/test/java/com/hp/octane/integrations/dto/StatusInfoTest.java @@ -33,14 +33,14 @@ import com.hp.octane.integrations.dto.general.CIProviderSummaryInfo; import com.hp.octane.integrations.dto.general.CIServerTypes; +import org.junit.jupiter.api.Test; import com.hp.octane.integrations.dto.general.CIPluginInfo; import com.hp.octane.integrations.dto.general.CIServerInfo; -import org.junit.Test; import java.util.UUID; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; /** * Status Info tests. diff --git a/integrations-sdk/src/test/java/com/hp/octane/integrations/end2end/basic/OctaneSDKBasicFunctionalityTest.java b/integrations-sdk/src/test/java/com/hp/octane/integrations/end2end/basic/OctaneSDKBasicFunctionalityTest.java index 1592b562..bc6d9649 100644 --- a/integrations-sdk/src/test/java/com/hp/octane/integrations/end2end/basic/OctaneSDKBasicFunctionalityTest.java +++ b/integrations-sdk/src/test/java/com/hp/octane/integrations/end2end/basic/OctaneSDKBasicFunctionalityTest.java @@ -54,16 +54,16 @@ import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.eclipse.jetty.http.HttpMethod; -import org.junit.Assert; -import org.junit.Test; +import org.eclipse.jetty.server.Request; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; -import javax.servlet.http.HttpServletResponse; -import java.io.IOException; import java.util.*; import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import java.util.stream.Stream; -import java.util.zip.GZIPInputStream; /** * Octane SDK functional sanity test @@ -76,8 +76,9 @@ public class OctaneSDKBasicFunctionalityTest { private static final Logger logger = LogManager.getLogger(OctaneSDKBasicFunctionalityTest.class); private static DTOFactory dtoFactory = DTOFactory.getInstance(); - @Test(timeout = 600000) - public void testE2EFunctional() throws ExecutionException, InterruptedException { + @Test + @Timeout(value = 600000, unit = TimeUnit.MILLISECONDS) + public void testE2EFunctional() throws ExecutionException, InterruptedException { Map simulators = null; Map> eventsCollectors = new LinkedHashMap<>(); Map> testResultsCollectors = new LinkedHashMap<>(); @@ -125,12 +126,12 @@ public void testE2EFunctional() throws ExecutionException, InterruptedException GeneralTestUtils.waitAtMostFor(10000, () -> { if (eventsCollectors.containsKey(spIdA) && eventsCollectors.get(spIdA).stream().mapToInt(cil -> cil.getEvents().size()).sum() == 3) { eventsCollectors.get(spIdA).forEach(cil -> { - Assert.assertNotNull(cil); - Assert.assertNotNull(cil.getServer()); - Assert.assertEquals(clientAInstanceId, cil.getServer().getInstanceId()); - Assert.assertEquals("custom", cil.getServer().getType()); - Assert.assertEquals("1.1.1", cil.getServer().getVersion()); - Assert.assertEquals("http://localhost:9999", cil.getServer().getUrl()); + Assertions.assertNotNull(cil); + Assertions.assertNotNull(cil.getServer()); + Assertions.assertEquals(clientAInstanceId, cil.getServer().getInstanceId()); + Assertions.assertEquals("custom", cil.getServer().getType()); + Assertions.assertEquals("1.1.1", cil.getServer().getVersion()); + Assertions.assertEquals("http://localhost:9999", cil.getServer().getUrl()); }); // TODO: add deeper verification return true; @@ -200,22 +201,22 @@ public void testE2EFunctional() throws ExecutionException, InterruptedException eventsCollectors.containsKey(spIdB) && eventsCollectors.get(spIdA).stream().mapToInt(cil -> cil.getEvents().size()).sum() == 3) { // client A eventsCollectors.get(spIdA).forEach(cil -> { - Assert.assertNotNull(cil); - Assert.assertNotNull(cil.getServer()); - Assert.assertEquals(clientAInstanceId, cil.getServer().getInstanceId()); - Assert.assertEquals("custom", cil.getServer().getType()); - Assert.assertEquals("1.1.1", cil.getServer().getVersion()); - Assert.assertEquals("http://localhost:9999", cil.getServer().getUrl()); + Assertions.assertNotNull(cil); + Assertions.assertNotNull(cil.getServer()); + Assertions.assertEquals(clientAInstanceId, cil.getServer().getInstanceId()); + Assertions.assertEquals("custom", cil.getServer().getType()); + Assertions.assertEquals("1.1.1", cil.getServer().getVersion()); + Assertions.assertEquals("http://localhost:9999", cil.getServer().getUrl()); }); // client B eventsCollectors.get(spIdB).forEach(cil -> { - Assert.assertNotNull(cil); - Assert.assertNotNull(cil.getServer()); - Assert.assertEquals(clientBInstanceId, cil.getServer().getInstanceId()); - Assert.assertEquals("custom", cil.getServer().getType()); - Assert.assertEquals("1.1.1", cil.getServer().getVersion()); - Assert.assertEquals("http://localhost:9999", cil.getServer().getUrl()); + Assertions.assertNotNull(cil); + Assertions.assertNotNull(cil.getServer()); + Assertions.assertEquals(clientBInstanceId, cil.getServer().getInstanceId()); + Assertions.assertEquals("custom", cil.getServer().getType()); + Assertions.assertEquals("1.1.1", cil.getServer().getVersion()); + Assertions.assertEquals("http://localhost:9999", cil.getServer().getUrl()); }); // TODO: add deeper verification @@ -280,14 +281,14 @@ public void testE2EFunctional() throws ExecutionException, InterruptedException // validate events GeneralTestUtils.waitAtMostFor(10000, () -> { if (eventsCollectors.containsKey(spIdB) && eventsCollectors.get(spIdB).stream().mapToInt(cil -> cil.getEvents().size()).sum() == 3) { - Assert.assertTrue(eventsCollectors.get(spIdA).isEmpty()); + Assertions.assertTrue(eventsCollectors.get(spIdA).isEmpty()); eventsCollectors.get(spIdB).forEach(cil -> { - Assert.assertNotNull(cil); - Assert.assertNotNull(cil.getServer()); - Assert.assertEquals(clientBInstanceId, cil.getServer().getInstanceId()); - Assert.assertEquals("custom", cil.getServer().getType()); - Assert.assertEquals("1.1.1", cil.getServer().getVersion()); - Assert.assertEquals("http://localhost:9999", cil.getServer().getUrl()); + Assertions.assertNotNull(cil); + Assertions.assertNotNull(cil.getServer()); + Assertions.assertEquals(clientBInstanceId, cil.getServer().getInstanceId()); + Assertions.assertEquals("custom", cil.getServer().getType()); + Assertions.assertEquals("1.1.1", cil.getServer().getVersion()); + Assertions.assertEquals("http://localhost:9999", cil.getServer().getUrl()); }); // TODO: add deeper verification return true; @@ -299,7 +300,7 @@ public void testE2EFunctional() throws ExecutionException, InterruptedException // validate tests GeneralTestUtils.waitAtMostFor(10000, () -> { if (testResultsCollectors.containsKey(spIdB) && testResultsCollectors.get(spIdB).size() == 1) { - Assert.assertTrue(testResultsCollectors.get(spIdA).isEmpty()); + Assertions.assertTrue(testResultsCollectors.get(spIdA).isEmpty()); // TODO: add deeper verification return true; } else { @@ -310,7 +311,7 @@ public void testE2EFunctional() throws ExecutionException, InterruptedException // validate logs GeneralTestUtils.waitAtMostFor(10000, () -> { if (logsCollectors.containsKey(spIdB) && logsCollectors.get(spIdB).size() == 1) { - Assert.assertTrue(logsCollectors.get(spIdA).isEmpty()); + Assertions.assertTrue(logsCollectors.get(spIdA).isEmpty()); // TODO: add deeper verification return true; } else { @@ -321,7 +322,7 @@ public void testE2EFunctional() throws ExecutionException, InterruptedException // validate coverages GeneralTestUtils.waitAtMostFor(10000, () -> { if (coverageCollectors.containsKey(spIdB) && coverageCollectors.get(spIdB).size() == 2) { - Assert.assertTrue(coverageCollectors.get(spIdA).isEmpty()); + Assertions.assertTrue(coverageCollectors.get(spIdA).isEmpty()); // TODO: add deeper verification return true; } else { @@ -348,14 +349,14 @@ public void testE2EFunctional() throws ExecutionException, InterruptedException CIPluginSDKUtils.doWait(4000); - Assert.assertTrue(eventsCollectors.get(spIdA).isEmpty()); - Assert.assertTrue(eventsCollectors.get(spIdB).isEmpty()); - Assert.assertTrue(testResultsCollectors.get(spIdA).isEmpty()); - Assert.assertTrue(testResultsCollectors.get(spIdB).isEmpty()); - Assert.assertTrue(logsCollectors.get(spIdA).isEmpty()); - Assert.assertTrue(logsCollectors.get(spIdB).isEmpty()); - Assert.assertTrue(coverageCollectors.get(spIdA).isEmpty()); - Assert.assertTrue(coverageCollectors.get(spIdB).isEmpty()); + Assertions.assertTrue(eventsCollectors.get(spIdA).isEmpty()); + Assertions.assertTrue(eventsCollectors.get(spIdB).isEmpty()); + Assertions.assertTrue(testResultsCollectors.get(spIdA).isEmpty()); + Assertions.assertTrue(testResultsCollectors.get(spIdB).isEmpty()); + Assertions.assertTrue(logsCollectors.get(spIdA).isEmpty()); + Assertions.assertTrue(logsCollectors.get(spIdB).isEmpty()); + Assertions.assertTrue(coverageCollectors.get(spIdA).isEmpty()); + Assertions.assertTrue(coverageCollectors.get(spIdB).isEmpty()); // // V @@ -380,14 +381,14 @@ public void testE2EFunctional() throws ExecutionException, InterruptedException CIPluginSDKUtils.doWait(4000); - Assert.assertTrue(eventsCollectors.get(spIdA).isEmpty()); - Assert.assertTrue(eventsCollectors.get(spIdB).isEmpty()); - Assert.assertTrue(testResultsCollectors.get(spIdA).isEmpty()); - Assert.assertTrue(testResultsCollectors.get(spIdB).isEmpty()); - Assert.assertTrue(logsCollectors.get(spIdA).isEmpty()); - Assert.assertTrue(logsCollectors.get(spIdB).isEmpty()); - Assert.assertTrue(coverageCollectors.get(spIdA).isEmpty()); - Assert.assertTrue(coverageCollectors.get(spIdB).isEmpty()); + Assertions.assertTrue(eventsCollectors.get(spIdA).isEmpty()); + Assertions.assertTrue(eventsCollectors.get(spIdB).isEmpty()); + Assertions.assertTrue(testResultsCollectors.get(spIdA).isEmpty()); + Assertions.assertTrue(testResultsCollectors.get(spIdB).isEmpty()); + Assertions.assertTrue(logsCollectors.get(spIdA).isEmpty()); + Assertions.assertTrue(logsCollectors.get(spIdB).isEmpty()); + Assertions.assertTrue(coverageCollectors.get(spIdA).isEmpty()); + Assertions.assertTrue(coverageCollectors.get(spIdB).isEmpty()); OctaneSDK.removeClient(clientA); // @@ -414,14 +415,14 @@ public void testE2EFunctional() throws ExecutionException, InterruptedException CIPluginSDKUtils.doWait(4000); - Assert.assertTrue(eventsCollectors.get(spIdA).isEmpty()); - Assert.assertTrue(eventsCollectors.get(spIdB).isEmpty()); - Assert.assertTrue(testResultsCollectors.get(spIdA).isEmpty()); - Assert.assertTrue(testResultsCollectors.get(spIdB).isEmpty()); - Assert.assertTrue(logsCollectors.get(spIdA).isEmpty()); - Assert.assertTrue(logsCollectors.get(spIdB).isEmpty()); - Assert.assertTrue(coverageCollectors.get(spIdA).isEmpty()); - Assert.assertTrue(coverageCollectors.get(spIdB).isEmpty()); + Assertions.assertTrue(eventsCollectors.get(spIdA).isEmpty()); + Assertions.assertTrue(eventsCollectors.get(spIdB).isEmpty()); + Assertions.assertTrue(testResultsCollectors.get(spIdA).isEmpty()); + Assertions.assertTrue(testResultsCollectors.get(spIdB).isEmpty()); + Assertions.assertTrue(logsCollectors.get(spIdA).isEmpty()); + Assertions.assertTrue(logsCollectors.get(spIdB).isEmpty()); + Assertions.assertTrue(coverageCollectors.get(spIdA).isEmpty()); + Assertions.assertTrue(coverageCollectors.get(spIdB).isEmpty()); // @@ -442,12 +443,12 @@ public void testE2EFunctional() throws ExecutionException, InterruptedException GeneralTestUtils.waitAtMostFor(5000, () -> { if (eventsCollectors.containsKey(spIdA) && eventsCollectors.get(spIdA).stream().mapToInt(cil -> cil.getEvents().size()).sum() == 3) { eventsCollectors.get(spIdA).forEach(cil -> { - Assert.assertNotNull(cil); - Assert.assertNotNull(cil.getServer()); - Assert.assertEquals(clientAInstanceId, cil.getServer().getInstanceId()); - Assert.assertEquals("custom", cil.getServer().getType()); - Assert.assertEquals("1.1.1", cil.getServer().getVersion()); - Assert.assertEquals("http://localhost:9999", cil.getServer().getUrl()); + Assertions.assertNotNull(cil); + Assertions.assertNotNull(cil.getServer()); + Assertions.assertEquals(clientAInstanceId, cil.getServer().getInstanceId()); + Assertions.assertEquals("custom", cil.getServer().getType()); + Assertions.assertEquals("1.1.1", cil.getServer().getVersion()); + Assertions.assertEquals("http://localhost:9999", cil.getServer().getUrl()); }); // TODO: add deeper verification return true; @@ -507,73 +508,75 @@ private Map initSPEPSimulators( OctaneSPEndpointSimulator simulator = OctaneSPEndpointSimulator.addInstance(spID); simulator.setOctaneVersion("15.1.8");//for octane roots // events API - simulator.installApiHandler(HttpMethod.PUT, "^.*events$", request -> { + simulator.installApiHandler(HttpMethod.PUT, "^.*events$", (request, response) -> { try { - String rawEventsBody = CIPluginSDKUtils.inputStreamToUTF8String(new GZIPInputStream(request.getInputStream())); + String rawEventsBody = OctaneSPEndpointSimulator.readRequestBody(request); CIEventsList eventsList = dtoFactory.dtoFromJson(rawEventsBody, CIEventsList.class); eventsCollectors .computeIfAbsent(spID, sp -> new LinkedList<>()) .add(eventsList); - request.getResponse().setStatus(HttpStatus.SC_OK); - } catch (IOException ioe) { + response.setStatus(HttpStatus.SC_OK); + } catch (Exception ioe) { throw new RuntimeException(ioe); } }); // test results preflight API - simulator.installApiHandler(HttpMethod.GET, "^.*tests-result-preflight$", request -> { + simulator.installApiHandler(HttpMethod.GET, "^.*tests-result-preflight$", (request, response) -> { try { - request.getResponse().setStatus(HttpStatus.SC_OK); - request.getResponse().getWriter().write("true"); - request.getResponse().getWriter().flush(); - } catch (IOException ioe) { - throw new RuntimeException(ioe); + response.setStatus(HttpStatus.SC_OK); + response.getHeaders().put("Content-Type", "text/plain"); + OctaneSPEndpointSimulator.writeResponseBody(response, "true"); + } catch (Exception e) { + throw new RuntimeException(e); } }); // test results push API - simulator.installApiHandler(HttpMethod.POST, "^.*test-results$", request -> { + simulator.installApiHandler(HttpMethod.POST, "^.*test-results$", (request, response) -> { try { - String rawTestResultBody = CIPluginSDKUtils.inputStreamToUTF8String(new GZIPInputStream(request.getInputStream())); + String rawTestResultBody = OctaneSPEndpointSimulator.readRequestBody(request); TestsResult testsResult = dtoFactory.dtoFromXml(rawTestResultBody, TestsResult.class); // [YG] below validations are done to ensure NEW API (via query params) aligned with an OLD API (data within XML) // [YG] in the future we'll remove OLD API and this validation should be done differently - request.mergeQueryParameters("", request.getQueryString()); - Assert.assertEquals(request.getQueryParameters().getString("instance-id"), testsResult.getBuildContext().getServerId()); - Assert.assertTrue(request.getQueryParameters().getString("job-ci-id").equals(CIPluginSDKUtils.urlEncodeBase64(testsResult.getBuildContext().getJobId())) || - request.getQueryParameters().getString("job-ci-id").equals(testsResult.getBuildContext().getJobId())); - Assert.assertEquals(request.getQueryParameters().getString("build-ci-id"), testsResult.getBuildContext().getBuildId()); + String instanceId = Request.getParameters(request).getValue("instance-id"); + String jobCiId = Request.getParameters(request).getValue("job-ci-id"); + String buildCiId = Request.getParameters(request).getValue("build-ci-id"); + Assertions.assertEquals(instanceId, testsResult.getBuildContext().getServerId()); + Assertions.assertTrue(jobCiId.equals(CIPluginSDKUtils.urlEncodeBase64(testsResult.getBuildContext().getJobId())) || + jobCiId.equals(testsResult.getBuildContext().getJobId())); + Assertions.assertEquals(buildCiId, testsResult.getBuildContext().getBuildId()); testResultsCollectors .computeIfAbsent(spID, sp -> new LinkedList<>()) .add(testsResult); - request.getResponse().setStatus(HttpStatus.SC_ACCEPTED); - request.getResponse().getWriter().write("{\"status\": \"queued\"}"); - request.getResponse().getWriter().flush(); - } catch (IOException ioe) { - throw new RuntimeException(ioe); + response.setStatus(HttpStatus.SC_ACCEPTED); + response.getHeaders().put("Content-Type", "application/json"); + OctaneSPEndpointSimulator.writeResponseBody(response, "{\"status\": \"queued\"}"); + } catch (Exception e) { + throw new RuntimeException(e); } }); // logs/coverage preflight API - simulator.installApiHandler(HttpMethod.GET, "^.*workspaceId$", request -> { + simulator.installApiHandler(HttpMethod.GET, "^.*workspaceId$", (request, response) -> { try { - request.getResponse().setStatus(HttpStatus.SC_OK); - request.getResponse().getWriter().write("[\"1001\"]"); - request.getResponse().getWriter().flush(); - } catch (IOException ioe) { - throw new RuntimeException(ioe); + response.setStatus(HttpStatus.SC_OK); + response.getHeaders().put("Content-Type", "application/json"); + OctaneSPEndpointSimulator.writeResponseBody(response, "[\"1001\"]"); + } catch (Exception e) { + throw new RuntimeException(e); } }); // logs push API - simulator.installApiHandler(HttpMethod.POST, "^.*logs$", request -> { + simulator.installApiHandler(HttpMethod.POST, "^.*logs$", (request, response) -> { try { - String rawLogBody = CIPluginSDKUtils.inputStreamToUTF8String(new GZIPInputStream(request.getInputStream())); + String rawLogBody = OctaneSPEndpointSimulator.readRequestBody(request); logsCollectors .computeIfAbsent(spID, sp -> new LinkedList<>()) .add(rawLogBody); - request.getResponse().setStatus(HttpStatus.SC_OK); - } catch (IOException ioe) { + response.setStatus(HttpStatus.SC_OK); + } catch (Exception ioe) { throw new RuntimeException(ioe); } }); @@ -582,26 +585,26 @@ private Map initSPEPSimulators( // no need to configure, since it's the same API as for logs, see above // coverage push API - simulator.installApiHandler(HttpMethod.PUT, "^.*coverage$", request -> { + simulator.installApiHandler(HttpMethod.PUT, "^.*coverage$", (request, response) -> { try { - String rawCoverageBody = CIPluginSDKUtils.inputStreamToUTF8String(new GZIPInputStream(request.getInputStream())); + String rawCoverageBody = OctaneSPEndpointSimulator.readRequestBody(request); coverageCollectors .computeIfAbsent(spID, sp -> new LinkedList<>()) .add(rawCoverageBody); - request.getResponse().setStatus(HttpStatus.SC_OK); - } catch (IOException ioe) { + response.setStatus(HttpStatus.SC_OK); + } catch (Exception ioe) { throw new RuntimeException(ioe); } }); // get roots - simulator.installApiHandler(HttpMethod.GET, "^.*pipeline-roots$", request -> { + simulator.installApiHandler(HttpMethod.GET, "^.*pipeline-roots$", (request, response) -> { try { - request.getResponse().setStatus(HttpStatus.SC_OK); - request.getResponse().getWriter().write("[]"); - request.getResponse().getWriter().flush(); - } catch (IOException ioe) { - throw new RuntimeException(ioe); + response.setStatus(HttpStatus.SC_OK); + response.getHeaders().put("Content-Type", "application/json"); + OctaneSPEndpointSimulator.writeResponseBody(response, "[]"); + } catch (Exception e) { + throw new RuntimeException(e); } }); @@ -671,3 +674,4 @@ private void removeSPEPSimulators(Collection simulato } } } + diff --git a/integrations-sdk/src/test/java/com/hp/octane/integrations/executor/CustomConverterTest.java b/integrations-sdk/src/test/java/com/hp/octane/integrations/executor/CustomConverterTest.java index ab7acdfa..5bf4d0d8 100644 --- a/integrations-sdk/src/test/java/com/hp/octane/integrations/executor/CustomConverterTest.java +++ b/integrations-sdk/src/test/java/com/hp/octane/integrations/executor/CustomConverterTest.java @@ -35,8 +35,8 @@ import com.hp.octane.integrations.executor.converters.CustomConverter; import com.hp.octane.integrations.executor.converters.GradleConverter; import com.hp.octane.integrations.executor.converters.ProtractorConverter; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; /** * Octane SDK tests @@ -59,7 +59,7 @@ public void mavenConverterTest() { CustomConverter converter = new CustomConverter(buildCustomFormat("$package.$class#$testName", ",")); String actual = converter.convert(fullFormatRawData, "", null).getConvertedTestsString(); - Assert.assertEquals("MF.simple.tests.AppTest#testAlwaysFail,MF.simple.tests.App2Test#testSendGet", actual); + Assertions.assertEquals("MF.simple.tests.AppTest#testAlwaysFail,MF.simple.tests.App2Test#testSendGet", actual); } @Test @@ -67,7 +67,7 @@ public void protractorConverterMultipleCaseTest() { ProtractorConverter protractorConverter = new ProtractorConverter(); String actual = protractorConverter.convert(fullFormatRawData, "", null).getConvertedTestsString(); - Assert.assertEquals("AppTest testAlwaysFail|App2Test testSendGet", actual); + Assertions.assertEquals("AppTest testAlwaysFail|App2Test testSendGet", actual); } @Test @@ -75,7 +75,7 @@ public void protractorConverterMultipleCaseNoPackageTest() { ProtractorConverter protractorConverter = new ProtractorConverter(); String actual = protractorConverter.convert(noPackageRawData, "", null).getConvertedTestsString(); - Assert.assertEquals("AppTest testAlwaysFail|App2Test testSendGet", actual); + Assertions.assertEquals("AppTest testAlwaysFail|App2Test testSendGet", actual); } @Test @@ -83,7 +83,7 @@ public void protractorSetFormatIsIgnored() { ProtractorConverter protractorConverter = new ProtractorConverter(); String actual = protractorConverter.setFormat("{\"testPattern\":\"bubub\",\"testDelimiter\":\"---\"}").convert(fullFormatRawData, "", null).getConvertedTestsString(); - Assert.assertEquals("AppTest testAlwaysFail|App2Test testSendGet", actual); + Assertions.assertEquals("AppTest testAlwaysFail|App2Test testSendGet", actual); } @Test @@ -91,7 +91,7 @@ public void protractorConverterSingleCaseTest() { ProtractorConverter protractorConverter = new ProtractorConverter(); String actual = protractorConverter.convert(singleRawData, "", null).getConvertedTestsString(); - Assert.assertEquals("AppTest testAlwaysFail", actual); + Assertions.assertEquals("AppTest testAlwaysFail", actual); } @Test @@ -99,7 +99,7 @@ public void gradleConverterMultipleCaseTest() { GradleConverter gradleConverter = new GradleConverter(); String actual = gradleConverter.convert(fullFormatRawData, "", null).getConvertedTestsString(); - Assert.assertEquals(" --tests MF.simple.tests.AppTest.testAlwaysFail --tests MF.simple.tests.App2Test.testSendGet", actual); + Assertions.assertEquals(" --tests MF.simple.tests.AppTest.testAlwaysFail --tests MF.simple.tests.App2Test.testSendGet", actual); } @Test @@ -107,7 +107,7 @@ public void gradleConverterMultipleCaseNoPackageTest() { GradleConverter gradleConverter = new GradleConverter(); String actual = gradleConverter.convert(noPackageRawData, "", null).getConvertedTestsString(); - Assert.assertEquals(" --tests AppTest.testAlwaysFail --tests App2Test.testSendGet", actual); + Assertions.assertEquals(" --tests AppTest.testAlwaysFail --tests App2Test.testSendGet", actual); } @Test @@ -115,7 +115,7 @@ public void gradleConverteMultipleCaseNoClassTest() { GradleConverter gradleConverter = new GradleConverter(); String actual = gradleConverter.convert(noClassRawData, "", null).getConvertedTestsString(); - Assert.assertEquals(" --tests testAlwaysFail --tests testSendGet", actual); + Assertions.assertEquals(" --tests testAlwaysFail --tests testSendGet", actual); } @Test @@ -123,7 +123,7 @@ public void gradleConverteSingleCaseTest() { GradleConverter gradleConverter = new GradleConverter(); String actual = gradleConverter.convert(singleRawData, "", null).getConvertedTestsString(); - Assert.assertEquals(" --tests MF.simple.tests.AppTest.testAlwaysFail", actual); + Assertions.assertEquals(" --tests MF.simple.tests.AppTest.testAlwaysFail", actual); } @Test @@ -132,6 +132,6 @@ public void bddTest() { BDDConverter converter = new BDDConverter(); String actual = converter.convert(data, "", null).getConvertedTestsString(); String expected = "'src\\test\\resources\\dan\\Dan_1021.feature' 'src\\test\\resources\\elisheva\\ES_1024 a.feature' --name '^feature name 1021$' --name '^feature name .1024 #1024 bbb$'"; - Assert.assertEquals(expected, actual); + Assertions.assertEquals(expected, actual); } } diff --git a/integrations-sdk/src/test/java/com/hp/octane/integrations/executor/CustomConverterWithJsonTest.java b/integrations-sdk/src/test/java/com/hp/octane/integrations/executor/CustomConverterWithJsonTest.java index cde3aecf..ae43c0d5 100644 --- a/integrations-sdk/src/test/java/com/hp/octane/integrations/executor/CustomConverterWithJsonTest.java +++ b/integrations-sdk/src/test/java/com/hp/octane/integrations/executor/CustomConverterWithJsonTest.java @@ -32,8 +32,8 @@ package com.hp.octane.integrations.executor; import com.hp.octane.integrations.executor.converters.CustomConverter; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; /** * Octane SDK tests @@ -62,8 +62,8 @@ public void jsonConverterTest() { CustomConverter converter = new CustomConverter(json); TestsToRunConverterResult result = converter.convert(fullFormatRawData, "", null); - Assert.assertEquals("converted", result.getTestsToRunConvertedParameterName()); - Assert.assertEquals("[MF.simple.tests.AppTest#myTest||MF.simple.tests.AppTestB#test\\040Send]", result.getConvertedTestsString()); + Assertions.assertEquals("converted", result.getTestsToRunConvertedParameterName()); + Assertions.assertEquals("[MF.simple.tests.AppTest#myTest||MF.simple.tests.AppTestB#test\\040Send]", result.getConvertedTestsString()); } @Test @@ -77,9 +77,9 @@ public void wrongTypeInMultipleTypesTest() { try { CustomConverter converter = new CustomConverter(json); - Assert.fail("Exception must have been thrown, but it not."); + Assertions.fail("Exception must have been thrown, but it not."); } catch (IllegalArgumentException e) { - Assert.assertEquals("Illegal target 'class' in replacement 'replaceString'. Target values must start with '$', for example $class.", e.getMessage()); + Assertions.assertEquals("Illegal target 'class' in replacement 'replaceString'. Target values must start with '$', for example $class.", e.getMessage()); } } @@ -95,7 +95,7 @@ public void replaceStringInMultipleTypesTest() { CustomConverter converter = new CustomConverter(json); String actual = converter.convert(fullFormatRawData, "", null).getConvertedTestsString(); - Assert.assertEquals("MFA.simpleA.bubus.AppTestA#myTestA+MFA.simpleA.bubus.AppTestB#bubu Send", actual); + Assertions.assertEquals("MFA.simpleA.bubus.AppTestA#myTestA+MFA.simpleA.bubus.AppTestB#bubu Send", actual); } @Test @@ -111,7 +111,7 @@ public void replaceToUpperCaseAndToLowerCaseTest() { CustomConverter converter = new CustomConverter(json); String actual = converter.convert(fullFormatRawData, "", null).getConvertedTestsString(); - Assert.assertEquals("MFA.simpleA.tests=apptesta#MYTESTA+MFA.simpleA.tests=apptestb#TEST SEND", actual); + Assertions.assertEquals("MFA.simpleA.tests=apptesta#MYTESTA+MFA.simpleA.tests=apptestb#TEST SEND", actual); } @Test @@ -125,7 +125,7 @@ public void joinStringWithDuplicationTest() { CustomConverter converter = new CustomConverter(json); String actual = converter.convert(fullFormatRawData, "", null).getConvertedTestsString(); - Assert.assertEquals("prefix|MFA.simpleA.tests|suffix;prefix|MFA.simpleA.tests|suffix;", actual); + Assertions.assertEquals("prefix|MFA.simpleA.tests|suffix;prefix|MFA.simpleA.tests|suffix;", actual); } @Test @@ -140,7 +140,7 @@ public void joinStringWithoutDuplicationTest() { CustomConverter converter = new CustomConverter(json); String actual = converter.convert(fullFormatRawData, "", null).getConvertedTestsString(); - Assert.assertEquals("prefix|MFA.simpleA.tests|suffix;", actual); + Assertions.assertEquals("prefix|MFA.simpleA.tests|suffix;", actual); } @Test @@ -154,11 +154,11 @@ public void booleanAsStringTest() { try { CustomConverter converter = new CustomConverter(json); - Assert.fail("Fail is expected"); + Assertions.fail("Fail is expected"); }catch (IllegalArgumentException e){ - Assert.assertEquals("Illegal value for field allowDuplication. Expected boolean value.", e.getMessage()); + Assertions.assertEquals("Illegal value for field allowDuplication. Expected boolean value.", e.getMessage()); }catch (Exception e1){ - Assert.fail("Wrong exception is received"); + Assertions.fail("Wrong exception is received"); } } @@ -174,7 +174,7 @@ public void replaceRegexIgnoreCaseInMultipleTypesTest() { CustomConverter converter = new CustomConverter(json); String actual = converter.convert(fullFormatRawData, "", null).getConvertedTestsString(); - Assert.assertEquals("MFA.simpleA.bubus.AppbubuA#mybubuA+MFA.simpleA.bubus.AppbubuB#bubu Send", actual); + Assertions.assertEquals("MFA.simpleA.bubus.AppbubuA#mybubuA+MFA.simpleA.bubus.AppbubuB#bubu Send", actual); } @Test @@ -190,7 +190,7 @@ public void convertExternalTestId() { CustomConverter converter = new CustomConverter(json); String actual = converter.convert(singleRawDataWithExternalTest, "", null).getConvertedTestsString(); - Assert.assertEquals("MF.simple.tests.AppTest#testAlways-BUBU", actual); + Assertions.assertEquals("MF.simple.tests.AppTest#testAlways-BUBU", actual); } @Test @@ -207,7 +207,7 @@ public void convertExternalTestIdAndClearMissingValue() { CustomConverter converter = new CustomConverter(json); String actual = converter.convert(singleRawDataWithExternalTest, "", null).getConvertedTestsString(); - Assert.assertEquals("MF.simple.tests.AppTest#testAlways-BUBU+MF.simple.tests.AppTest#testNotAlways", actual); + Assertions.assertEquals("MF.simple.tests.AppTest#testAlways-BUBU+MF.simple.tests.AppTest#testNotAlways", actual); } @Test @@ -216,9 +216,9 @@ public void missingTestPatternTest() { "\"testDelimiter\": \"||\"}"; try { CustomConverter converter = new CustomConverter(json); - Assert.fail("Exception must have been thrown, but it not."); + Assertions.fail("Exception must have been thrown, but it not."); } catch (IllegalArgumentException e) { - Assert.assertEquals("Field 'testPattern' is missing in format json", e.getMessage()); + Assertions.assertEquals("Field 'testPattern' is missing in format json", e.getMessage()); } } @@ -231,9 +231,9 @@ public void illegalReplaceActionTypeTest() { "]}"; try { CustomConverter converter = new CustomConverter(json); - Assert.fail("Exception must have been thrown, but it not."); + Assertions.fail("Exception must have been thrown, but it not."); } catch (IllegalArgumentException e) { - Assert.assertEquals("Unknown replacement type 'notExist'", e.getMessage()); + Assertions.assertEquals("Unknown replacement type 'notExist'", e.getMessage()); } } @@ -246,9 +246,9 @@ public void illegalTargetInReplacementTest() { "]}"; try { CustomConverter converter = new CustomConverter(json); - Assert.fail("Exception must have been thrown, but it not."); + Assertions.fail("Exception must have been thrown, but it not."); } catch (IllegalArgumentException e) { - Assert.assertEquals("Illegal target 'package' in replacement 'replaceRegex'. Target values must start with '$', for example $package.", e.getMessage()); + Assertions.assertEquals("Illegal target 'package' in replacement 'replaceRegex'. Target values must start with '$', for example $package.", e.getMessage()); } } @@ -261,9 +261,9 @@ public void missingRegexFieldInReplaceRegexTest() { "]}"; try { CustomConverter converter = new CustomConverter(json); - Assert.fail("Exception must have been thrown, but it not."); + Assertions.fail("Exception must have been thrown, but it not."); } catch (IllegalArgumentException e) { - Assert.assertEquals("The replacement 'replaceRegex' is missing field 'regex'", e.getMessage()); + Assertions.assertEquals("The replacement 'replaceRegex' is missing field 'regex'", e.getMessage()); } } @@ -276,9 +276,9 @@ public void missingReplacementFieldInReplaceRegexTest() { "]}"; try { CustomConverter converter = new CustomConverter(json); - Assert.fail("Exception must have been thrown, but it not."); + Assertions.fail("Exception must have been thrown, but it not."); } catch (IllegalArgumentException e) { - Assert.assertEquals("The replacement 'replaceRegex' is missing field 'replacement'", e.getMessage()); + Assertions.assertEquals("The replacement 'replaceRegex' is missing field 'replacement'", e.getMessage()); } } diff --git a/integrations-sdk/src/test/java/com/hp/octane/integrations/executor/TestsToRunConverterTest.java b/integrations-sdk/src/test/java/com/hp/octane/integrations/executor/TestsToRunConverterTest.java index ddecc611..171a6f6d 100644 --- a/integrations-sdk/src/test/java/com/hp/octane/integrations/executor/TestsToRunConverterTest.java +++ b/integrations-sdk/src/test/java/com/hp/octane/integrations/executor/TestsToRunConverterTest.java @@ -31,8 +31,8 @@ */ package com.hp.octane.integrations.executor; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import static com.hp.octane.integrations.executor.TestsToRunFramework.JUnit4; import static com.hp.octane.integrations.executor.TestsToRunFramework.MF_UFT; @@ -83,28 +83,28 @@ private String converterTest(TestsToRunFramework framework, String rawData) { public void customConverterJsonTest() { String actual = converterTest(JUnit4, v2MavenFormatRawData); - Assert.assertEquals(outputMavenResult, actual); + Assertions.assertEquals(outputMavenResult, actual); } @Test public void customConverterStringTest() { String actual = converterTest(JUnit4, v1MavenFormatRawData); - Assert.assertEquals(outputMavenResult, actual); + Assertions.assertEquals(outputMavenResult, actual); } @Test public void uftConverterJsonTest() { String actual = converterTest(MF_UFT, v2UFTFormatRawData); - Assert.assertEquals(outputUFTResult, actual); + Assertions.assertEquals(outputUFTResult, actual); } @Test public void uftConverterStringTest() { String actual = converterTest(MF_UFT, v1UFTFormatRawData); - Assert.assertEquals(outputUFTResult, actual); + Assertions.assertEquals(outputUFTResult, actual); } } diff --git a/integrations-sdk/src/test/java/com/hp/octane/integrations/exported/tests/SPIProvisioningTest.java b/integrations-sdk/src/test/java/com/hp/octane/integrations/exported/tests/SPIProvisioningTest.java index 65d78b2d..999e92a1 100644 --- a/integrations-sdk/src/test/java/com/hp/octane/integrations/exported/tests/SPIProvisioningTest.java +++ b/integrations-sdk/src/test/java/com/hp/octane/integrations/exported/tests/SPIProvisioningTest.java @@ -31,7 +31,7 @@ */ package com.hp.octane.integrations.exported.tests; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * SPI Provisioning tests. diff --git a/integrations-sdk/src/test/java/com/hp/octane/integrations/services/bridge/BridgeServiceNegativeTests.java b/integrations-sdk/src/test/java/com/hp/octane/integrations/services/bridge/BridgeServiceNegativeTests.java index 37293131..7793e5d5 100644 --- a/integrations-sdk/src/test/java/com/hp/octane/integrations/services/bridge/BridgeServiceNegativeTests.java +++ b/integrations-sdk/src/test/java/com/hp/octane/integrations/services/bridge/BridgeServiceNegativeTests.java @@ -32,27 +32,35 @@ package com.hp.octane.integrations.services.bridge; import com.hp.octane.integrations.OctaneSDK; -import org.junit.Test; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertThrows; public class BridgeServiceNegativeTests { - @Test(expected = IllegalArgumentException.class) + @Test public void testA() { - new BridgeServiceImpl(null, null, null, null); - } + assertThrows(IllegalArgumentException.class, () -> { + new BridgeServiceImpl(null, null, null, null); + }); + } - @Test(expected = ClassCastException.class) + @Test public void testB() { - new BridgeServiceImpl((OctaneSDK.SDKServicesConfigurer) new Object(), null, null, null); - } + assertThrows(ClassCastException.class, () -> { + new BridgeServiceImpl((OctaneSDK.SDKServicesConfigurer) new Object(), null, null, null); + }); + } - @Test(expected = IllegalArgumentException.class) + @Test public void testC() { - BridgeService.newInstance(null, null, null, null); - } + assertThrows(IllegalArgumentException.class, () -> + BridgeService.newInstance(null, null, null, null)); + } - @Test(expected = ClassCastException.class) + @Test public void testD() { - BridgeService.newInstance((OctaneSDK.SDKServicesConfigurer) new Object(), null, null, null); - } + assertThrows(ClassCastException.class, () -> + BridgeService.newInstance((OctaneSDK.SDKServicesConfigurer) new Object(), null, null, null)); + } } diff --git a/integrations-sdk/src/test/java/com/hp/octane/integrations/services/configuration/ConfigurationServiceNegativeTests.java b/integrations-sdk/src/test/java/com/hp/octane/integrations/services/configuration/ConfigurationServiceNegativeTests.java index 72d86386..66eaa0e6 100644 --- a/integrations-sdk/src/test/java/com/hp/octane/integrations/services/configuration/ConfigurationServiceNegativeTests.java +++ b/integrations-sdk/src/test/java/com/hp/octane/integrations/services/configuration/ConfigurationServiceNegativeTests.java @@ -32,27 +32,35 @@ package com.hp.octane.integrations.services.configuration; import com.hp.octane.integrations.OctaneSDK; -import org.junit.Test; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertThrows; public class ConfigurationServiceNegativeTests { - @Test(expected = IllegalArgumentException.class) + @Test public void testA() { - new ConfigurationServiceImpl(null, null); - } + assertThrows(IllegalArgumentException.class, () -> { + new ConfigurationServiceImpl(null, null); + }); + } - @Test(expected = ClassCastException.class) + @Test public void testB() { - new ConfigurationServiceImpl((OctaneSDK.SDKServicesConfigurer) new Object(), null); - } + assertThrows(ClassCastException.class, () -> { + new ConfigurationServiceImpl((OctaneSDK.SDKServicesConfigurer) new Object(), null); + }); + } - @Test(expected = IllegalArgumentException.class) + @Test public void testC() { - ConfigurationService.newInstance(null, null); - } + assertThrows(IllegalArgumentException.class, () -> + ConfigurationService.newInstance(null, null)); + } - @Test(expected = ClassCastException.class) + @Test public void testD() { - ConfigurationService.newInstance((OctaneSDK.SDKServicesConfigurer) new Object(), null); - } + assertThrows(ClassCastException.class, () -> + ConfigurationService.newInstance((OctaneSDK.SDKServicesConfigurer) new Object(), null)); + } } diff --git a/integrations-sdk/src/test/java/com/hp/octane/integrations/services/coverage/CoverageServiceNegativeTests.java b/integrations-sdk/src/test/java/com/hp/octane/integrations/services/coverage/CoverageServiceNegativeTests.java index 769f9a70..371d99f2 100644 --- a/integrations-sdk/src/test/java/com/hp/octane/integrations/services/coverage/CoverageServiceNegativeTests.java +++ b/integrations-sdk/src/test/java/com/hp/octane/integrations/services/coverage/CoverageServiceNegativeTests.java @@ -38,240 +38,280 @@ import com.hp.octane.integrations.dto.general.CIServerInfo; import com.hp.octane.integrations.services.sonar.SonarService; import com.hp.octane.integrations.services.sonar.SonarServiceImpl; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.util.UUID; +import static org.junit.jupiter.api.Assertions.assertThrows; + public class CoverageServiceNegativeTests { private static final DTOFactory dtoFactory = DTOFactory.getInstance(); // Coverage service - @Test(expected = IllegalArgumentException.class) + @Test public void testA1() { - new CoverageServiceImpl(null, null, null, null); - } + assertThrows(IllegalArgumentException.class, () -> { + new CoverageServiceImpl(null, null, null, null); + }); + } - @Test(expected = ClassCastException.class) + @Test public void testA2() { - new CoverageServiceImpl((OctaneSDK.SDKServicesConfigurer) new Object(), null, null, null); - } + assertThrows(ClassCastException.class, () -> { + new CoverageServiceImpl((OctaneSDK.SDKServicesConfigurer) new Object(), null, null, null); + }); + } - @Test(expected = IllegalArgumentException.class) + @Test public void testA3() { - CoverageService.newInstance(null, null, null, null); - } + assertThrows(IllegalArgumentException.class, () -> + CoverageService.newInstance(null, null, null, null)); + } - @Test(expected = ClassCastException.class) + @Test public void testA4() { - CoverageService.newInstance((OctaneSDK.SDKServicesConfigurer) new Object(), null, null, null); - } + assertThrows(ClassCastException.class, () -> + CoverageService.newInstance((OctaneSDK.SDKServicesConfigurer) new Object(), null, null, null)); + } // Sonar service - @Test(expected = IllegalArgumentException.class) + @Test public void testB1() { - new SonarServiceImpl(null, null, null, null); - } + assertThrows(IllegalArgumentException.class, () -> { + new SonarServiceImpl(null, null, null, null); + }); + } - @Test(expected = ClassCastException.class) + @Test public void testB2() { - new SonarServiceImpl((OctaneSDK.SDKServicesConfigurer) new Object(), null, null, null); - } + assertThrows(ClassCastException.class, () -> { + new SonarServiceImpl((OctaneSDK.SDKServicesConfigurer) new Object(), null, null, null); + }); + } - @Test(expected = IllegalArgumentException.class) + @Test public void testB3() { - SonarService.newInstance(null, null, null,null); - } + assertThrows(IllegalArgumentException.class, () -> + SonarService.newInstance(null, null, null, null)); + } - @Test(expected = ClassCastException.class) + @Test public void testB4() { - SonarService.newInstance((OctaneSDK.SDKServicesConfigurer) new Object(), null, null, null); - } + assertThrows(ClassCastException.class, () -> + SonarService.newInstance((OctaneSDK.SDKServicesConfigurer) new Object(), null, null, null)); + } // enqueue API negative testing validation - @Test(expected = IllegalArgumentException.class) + @Test public void testE1() { - OctaneConfiguration configuration = new OctaneConfigurationIntern(UUID.randomUUID().toString(), "http://localhost:8080", UUID.randomUUID().toString()); - OctaneClient client = OctaneSDK.addClient(configuration, PluginServices.class); - Assert.assertNotNull(client); - - CoverageService coverageService = client.getCoverageService(); - try { - coverageService.enqueuePushCoverage(null, null, null, null, null); - } finally { - OctaneSDK.removeClient(client); - } - } - - @Test(expected = IllegalArgumentException.class) + assertThrows(IllegalArgumentException.class, () -> { + OctaneConfiguration configuration = new OctaneConfigurationIntern(UUID.randomUUID().toString(), "http://localhost:8080", UUID.randomUUID().toString()); + OctaneClient client = OctaneSDK.addClient(configuration, PluginServices.class); + Assertions.assertNotNull(client); + + CoverageService coverageService = client.getCoverageService(); + try { + coverageService.enqueuePushCoverage(null, null, null, null, null); + } finally { + OctaneSDK.removeClient(client); + } + }); + } + + @Test public void testE2() { - OctaneConfiguration configuration = new OctaneConfigurationIntern(UUID.randomUUID().toString(), "http://localhost:8080", UUID.randomUUID().toString()); - OctaneClient client = OctaneSDK.addClient(configuration, PluginServices.class); - Assert.assertNotNull(client); - - CoverageService coverageService = client.getCoverageService(); - try { - coverageService.enqueuePushCoverage("", null, null, null, null); - } finally { - OctaneSDK.removeClient(client); - } - } - - @Test(expected = IllegalArgumentException.class) + assertThrows(IllegalArgumentException.class, () -> { + OctaneConfiguration configuration = new OctaneConfigurationIntern(UUID.randomUUID().toString(), "http://localhost:8080", UUID.randomUUID().toString()); + OctaneClient client = OctaneSDK.addClient(configuration, PluginServices.class); + Assertions.assertNotNull(client); + + CoverageService coverageService = client.getCoverageService(); + try { + coverageService.enqueuePushCoverage("", null, null, null, null); + } finally { + OctaneSDK.removeClient(client); + } + }); + } + + @Test public void testE3() { - OctaneConfiguration configuration = new OctaneConfigurationIntern(UUID.randomUUID().toString(), "http://localhost:8080", UUID.randomUUID().toString()); - OctaneClient client = OctaneSDK.addClient(configuration, PluginServices.class); - Assert.assertNotNull(client); - - CoverageService coverageService = client.getCoverageService(); - try { - coverageService.enqueuePushCoverage("job-id", null, null, null, null); - } finally { - OctaneSDK.removeClient(client); - } - } - - @Test(expected = IllegalArgumentException.class) + assertThrows(IllegalArgumentException.class, () -> { + OctaneConfiguration configuration = new OctaneConfigurationIntern(UUID.randomUUID().toString(), "http://localhost:8080", UUID.randomUUID().toString()); + OctaneClient client = OctaneSDK.addClient(configuration, PluginServices.class); + Assertions.assertNotNull(client); + + CoverageService coverageService = client.getCoverageService(); + try { + coverageService.enqueuePushCoverage("job-id", null, null, null, null); + } finally { + OctaneSDK.removeClient(client); + } + }); + } + + @Test public void testE4() { - OctaneConfiguration configuration = new OctaneConfigurationIntern(UUID.randomUUID().toString(), "http://localhost:8080", UUID.randomUUID().toString()); - OctaneClient client = OctaneSDK.addClient(configuration, PluginServices.class); - Assert.assertNotNull(client); - - CoverageService coverageService = client.getCoverageService(); - try { - coverageService.enqueuePushCoverage("job-id", "", null, null, null); - } finally { - OctaneSDK.removeClient(client); - } - } - - @Test(expected = IllegalArgumentException.class) + assertThrows(IllegalArgumentException.class, () -> { + OctaneConfiguration configuration = new OctaneConfigurationIntern(UUID.randomUUID().toString(), "http://localhost:8080", UUID.randomUUID().toString()); + OctaneClient client = OctaneSDK.addClient(configuration, PluginServices.class); + Assertions.assertNotNull(client); + + CoverageService coverageService = client.getCoverageService(); + try { + coverageService.enqueuePushCoverage("job-id", "", null, null, null); + } finally { + OctaneSDK.removeClient(client); + } + }); + } + + @Test public void testE5() { - OctaneConfiguration configuration = new OctaneConfigurationIntern(UUID.randomUUID().toString(), "http://localhost:8080", UUID.randomUUID().toString()); - OctaneClient client = OctaneSDK.addClient(configuration, PluginServices.class); - Assert.assertNotNull(client); - - CoverageService coverageService = client.getCoverageService(); - try { - coverageService.enqueuePushCoverage("job-id", "build-id", null, null, null); - } finally { - OctaneSDK.removeClient(client); - } - } + assertThrows(IllegalArgumentException.class, () -> { + OctaneConfiguration configuration = new OctaneConfigurationIntern(UUID.randomUUID().toString(), "http://localhost:8080", UUID.randomUUID().toString()); + OctaneClient client = OctaneSDK.addClient(configuration, PluginServices.class); + Assertions.assertNotNull(client); + + CoverageService coverageService = client.getCoverageService(); + try { + coverageService.enqueuePushCoverage("job-id", "build-id", null, null, null); + } finally { + OctaneSDK.removeClient(client); + } + }); + } // push API negative testing validation - @Test(expected = IllegalArgumentException.class) + @Test public void testF1() { - OctaneConfiguration configuration = new OctaneConfigurationIntern(UUID.randomUUID().toString(), "http://localhost:8080", UUID.randomUUID().toString()); - OctaneClient client = OctaneSDK.addClient(configuration, PluginServices.class); - Assert.assertNotNull(client); - - CoverageService coverageService = client.getCoverageService(); - try { - coverageService.pushCoverage(null, null, null, null); - } finally { - OctaneSDK.removeClient(client); - } - } - - @Test(expected = IllegalArgumentException.class) + assertThrows(IllegalArgumentException.class, () -> { + OctaneConfiguration configuration = new OctaneConfigurationIntern(UUID.randomUUID().toString(), "http://localhost:8080", UUID.randomUUID().toString()); + OctaneClient client = OctaneSDK.addClient(configuration, PluginServices.class); + Assertions.assertNotNull(client); + + CoverageService coverageService = client.getCoverageService(); + try { + coverageService.pushCoverage(null, null, null, null); + } finally { + OctaneSDK.removeClient(client); + } + }); + } + + @Test public void testF2() { - OctaneConfiguration configuration = new OctaneConfigurationIntern(UUID.randomUUID().toString(), "http://localhost:8080", UUID.randomUUID().toString()); - OctaneClient client = OctaneSDK.addClient(configuration, PluginServices.class); - Assert.assertNotNull(client); - - CoverageService coverageService = client.getCoverageService(); - try { - coverageService.pushCoverage("", null, null, null); - } finally { - OctaneSDK.removeClient(client); - } - } - - @Test(expected = IllegalArgumentException.class) + assertThrows(IllegalArgumentException.class, () -> { + OctaneConfiguration configuration = new OctaneConfigurationIntern(UUID.randomUUID().toString(), "http://localhost:8080", UUID.randomUUID().toString()); + OctaneClient client = OctaneSDK.addClient(configuration, PluginServices.class); + Assertions.assertNotNull(client); + + CoverageService coverageService = client.getCoverageService(); + try { + coverageService.pushCoverage("", null, null, null); + } finally { + OctaneSDK.removeClient(client); + } + }); + } + + @Test public void testF3() { - OctaneConfiguration configuration = new OctaneConfigurationIntern(UUID.randomUUID().toString(), "http://localhost:8080", UUID.randomUUID().toString()); - OctaneClient client = OctaneSDK.addClient(configuration, PluginServices.class); - Assert.assertNotNull(client); - - CoverageService coverageService = client.getCoverageService(); - try { - coverageService.pushCoverage("job-id", null, null, null); - } finally { - OctaneSDK.removeClient(client); - } - } - - @Test(expected = IllegalArgumentException.class) + assertThrows(IllegalArgumentException.class, () -> { + OctaneConfiguration configuration = new OctaneConfigurationIntern(UUID.randomUUID().toString(), "http://localhost:8080", UUID.randomUUID().toString()); + OctaneClient client = OctaneSDK.addClient(configuration, PluginServices.class); + Assertions.assertNotNull(client); + + CoverageService coverageService = client.getCoverageService(); + try { + coverageService.pushCoverage("job-id", null, null, null); + } finally { + OctaneSDK.removeClient(client); + } + }); + } + + @Test public void testF4() { - OctaneConfiguration configuration = new OctaneConfigurationIntern(UUID.randomUUID().toString(), "http://localhost:8080", UUID.randomUUID().toString()); - OctaneClient client = OctaneSDK.addClient(configuration, PluginServices.class); - Assert.assertNotNull(client); - - CoverageService coverageService = client.getCoverageService(); - try { - coverageService.pushCoverage("job-id", "", null, null); - } finally { - OctaneSDK.removeClient(client); - } - } - - @Test(expected = IllegalArgumentException.class) + assertThrows(IllegalArgumentException.class, () -> { + OctaneConfiguration configuration = new OctaneConfigurationIntern(UUID.randomUUID().toString(), "http://localhost:8080", UUID.randomUUID().toString()); + OctaneClient client = OctaneSDK.addClient(configuration, PluginServices.class); + Assertions.assertNotNull(client); + + CoverageService coverageService = client.getCoverageService(); + try { + coverageService.pushCoverage("job-id", "", null, null); + } finally { + OctaneSDK.removeClient(client); + } + }); + } + + @Test public void testF5() { - OctaneConfiguration configuration = new OctaneConfigurationIntern(UUID.randomUUID().toString(), "http://localhost:8080", UUID.randomUUID().toString()); - OctaneClient client = OctaneSDK.addClient(configuration, PluginServices.class); - Assert.assertNotNull(client); - - CoverageService coverageService = client.getCoverageService(); - try { - coverageService.pushCoverage("job-id", "build-id", null, null); - } finally { - OctaneSDK.removeClient(client); - } - } - - @Test(expected = IllegalArgumentException.class) + assertThrows(IllegalArgumentException.class, () -> { + OctaneConfiguration configuration = new OctaneConfigurationIntern(UUID.randomUUID().toString(), "http://localhost:8080", UUID.randomUUID().toString()); + OctaneClient client = OctaneSDK.addClient(configuration, PluginServices.class); + Assertions.assertNotNull(client); + + CoverageService coverageService = client.getCoverageService(); + try { + coverageService.pushCoverage("job-id", "build-id", null, null); + } finally { + OctaneSDK.removeClient(client); + } + }); + } + + @Test public void testF6() { - OctaneConfiguration configuration = new OctaneConfigurationIntern(UUID.randomUUID().toString(), "http://localhost:8080", UUID.randomUUID().toString()); - OctaneClient client = OctaneSDK.addClient(configuration, PluginServices.class); - Assert.assertNotNull(client); - - CoverageService coverageService = client.getCoverageService(); - try { - coverageService.pushCoverage("job-id", "build-id", CoverageReportType.JACOCOXML, null); - } finally { - OctaneSDK.removeClient(client); - } - } + assertThrows(IllegalArgumentException.class, () -> { + OctaneConfiguration configuration = new OctaneConfigurationIntern(UUID.randomUUID().toString(), "http://localhost:8080", UUID.randomUUID().toString()); + OctaneClient client = OctaneSDK.addClient(configuration, PluginServices.class); + Assertions.assertNotNull(client); + + CoverageService coverageService = client.getCoverageService(); + try { + coverageService.pushCoverage("job-id", "build-id", CoverageReportType.JACOCOXML, null); + } finally { + OctaneSDK.removeClient(client); + } + }); + } // is relevant API negative test - @Test(expected = IllegalArgumentException.class) + @Test public void testG1() { - OctaneConfiguration configuration = new OctaneConfigurationIntern(UUID.randomUUID().toString(), "http://localhost:8080", UUID.randomUUID().toString()); - OctaneClient client = OctaneSDK.addClient(configuration, PluginServices.class); - Assert.assertNotNull(client); - - CoverageService coverageService = client.getCoverageService(); - try { - coverageService.isSonarReportRelevant(null); - } finally { - OctaneSDK.removeClient(client); - } - } - - @Test(expected = IllegalArgumentException.class) + assertThrows(IllegalArgumentException.class, () -> { + OctaneConfiguration configuration = new OctaneConfigurationIntern(UUID.randomUUID().toString(), "http://localhost:8080", UUID.randomUUID().toString()); + OctaneClient client = OctaneSDK.addClient(configuration, PluginServices.class); + Assertions.assertNotNull(client); + + CoverageService coverageService = client.getCoverageService(); + try { + coverageService.isSonarReportRelevant(null); + } finally { + OctaneSDK.removeClient(client); + } + }); + } + + @Test public void testG2() { - OctaneConfiguration configuration = new OctaneConfigurationIntern(UUID.randomUUID().toString(), "http://localhost:8080", UUID.randomUUID().toString()); - OctaneClient client = OctaneSDK.addClient(configuration, PluginServices.class); - Assert.assertNotNull(client); - - CoverageService coverageService = client.getCoverageService(); - try { - coverageService.isSonarReportRelevant(""); - } finally { - OctaneSDK.removeClient(client); - } - } + assertThrows(IllegalArgumentException.class, () -> { + OctaneConfiguration configuration = new OctaneConfigurationIntern(UUID.randomUUID().toString(), "http://localhost:8080", UUID.randomUUID().toString()); + OctaneClient client = OctaneSDK.addClient(configuration, PluginServices.class); + Assertions.assertNotNull(client); + + CoverageService coverageService = client.getCoverageService(); + try { + coverageService.isSonarReportRelevant(""); + } finally { + OctaneSDK.removeClient(client); + } + }); + } public static final class PluginServices extends CIPluginServices { diff --git a/integrations-sdk/src/test/java/com/hp/octane/integrations/services/entities/EntitiesServiceNegativeTests.java b/integrations-sdk/src/test/java/com/hp/octane/integrations/services/entities/EntitiesServiceNegativeTests.java index ea7eaf10..316e8fbc 100644 --- a/integrations-sdk/src/test/java/com/hp/octane/integrations/services/entities/EntitiesServiceNegativeTests.java +++ b/integrations-sdk/src/test/java/com/hp/octane/integrations/services/entities/EntitiesServiceNegativeTests.java @@ -32,27 +32,35 @@ package com.hp.octane.integrations.services.entities; import com.hp.octane.integrations.OctaneSDK; -import org.junit.Test; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertThrows; public class EntitiesServiceNegativeTests { - @Test(expected = IllegalArgumentException.class) + @Test public void testA() { - new EntitiesServiceImpl(null, null); - } + assertThrows(IllegalArgumentException.class, () -> { + new EntitiesServiceImpl(null, null); + }); + } - @Test(expected = ClassCastException.class) + @Test public void testB() { - new EntitiesServiceImpl((OctaneSDK.SDKServicesConfigurer) new Object(), null); - } + assertThrows(ClassCastException.class, () -> { + new EntitiesServiceImpl((OctaneSDK.SDKServicesConfigurer) new Object(), null); + }); + } - @Test(expected = IllegalArgumentException.class) + @Test public void testC() { - EntitiesService.newInstance(null, null); - } + assertThrows(IllegalArgumentException.class, () -> + EntitiesService.newInstance(null, null)); + } - @Test(expected = ClassCastException.class) + @Test public void testD() { - EntitiesService.newInstance((OctaneSDK.SDKServicesConfigurer) new Object(), null); - } + assertThrows(ClassCastException.class, () -> + EntitiesService.newInstance((OctaneSDK.SDKServicesConfigurer) new Object(), null)); + } } diff --git a/integrations-sdk/src/test/java/com/hp/octane/integrations/services/events/EventsServiceNegativeTests.java b/integrations-sdk/src/test/java/com/hp/octane/integrations/services/events/EventsServiceNegativeTests.java index e43fe372..432e4075 100644 --- a/integrations-sdk/src/test/java/com/hp/octane/integrations/services/events/EventsServiceNegativeTests.java +++ b/integrations-sdk/src/test/java/com/hp/octane/integrations/services/events/EventsServiceNegativeTests.java @@ -32,27 +32,35 @@ package com.hp.octane.integrations.services.events; import com.hp.octane.integrations.OctaneSDK; -import org.junit.Test; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertThrows; public class EventsServiceNegativeTests { - @Test(expected = IllegalArgumentException.class) + @Test public void testA() { - new EventsServiceImpl(null, null, null); - } + assertThrows(IllegalArgumentException.class, () -> { + new EventsServiceImpl(null, null, null); + }); + } - @Test(expected = ClassCastException.class) + @Test public void testB() { - new EventsServiceImpl((OctaneSDK.SDKServicesConfigurer) new Object(), null, null); - } + assertThrows(ClassCastException.class, () -> { + new EventsServiceImpl((OctaneSDK.SDKServicesConfigurer) new Object(), null, null); + }); + } - @Test(expected = IllegalArgumentException.class) + @Test public void testC() { - EventsService.newInstance(null, null, null); - } + assertThrows(IllegalArgumentException.class, () -> + EventsService.newInstance(null, null, null)); + } - @Test(expected = ClassCastException.class) + @Test public void testD() { - EventsService.newInstance((OctaneSDK.SDKServicesConfigurer) new Object(), null, null); - } + assertThrows(ClassCastException.class, () -> + EventsService.newInstance((OctaneSDK.SDKServicesConfigurer) new Object(), null, null)); + } } diff --git a/integrations-sdk/src/test/java/com/hp/octane/integrations/services/logging/LoggingNegativeTests.java b/integrations-sdk/src/test/java/com/hp/octane/integrations/services/logging/LoggingNegativeTests.java index 2a9c225c..3cc62ad2 100644 --- a/integrations-sdk/src/test/java/com/hp/octane/integrations/services/logging/LoggingNegativeTests.java +++ b/integrations-sdk/src/test/java/com/hp/octane/integrations/services/logging/LoggingNegativeTests.java @@ -32,27 +32,35 @@ package com.hp.octane.integrations.services.logging; import com.hp.octane.integrations.OctaneSDK; -import org.junit.Test; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertThrows; public class LoggingNegativeTests { - @Test(expected = IllegalArgumentException.class) + @Test public void testA() { - new LoggingServiceImpl(null); - } + assertThrows(IllegalArgumentException.class, () -> { + new LoggingServiceImpl(null); + }); + } - @Test(expected = ClassCastException.class) + @Test public void testB() { - new LoggingServiceImpl((OctaneSDK.SDKServicesConfigurer) new Object()); - } + assertThrows(ClassCastException.class, () -> { + new LoggingServiceImpl((OctaneSDK.SDKServicesConfigurer) new Object()); + }); + } - @Test(expected = IllegalArgumentException.class) + @Test public void testC() { - LoggingService.newInstance(null); - } + assertThrows(IllegalArgumentException.class, () -> + LoggingService.newInstance(null)); + } - @Test(expected = ClassCastException.class) + @Test public void testD() { - LoggingService.newInstance((OctaneSDK.SDKServicesConfigurer) new Object()); - } + assertThrows(ClassCastException.class, () -> + LoggingService.newInstance((OctaneSDK.SDKServicesConfigurer) new Object())); + } } diff --git a/integrations-sdk/src/test/java/com/hp/octane/integrations/services/logs/LogsServiceNegativeTests.java b/integrations-sdk/src/test/java/com/hp/octane/integrations/services/logs/LogsServiceNegativeTests.java index 2b527a5b..dfd4d15f 100644 --- a/integrations-sdk/src/test/java/com/hp/octane/integrations/services/logs/LogsServiceNegativeTests.java +++ b/integrations-sdk/src/test/java/com/hp/octane/integrations/services/logs/LogsServiceNegativeTests.java @@ -32,27 +32,35 @@ package com.hp.octane.integrations.services.logs; import com.hp.octane.integrations.OctaneSDK; -import org.junit.Test; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertThrows; public class LogsServiceNegativeTests { - @Test(expected = IllegalArgumentException.class) + @Test public void testA() { - new LogsServiceImpl(null, null, null, null); - } + assertThrows(IllegalArgumentException.class, () -> { + new LogsServiceImpl(null, null, null, null); + }); + } - @Test(expected = ClassCastException.class) + @Test public void testB() { - new LogsServiceImpl((OctaneSDK.SDKServicesConfigurer) new Object(), null, null, null); - } + assertThrows(ClassCastException.class, () -> { + new LogsServiceImpl((OctaneSDK.SDKServicesConfigurer) new Object(), null, null, null); + }); + } - @Test(expected = IllegalArgumentException.class) + @Test public void testC() { - LogsService.newInstance(null, null, null, null); - } + assertThrows(IllegalArgumentException.class, () -> + LogsService.newInstance(null, null, null, null)); + } - @Test(expected = ClassCastException.class) + @Test public void testD() { - LogsService.newInstance((OctaneSDK.SDKServicesConfigurer) new Object(), null, null, null); - } + assertThrows(ClassCastException.class, () -> + LogsService.newInstance((OctaneSDK.SDKServicesConfigurer) new Object(), null, null, null)); + } } diff --git a/integrations-sdk/src/test/java/com/hp/octane/integrations/services/pipelines/PipelineContextServiceNegativeTests.java b/integrations-sdk/src/test/java/com/hp/octane/integrations/services/pipelines/PipelineContextServiceNegativeTests.java index 51754884..798eef4c 100644 --- a/integrations-sdk/src/test/java/com/hp/octane/integrations/services/pipelines/PipelineContextServiceNegativeTests.java +++ b/integrations-sdk/src/test/java/com/hp/octane/integrations/services/pipelines/PipelineContextServiceNegativeTests.java @@ -32,27 +32,35 @@ package com.hp.octane.integrations.services.pipelines; import com.hp.octane.integrations.OctaneSDK; -import org.junit.Test; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertThrows; public class PipelineContextServiceNegativeTests { - @Test(expected = IllegalArgumentException.class) + @Test public void testA() { - new PipelineContextServiceImpl(null, null); - } + assertThrows(IllegalArgumentException.class, () -> { + new PipelineContextServiceImpl(null, null); + }); + } - @Test(expected = ClassCastException.class) + @Test public void testB() { - new PipelineContextServiceImpl((OctaneSDK.SDKServicesConfigurer) new Object(), null); - } + assertThrows(ClassCastException.class, () -> { + new PipelineContextServiceImpl((OctaneSDK.SDKServicesConfigurer) new Object(), null); + }); + } - @Test(expected = IllegalArgumentException.class) + @Test public void testC() { - PipelineContextService.newInstance(null, null); - } + assertThrows(IllegalArgumentException.class, () -> + PipelineContextService.newInstance(null, null)); + } - @Test(expected = ClassCastException.class) + @Test public void testD() { - PipelineContextService.newInstance((OctaneSDK.SDKServicesConfigurer) new Object(), null); - } + assertThrows(ClassCastException.class, () -> + PipelineContextService.newInstance((OctaneSDK.SDKServicesConfigurer) new Object(), null)); + } } diff --git a/integrations-sdk/src/test/java/com/hp/octane/integrations/services/pullrequestsandbranches/PullRequestsServiceNegativeTests.java b/integrations-sdk/src/test/java/com/hp/octane/integrations/services/pullrequestsandbranches/PullRequestsServiceNegativeTests.java index fd49ecf7..1412d2b9 100644 --- a/integrations-sdk/src/test/java/com/hp/octane/integrations/services/pullrequestsandbranches/PullRequestsServiceNegativeTests.java +++ b/integrations-sdk/src/test/java/com/hp/octane/integrations/services/pullrequestsandbranches/PullRequestsServiceNegativeTests.java @@ -32,27 +32,35 @@ package com.hp.octane.integrations.services.pullrequestsandbranches; import com.hp.octane.integrations.OctaneSDK; -import org.junit.Test; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertThrows; public class PullRequestsServiceNegativeTests { - @Test(expected = IllegalArgumentException.class) + @Test public void testA() { - new PullRequestAndBranchServiceImpl(null, null, null); - } + assertThrows(IllegalArgumentException.class, () -> { + new PullRequestAndBranchServiceImpl(null, null, null); + }); + } - @Test(expected = ClassCastException.class) + @Test public void testB() { - new PullRequestAndBranchServiceImpl((OctaneSDK.SDKServicesConfigurer) new Object(), null, null); - } + assertThrows(ClassCastException.class, () -> { + new PullRequestAndBranchServiceImpl((OctaneSDK.SDKServicesConfigurer) new Object(), null, null); + }); + } - @Test(expected = IllegalArgumentException.class) + @Test public void testC() { - PullRequestAndBranchService.newInstance(null, null, null); - } + assertThrows(IllegalArgumentException.class, () -> + PullRequestAndBranchService.newInstance(null, null, null)); + } - @Test(expected = ClassCastException.class) + @Test public void testD() { - PullRequestAndBranchService.newInstance((OctaneSDK.SDKServicesConfigurer) new Object(), null, null); - } + assertThrows(ClassCastException.class, () -> + PullRequestAndBranchService.newInstance((OctaneSDK.SDKServicesConfigurer) new Object(), null, null)); + } } diff --git a/integrations-sdk/src/test/java/com/hp/octane/integrations/services/queueing/QueueingServiceNegativeTests.java b/integrations-sdk/src/test/java/com/hp/octane/integrations/services/queueing/QueueingServiceNegativeTests.java index d224ac6c..6dc3a6d3 100644 --- a/integrations-sdk/src/test/java/com/hp/octane/integrations/services/queueing/QueueingServiceNegativeTests.java +++ b/integrations-sdk/src/test/java/com/hp/octane/integrations/services/queueing/QueueingServiceNegativeTests.java @@ -32,27 +32,35 @@ package com.hp.octane.integrations.services.queueing; import com.hp.octane.integrations.OctaneSDK; -import org.junit.Test; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertThrows; public class QueueingServiceNegativeTests { - @Test(expected = IllegalArgumentException.class) + @Test public void testA() { - new QueueingServiceImpl(null); - } + assertThrows(IllegalArgumentException.class, () -> { + new QueueingServiceImpl(null); + }); + } - @Test(expected = ClassCastException.class) + @Test public void testB() { - new QueueingServiceImpl((OctaneSDK.SDKServicesConfigurer) new Object()); - } + assertThrows(ClassCastException.class, () -> { + new QueueingServiceImpl((OctaneSDK.SDKServicesConfigurer) new Object()); + }); + } - @Test(expected = IllegalArgumentException.class) + @Test public void testC() { - QueueingService.newInstance(null); - } + assertThrows(IllegalArgumentException.class, () -> + QueueingService.newInstance(null)); + } - @Test(expected = ClassCastException.class) + @Test public void testD() { - QueueingService.newInstance((OctaneSDK.SDKServicesConfigurer) new Object()); - } + assertThrows(ClassCastException.class, () -> + QueueingService.newInstance((OctaneSDK.SDKServicesConfigurer) new Object())); + } } diff --git a/integrations-sdk/src/test/java/com/hp/octane/integrations/services/rest/RestServiceNegativeTests.java b/integrations-sdk/src/test/java/com/hp/octane/integrations/services/rest/RestServiceNegativeTests.java index 91d7f1c1..46c48198 100644 --- a/integrations-sdk/src/test/java/com/hp/octane/integrations/services/rest/RestServiceNegativeTests.java +++ b/integrations-sdk/src/test/java/com/hp/octane/integrations/services/rest/RestServiceNegativeTests.java @@ -32,53 +32,69 @@ package com.hp.octane.integrations.services.rest; import com.hp.octane.integrations.OctaneSDK; -import org.junit.Test; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertThrows; public class RestServiceNegativeTests { // REST Service // - @Test(expected = IllegalArgumentException.class) + @Test public void testA() { - new RestServiceImpl(null); - } + assertThrows(IllegalArgumentException.class, () -> { + new RestServiceImpl(null); + }); + } - @Test(expected = ClassCastException.class) + @Test public void testB() { - new RestServiceImpl((OctaneSDK.SDKServicesConfigurer) new Object()); - } + assertThrows(ClassCastException.class, () -> { + new RestServiceImpl((OctaneSDK.SDKServicesConfigurer) new Object()); + }); + } - @Test(expected = IllegalArgumentException.class) + @Test public void testC() { - RestService.newInstance(null); - } + assertThrows(IllegalArgumentException.class, () -> + RestService.newInstance(null)); + } - @Test(expected = ClassCastException.class) + @Test public void testD() { - RestService.newInstance((OctaneSDK.SDKServicesConfigurer) new Object()); - } + assertThrows(ClassCastException.class, () -> + RestService.newInstance((OctaneSDK.SDKServicesConfigurer) new Object())); + } // Octane REST Client // - @Test(expected = IllegalArgumentException.class) + @Test public void testE() { - new OctaneRestClientImpl(null); - } + assertThrows(IllegalArgumentException.class, () -> { + new OctaneRestClientImpl(null); + }); + } - @Test(expected = ClassCastException.class) + @Test public void testF() { - new OctaneRestClientImpl((OctaneSDK.SDKServicesConfigurer) new Object()); - } + assertThrows(ClassCastException.class, () -> { + new OctaneRestClientImpl((OctaneSDK.SDKServicesConfigurer) new Object()); + }); + } // SSC (Fortify OP) REST Client // - @Test(expected = IllegalArgumentException.class) + @Test public void testG() { - new SSCRestClientImpl(null); - } + assertThrows(IllegalArgumentException.class, () -> { + new SSCRestClientImpl(null); + }); + } - @Test(expected = ClassCastException.class) + @Test public void testH() { - new SSCRestClientImpl((OctaneSDK.SDKServicesConfigurer) new Object()); - } + assertThrows(ClassCastException.class, () -> { + new SSCRestClientImpl((OctaneSDK.SDKServicesConfigurer) new Object()); + }); + } } \ No newline at end of file diff --git a/integrations-sdk/src/test/java/com/hp/octane/integrations/services/scmdata/SCMDataServiceNegativeTests.java b/integrations-sdk/src/test/java/com/hp/octane/integrations/services/scmdata/SCMDataServiceNegativeTests.java index abee5e91..9fe2dfec 100644 --- a/integrations-sdk/src/test/java/com/hp/octane/integrations/services/scmdata/SCMDataServiceNegativeTests.java +++ b/integrations-sdk/src/test/java/com/hp/octane/integrations/services/scmdata/SCMDataServiceNegativeTests.java @@ -35,97 +35,113 @@ import com.hp.octane.integrations.dto.DTOFactory; import com.hp.octane.integrations.dto.general.CIPluginInfo; import com.hp.octane.integrations.dto.general.CIServerInfo; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.util.UUID; +import static org.junit.jupiter.api.Assertions.assertThrows; + public class SCMDataServiceNegativeTests { private static final DTOFactory dtoFactory = DTOFactory.getInstance(); - @Test(expected = IllegalArgumentException.class) + @Test public void testA() { - new SCMDataServiceImpl(null, null, null, null, null); - } + assertThrows(IllegalArgumentException.class, () -> { + new SCMDataServiceImpl(null, null, null, null, null); + }); + } - @Test(expected = ClassCastException.class) + @Test public void testB() { - new SCMDataServiceImpl(null, (OctaneSDK.SDKServicesConfigurer) new Object(), null, null, null); - } + assertThrows(ClassCastException.class, () -> { + new SCMDataServiceImpl(null, (OctaneSDK.SDKServicesConfigurer) new Object(), null, null, null); + }); + } - @Test(expected = IllegalArgumentException.class) + @Test public void testC() { - SCMDataService.newInstance(null, null, null, null, null); - } + assertThrows(IllegalArgumentException.class, () -> + SCMDataService.newInstance(null, null, null, null, null)); + } - @Test(expected = ClassCastException.class) + @Test public void testD() { - SCMDataService.newInstance(null, (OctaneSDK.SDKServicesConfigurer) new Object(), null, null, null); - } + assertThrows(ClassCastException.class, () -> + SCMDataService.newInstance(null, (OctaneSDK.SDKServicesConfigurer) new Object(), null, null, null)); + } // enqueue API negative testing validation - @Test(expected = IllegalArgumentException.class) + @Test public void testE1() { - OctaneConfiguration configuration = new OctaneConfigurationIntern(UUID.randomUUID().toString(), "http://localhost:8080", UUID.randomUUID().toString()); - OctaneClient client = OctaneSDK.addClient(configuration, SCMDataServiceNegativeTests.PluginServices.class); - Assert.assertNotNull(client); + assertThrows(IllegalArgumentException.class, () -> { + OctaneConfiguration configuration = new OctaneConfigurationIntern(UUID.randomUUID().toString(), "http://localhost:8080", UUID.randomUUID().toString()); + OctaneClient client = OctaneSDK.addClient(configuration, SCMDataServiceNegativeTests.PluginServices.class); + Assertions.assertNotNull(client); + + SCMDataService scmDataService = client.getSCMDataService(); + try { + scmDataService.enqueueSCMData(null, null, null, null); + } finally { + OctaneSDK.removeClient(client); + } + }); + } - SCMDataService scmDataService = client.getSCMDataService(); - try { - scmDataService.enqueueSCMData(null, null,null, null); - } finally { - OctaneSDK.removeClient(client); - } - } - - @Test(expected = IllegalArgumentException.class) + @Test public void testE2() { - OctaneConfiguration configuration = new OctaneConfigurationIntern(UUID.randomUUID().toString(), "http://localhost:8080", UUID.randomUUID().toString()); - OctaneClient client = OctaneSDK.addClient(configuration, SCMDataServiceNegativeTests.PluginServices.class); - Assert.assertNotNull(client); + assertThrows(IllegalArgumentException.class, () -> { + OctaneConfiguration configuration = new OctaneConfigurationIntern(UUID.randomUUID().toString(), "http://localhost:8080", UUID.randomUUID().toString()); + OctaneClient client = OctaneSDK.addClient(configuration, SCMDataServiceNegativeTests.PluginServices.class); + Assertions.assertNotNull(client); + + SCMDataService scmDataService = client.getSCMDataService(); + try { + scmDataService.enqueueSCMData("", null, null, null); + } finally { + OctaneSDK.removeClient(client); + } + }); + } - SCMDataService scmDataService = client.getSCMDataService(); - try { - scmDataService.enqueueSCMData("", null,null, null); - } finally { - OctaneSDK.removeClient(client); - } - } - - @Test(expected = IllegalArgumentException.class) + @Test public void testE3() { - OctaneConfiguration configuration = new OctaneConfigurationIntern(UUID.randomUUID().toString(), "http://localhost:8080", UUID.randomUUID().toString()); - OctaneClient client = OctaneSDK.addClient(configuration, SCMDataServiceNegativeTests.PluginServices.class); - Assert.assertNotNull(client); - - SCMDataService scmDataService = client.getSCMDataService(); - try { - scmDataService.enqueueSCMData("job-id", null,null, null); - } finally { - OctaneSDK.removeClient(client); - } - } + assertThrows(IllegalArgumentException.class, () -> { + OctaneConfiguration configuration = new OctaneConfigurationIntern(UUID.randomUUID().toString(), "http://localhost:8080", UUID.randomUUID().toString()); + OctaneClient client = OctaneSDK.addClient(configuration, SCMDataServiceNegativeTests.PluginServices.class); + Assertions.assertNotNull(client); + + SCMDataService scmDataService = client.getSCMDataService(); + try { + scmDataService.enqueueSCMData("job-id", null, null, null); + } finally { + OctaneSDK.removeClient(client); + } + }); + } - @Test(expected = IllegalArgumentException.class) + @Test public void testE4() { - OctaneConfiguration configuration = new OctaneConfigurationIntern(UUID.randomUUID().toString(), "http://localhost:8080", UUID.randomUUID().toString()); - OctaneClient client = OctaneSDK.addClient(configuration, SCMDataServiceNegativeTests.PluginServices.class); - Assert.assertNotNull(client); - - SCMDataService scmDataService = client.getSCMDataService(); - try { - scmDataService.enqueueSCMData("job-id", "",null, null); - } finally { - OctaneSDK.removeClient(client); - } - } + assertThrows(IllegalArgumentException.class, () -> { + OctaneConfiguration configuration = new OctaneConfigurationIntern(UUID.randomUUID().toString(), "http://localhost:8080", UUID.randomUUID().toString()); + OctaneClient client = OctaneSDK.addClient(configuration, SCMDataServiceNegativeTests.PluginServices.class); + Assertions.assertNotNull(client); + + SCMDataService scmDataService = client.getSCMDataService(); + try { + scmDataService.enqueueSCMData("job-id", "", null, null); + } finally { + OctaneSDK.removeClient(client); + } + }); + } // this one is the OK one @Test public void testE5() { OctaneConfiguration configuration = new OctaneConfigurationIntern(UUID.randomUUID().toString(), "http://localhost:8080", UUID.randomUUID().toString()); OctaneClient client = OctaneSDK.addClient(configuration, SCMDataServiceNegativeTests.PluginServices.class); - Assert.assertNotNull(client); + Assertions.assertNotNull(client); SCMDataService scmDataService = client.getSCMDataService(); try { diff --git a/integrations-sdk/src/test/java/com/hp/octane/integrations/services/tasking/TaskingServiceE2ETests.java b/integrations-sdk/src/test/java/com/hp/octane/integrations/services/tasking/TaskingServiceE2ETests.java index 2682bc43..b95c29d2 100644 --- a/integrations-sdk/src/test/java/com/hp/octane/integrations/services/tasking/TaskingServiceE2ETests.java +++ b/integrations-sdk/src/test/java/com/hp/octane/integrations/services/tasking/TaskingServiceE2ETests.java @@ -40,16 +40,14 @@ import com.hp.octane.integrations.dto.connectivity.OctaneTaskAbridged; import com.hp.octane.integrations.testhelpers.GeneralTestUtils; import com.hp.octane.integrations.testhelpers.OctaneSPEndpointSimulator; -import com.hp.octane.integrations.utils.CIPluginSDKUtils; import org.apache.http.HttpStatus; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.eclipse.jetty.http.HttpMethod; -import org.eclipse.jetty.server.Response; -import org.junit.AfterClass; -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; import java.util.Collections; import java.util.HashMap; @@ -58,7 +56,6 @@ import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.TimeUnit; -import java.util.zip.GZIPInputStream; import static org.apache.http.HttpHeaders.CONTENT_TYPE; @@ -73,18 +70,18 @@ public class TaskingServiceE2ETests { private static final BlockingQueue tasks = new ArrayBlockingQueue<>(10); private static final Map results = new HashMap<>(); - @BeforeClass + @BeforeAll public static void setupEnvironment() { // setup Octane simulator OctaneSPEndpointSimulator octaneSPEndpointSimulator = setupOctaneEPSimulator(sspId); - Assert.assertNotNull(octaneSPEndpointSimulator); + Assertions.assertNotNull(octaneSPEndpointSimulator); // setup Octane client OctaneConfiguration configuration = new OctaneConfigurationIntern(inId, OctaneSPEndpointSimulator.getSimulatorUrl(), sspId); client = OctaneSDK.addClient(configuration, TaskingTestPluginServicesTest.class); } - @AfterClass + @AfterAll public static void cleanupEnvironment() { OctaneSDK.removeClient(client); OctaneSPEndpointSimulator.removeInstance(sspId); @@ -120,18 +117,18 @@ public void taskingE2ETest() { }); // verify status task cycle - Assert.assertTrue(results.containsKey(statusTaskId)); + Assertions.assertTrue(results.containsKey(statusTaskId)); OctaneResultAbridged statusResult = results.get(statusTaskId); - Assert.assertNotNull(statusResult); - Assert.assertEquals(inId, statusResult.getServiceId()); - Assert.assertEquals(HttpStatus.SC_OK, statusResult.getStatus()); + Assertions.assertNotNull(statusResult); + Assertions.assertEquals(inId, statusResult.getServiceId()); + Assertions.assertEquals(HttpStatus.SC_OK, statusResult.getStatus()); // verify jobs task cycle - Assert.assertTrue(results.containsKey(jobsTaskId)); + Assertions.assertTrue(results.containsKey(jobsTaskId)); OctaneResultAbridged jobsResult = results.get(jobsTaskId); - Assert.assertNotNull(jobsResult); - Assert.assertEquals(inId, jobsResult.getServiceId()); - Assert.assertEquals(HttpStatus.SC_OK, jobsResult.getStatus()); + Assertions.assertNotNull(jobsResult); + Assertions.assertEquals(inId, jobsResult.getServiceId()); + Assertions.assertEquals(HttpStatus.SC_OK, jobsResult.getStatus()); } private static OctaneSPEndpointSimulator setupOctaneEPSimulator(String sspId) { @@ -141,16 +138,14 @@ private static OctaneSPEndpointSimulator setupOctaneEPSimulator(String sspId) { result.removeApiHandler(HttpMethod.GET, "^.*tasks$"); // install GET tasks API handler - result.installApiHandler(HttpMethod.GET, "^.*tasks$", request -> { + result.installApiHandler(HttpMethod.GET, "^.*tasks$", (request, response) -> { try { - Response response = request.getResponse(); OctaneTaskAbridged task = tasks.poll(500, TimeUnit.MILLISECONDS); if (task != null) { logger.info("got task to dispatch to CI Server - " + task.getUrl() + " - " + task.getId() + "..."); response.setStatus(HttpStatus.SC_OK); - response.addHeader(CONTENT_TYPE, "application/json"); - response.getWriter().write(dtoFactory.dtoCollectionToJson(Collections.singletonList(task))); - response.flushBuffer(); + response.getHeaders().put(CONTENT_TYPE, "application/json"); + OctaneSPEndpointSimulator.writeResponseBody(response, dtoFactory.dtoCollectionToJson(Collections.singletonList(task))); logger.info("... task dispatched"); } else { results.put("timeout_flow_verification_part", null); @@ -162,13 +157,13 @@ private static OctaneSPEndpointSimulator setupOctaneEPSimulator(String sspId) { }); // install PUT results API handler - result.installApiHandler(HttpMethod.PUT, "^.*result$", request -> { + result.installApiHandler(HttpMethod.PUT, "^.*result$", (request, response) -> { try { - String rawBody = CIPluginSDKUtils.inputStreamToUTF8String(new GZIPInputStream(request.getInputStream())); + String rawBody = OctaneSPEndpointSimulator.readRequestBody(request); OctaneResultAbridged taskResult = dtoFactory.dtoFromJson(rawBody, OctaneResultAbridged.class); logger.info("received and parsed result for task " + taskResult.getId()); - Assert.assertNotNull(taskResult); - Assert.assertNotNull(taskResult.getId()); + Assertions.assertNotNull(taskResult); + Assertions.assertNotNull(taskResult.getId()); results.put(taskResult.getId(), taskResult); } catch (Exception e) { logger.error("failed during simulation of Octane EP - PUT results", e); diff --git a/integrations-sdk/src/test/java/com/hp/octane/integrations/services/tasking/TaskingServiceNegativeTests.java b/integrations-sdk/src/test/java/com/hp/octane/integrations/services/tasking/TaskingServiceNegativeTests.java index bdfadd6e..4b472448 100644 --- a/integrations-sdk/src/test/java/com/hp/octane/integrations/services/tasking/TaskingServiceNegativeTests.java +++ b/integrations-sdk/src/test/java/com/hp/octane/integrations/services/tasking/TaskingServiceNegativeTests.java @@ -33,18 +33,24 @@ import com.hp.octane.integrations.OctaneSDK; import com.hp.octane.integrations.services.configuration.ConfigurationService; -import org.junit.Test; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertThrows; public class TaskingServiceNegativeTests { - @Test(expected = IllegalArgumentException.class) + @Test public void testA() { - new TasksProcessorImpl(null,null); - } + assertThrows(IllegalArgumentException.class, () -> { + new TasksProcessorImpl(null, null); + }); + } - @Test(expected = ClassCastException.class) + @Test public void testB() { - new TasksProcessorImpl((OctaneSDK.SDKServicesConfigurer) new Object(),(ConfigurationService) new Object()); - } + assertThrows(ClassCastException.class, () -> { + new TasksProcessorImpl((OctaneSDK.SDKServicesConfigurer) new Object(), (ConfigurationService) new Object()); + }); + } } diff --git a/integrations-sdk/src/test/java/com/hp/octane/integrations/services/tasking/TaskingServiceTests.java b/integrations-sdk/src/test/java/com/hp/octane/integrations/services/tasking/TaskingServiceTests.java index ef646bb3..ef347e8a 100644 --- a/integrations-sdk/src/test/java/com/hp/octane/integrations/services/tasking/TaskingServiceTests.java +++ b/integrations-sdk/src/test/java/com/hp/octane/integrations/services/tasking/TaskingServiceTests.java @@ -47,10 +47,10 @@ import org.apache.http.HttpHeaders; import org.apache.http.HttpStatus; import org.apache.http.entity.ContentType; -import org.junit.AfterClass; -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; import java.util.UUID; @@ -59,13 +59,14 @@ import static com.hp.octane.integrations.services.tasking.TaskingTestPluginServicesTest.TEST_SERVER_TYPE; import static com.hp.octane.integrations.services.tasking.TaskingTestPluginServicesTest.TEST_SERVER_URL; import static com.hp.octane.integrations.services.tasking.TaskingTestPluginServicesTest.TEST_SERVER_VERSION; +import static org.junit.jupiter.api.Assertions.assertThrows; public class TaskingServiceTests { private static final DTOFactory dtoFactory = DTOFactory.getInstance(); private static final String APIPrefix = "/nga/api/v1"; private static OctaneClient client; - @BeforeClass + @BeforeAll public static void setupClient() { String inId = UUID.randomUUID().toString(); String sspId = UUID.randomUUID().toString(); @@ -73,71 +74,79 @@ public static void setupClient() { client = OctaneSDK.addClient(configuration, TaskingTestPluginServicesTest.class); } - @AfterClass + @AfterAll public static void removeClient() { OctaneSDK.removeClient(client); } - @Test(expected = IllegalArgumentException.class) + @Test public void negativeTestA() { - TasksProcessor tasksProcessor = client.getTasksProcessor(); - Assert.assertNotNull(tasksProcessor); + assertThrows(IllegalArgumentException.class, () -> { + TasksProcessor tasksProcessor = client.getTasksProcessor(); + Assertions.assertNotNull(tasksProcessor); - tasksProcessor.execute(null); - } + tasksProcessor.execute(null); + }); + } - @Test(expected = IllegalArgumentException.class) + @Test public void negativeTestB() { - TasksProcessor tasksProcessor = client.getTasksProcessor(); - Assert.assertNotNull(tasksProcessor); + assertThrows(IllegalArgumentException.class, () -> { + TasksProcessor tasksProcessor = client.getTasksProcessor(); + Assertions.assertNotNull(tasksProcessor); - OctaneTaskAbridged taskAbridged = dtoFactory.newDTO(OctaneTaskAbridged.class); - tasksProcessor.execute(taskAbridged); - } + OctaneTaskAbridged taskAbridged = dtoFactory.newDTO(OctaneTaskAbridged.class); + tasksProcessor.execute(taskAbridged); + }); + } - @Test(expected = IllegalArgumentException.class) + @Test public void negativeTestC() { - TasksProcessor tasksProcessor = client.getTasksProcessor(); - Assert.assertNotNull(tasksProcessor); + assertThrows(IllegalArgumentException.class, () -> { + TasksProcessor tasksProcessor = client.getTasksProcessor(); + Assertions.assertNotNull(tasksProcessor); - OctaneTaskAbridged taskAbridged = dtoFactory.newDTO(OctaneTaskAbridged.class) - .setUrl(""); - tasksProcessor.execute(taskAbridged); - } + OctaneTaskAbridged taskAbridged = dtoFactory.newDTO(OctaneTaskAbridged.class) + .setUrl(""); + tasksProcessor.execute(taskAbridged); + }); + } - @Test(expected = IllegalArgumentException.class) + @Test public void negativeTestD() { - TasksProcessor tasksProcessor = client.getTasksProcessor(); - Assert.assertNotNull(tasksProcessor); + assertThrows(IllegalArgumentException.class, () -> { + TasksProcessor tasksProcessor = client.getTasksProcessor(); + Assertions.assertNotNull(tasksProcessor); - OctaneTaskAbridged taskAbridged = dtoFactory.newDTO(OctaneTaskAbridged.class) - .setUrl("some_wrong_url"); - tasksProcessor.execute(taskAbridged); - } + OctaneTaskAbridged taskAbridged = dtoFactory.newDTO(OctaneTaskAbridged.class) + .setUrl("some_wrong_url"); + tasksProcessor.execute(taskAbridged); + }); + } @Test public void testNonExistingAPI() { TasksProcessor tasksProcessor = client.getTasksProcessor(); - Assert.assertNotNull(tasksProcessor); + Assertions.assertNotNull(tasksProcessor); OctaneTaskAbridged taskAbridged = dtoFactory.newDTO(OctaneTaskAbridged.class) .setId(UUID.randomUUID().toString()) .setUrl(OctaneSPEndpointSimulator.getSimulatorUrl() + APIPrefix + "/some/non/existing/url"); OctaneResultAbridged resultAbridged = tasksProcessor.execute(taskAbridged); - Assert.assertNotNull(resultAbridged); - Assert.assertEquals(HttpStatus.SC_NOT_FOUND, resultAbridged.getStatus()); - Assert.assertNotNull(resultAbridged.getHeaders()); - Assert.assertTrue(resultAbridged.getHeaders().isEmpty()); - Assert.assertEquals(taskAbridged.getId(), resultAbridged.getId()); - Assert.assertEquals(client.getInstanceId(), resultAbridged.getServiceId()); - Assert.assertNull(resultAbridged.getBody()); + Assertions.assertNotNull(resultAbridged); + Assertions.assertEquals(HttpStatus.SC_NOT_FOUND, resultAbridged.getStatus()); + Assertions.assertNotNull(resultAbridged.getHeaders()); + Assertions.assertTrue(resultAbridged.getHeaders().isEmpty()); + Assertions.assertEquals(taskAbridged.getId(), resultAbridged.getId()); + Assertions.assertEquals(client.getInstanceId(), resultAbridged.getServiceId()); + Assertions.assertNull(resultAbridged.getBody()); } @Test public void testJobNoImplementedAPI() { TasksProcessor tasksProcessor = client.getTasksProcessor(); - Assert.assertNotNull(tasksProcessor); + Assertions.assertNotNull(tasksProcessor); OctaneTaskAbridged taskAbridged = dtoFactory.newDTO(OctaneTaskAbridged.class) .setId(UUID.randomUUID().toString()) @@ -153,7 +162,7 @@ public void testJobNoImplementedAPI() { @Test public void testJobsWithParamsAPI() { TasksProcessor tasksProcessor = client.getTasksProcessor(); - Assert.assertNotNull(tasksProcessor); + Assertions.assertNotNull(tasksProcessor); OctaneTaskAbridged taskAbridged = dtoFactory.newDTO(OctaneTaskAbridged.class) .setId(UUID.randomUUID().toString()) @@ -163,20 +172,20 @@ public void testJobsWithParamsAPI() { runCommonAsserts(resultAbridged, taskAbridged.getId(), HttpStatus.SC_OK); CIJobsList ciJobsList = dtoFactory.dtoFromJson(resultAbridged.getBody(), CIJobsList.class); - Assert.assertNotNull(ciJobsList); - Assert.assertNotNull(ciJobsList.getJobs()); - Assert.assertEquals(3, ciJobsList.getJobs().length); + Assertions.assertNotNull(ciJobsList); + Assertions.assertNotNull(ciJobsList.getJobs()); + Assertions.assertEquals(3, ciJobsList.getJobs().length); for (PipelineNode ciJob : ciJobsList.getJobs()) { - Assert.assertNotNull(ciJob); - Assert.assertTrue(ciJob.getName().startsWith("Job ")); - Assert.assertTrue(ciJob.getJobCiId().startsWith("job-")); - Assert.assertNotNull(ciJob.getParameters()); - Assert.assertEquals(3, ciJob.getParameters().size()); + Assertions.assertNotNull(ciJob); + Assertions.assertTrue(ciJob.getName().startsWith("Job ")); + Assertions.assertTrue(ciJob.getJobCiId().startsWith("job-")); + Assertions.assertNotNull(ciJob.getParameters()); + Assertions.assertEquals(3, ciJob.getParameters().size()); for (CIParameter ciParameter : ciJob.getParameters()) { - Assert.assertNotNull(ciParameter); - Assert.assertNotNull(ciParameter.getName()); - Assert.assertNotNull(ciParameter.getType()); - Assert.assertNotNull(ciParameter.getValue()); + Assertions.assertNotNull(ciParameter); + Assertions.assertNotNull(ciParameter.getName()); + Assertions.assertNotNull(ciParameter.getType()); + Assertions.assertNotNull(ciParameter.getValue()); } } } @@ -184,7 +193,7 @@ public void testJobsWithParamsAPI() { @Test public void testJobsNoParamsAPI() { TasksProcessor tasksProcessor = client.getTasksProcessor(); - Assert.assertNotNull(tasksProcessor); + Assertions.assertNotNull(tasksProcessor); OctaneTaskAbridged taskAbridged = dtoFactory.newDTO(OctaneTaskAbridged.class) .setId(UUID.randomUUID().toString()) @@ -194,41 +203,41 @@ public void testJobsNoParamsAPI() { runCommonAsserts(resultAbridged, taskAbridged.getId(), HttpStatus.SC_OK); CIJobsList ciJobsList = dtoFactory.dtoFromJson(resultAbridged.getBody(), CIJobsList.class); - Assert.assertNotNull(ciJobsList); - Assert.assertNotNull(ciJobsList.getJobs()); - Assert.assertEquals(3, ciJobsList.getJobs().length); + Assertions.assertNotNull(ciJobsList); + Assertions.assertNotNull(ciJobsList.getJobs()); + Assertions.assertEquals(3, ciJobsList.getJobs().length); for (PipelineNode ciJob : ciJobsList.getJobs()) { - Assert.assertNotNull(ciJob); - Assert.assertTrue(ciJob.getName().startsWith("Job ")); - Assert.assertTrue(ciJob.getJobCiId().startsWith("job-")); - Assert.assertNotNull(ciJob.getParameters()); - Assert.assertTrue(ciJob.getParameters().isEmpty()); + Assertions.assertNotNull(ciJob); + Assertions.assertTrue(ciJob.getName().startsWith("Job ")); + Assertions.assertTrue(ciJob.getJobCiId().startsWith("job-")); + Assertions.assertNotNull(ciJob.getParameters()); + Assertions.assertTrue(ciJob.getParameters().isEmpty()); } } @Test public void testJobNotExistsAPI() { TasksProcessor tasksProcessor = client.getTasksProcessor(); - Assert.assertNotNull(tasksProcessor); + Assertions.assertNotNull(tasksProcessor); OctaneTaskAbridged taskAbridged = dtoFactory.newDTO(OctaneTaskAbridged.class) .setId(UUID.randomUUID().toString()) .setUrl(OctaneSPEndpointSimulator.getSimulatorUrl() + APIPrefix + "/jobs/job-not-exists"); OctaneResultAbridged resultAbridged = tasksProcessor.execute(taskAbridged); - Assert.assertNotNull(resultAbridged); - Assert.assertEquals(HttpStatus.SC_NOT_FOUND, resultAbridged.getStatus()); - Assert.assertNotNull(resultAbridged.getHeaders()); - Assert.assertTrue(resultAbridged.getHeaders().isEmpty()); - Assert.assertEquals(taskAbridged.getId(), resultAbridged.getId()); - Assert.assertEquals(client.getInstanceId(), resultAbridged.getServiceId()); - Assert.assertNull(resultAbridged.getBody()); + Assertions.assertNotNull(resultAbridged); + Assertions.assertEquals(HttpStatus.SC_NOT_FOUND, resultAbridged.getStatus()); + Assertions.assertNotNull(resultAbridged.getHeaders()); + Assertions.assertTrue(resultAbridged.getHeaders().isEmpty()); + Assertions.assertEquals(taskAbridged.getId(), resultAbridged.getId()); + Assertions.assertEquals(client.getInstanceId(), resultAbridged.getServiceId()); + Assertions.assertNull(resultAbridged.getBody()); } @Test public void testJobSpecificAPI() { TasksProcessor tasksProcessor = client.getTasksProcessor(); - Assert.assertNotNull(tasksProcessor); + Assertions.assertNotNull(tasksProcessor); OctaneTaskAbridged taskAbridged = dtoFactory.newDTO(OctaneTaskAbridged.class) .setId(UUID.randomUUID().toString()) @@ -238,22 +247,22 @@ public void testJobSpecificAPI() { runCommonAsserts(resultAbridged, taskAbridged.getId(), HttpStatus.SC_OK); PipelineNode pipeline = dtoFactory.dtoFromJson(resultAbridged.getBody(), PipelineNode.class); - Assert.assertNotNull(pipeline); - Assert.assertEquals("job-a", pipeline.getJobCiId()); - Assert.assertEquals("Job A", pipeline.getName()); - Assert.assertNotNull(pipeline.getPhasesInternal()); - Assert.assertTrue(pipeline.getPhasesInternal().isEmpty()); - Assert.assertNotNull(pipeline.getPhasesPostBuild()); - Assert.assertTrue(pipeline.getPhasesPostBuild().isEmpty()); - Assert.assertNotNull(pipeline.getParameters()); - Assert.assertTrue(pipeline.getParameters().isEmpty()); - Assert.assertNull(pipeline.getMultiBranchType()); + Assertions.assertNotNull(pipeline); + Assertions.assertEquals("job-a", pipeline.getJobCiId()); + Assertions.assertEquals("Job A", pipeline.getName()); + Assertions.assertNotNull(pipeline.getPhasesInternal()); + Assertions.assertTrue(pipeline.getPhasesInternal().isEmpty()); + Assertions.assertNotNull(pipeline.getPhasesPostBuild()); + Assertions.assertTrue(pipeline.getPhasesPostBuild().isEmpty()); + Assertions.assertNotNull(pipeline.getParameters()); + Assertions.assertTrue(pipeline.getParameters().isEmpty()); + Assertions.assertNull(pipeline.getMultiBranchType()); } @Test public void testRunNotImplementedAPI() { TasksProcessor tasksProcessor = client.getTasksProcessor(); - Assert.assertNotNull(tasksProcessor); + Assertions.assertNotNull(tasksProcessor); OctaneTaskAbridged taskAbridged = dtoFactory.newDTO(OctaneTaskAbridged.class) .setId(UUID.randomUUID().toString()) @@ -263,17 +272,17 @@ public void testRunNotImplementedAPI() { OctaneResultAbridged resultAbridged = tasksProcessor.execute(taskAbridged); TaskingTestPluginServicesTest.runAPINotImplemented = false; - Assert.assertNotNull(resultAbridged); - Assert.assertEquals(HttpStatus.SC_NOT_IMPLEMENTED, resultAbridged.getStatus()); - Assert.assertEquals(taskAbridged.getId(), resultAbridged.getId()); - Assert.assertEquals(client.getInstanceId(), resultAbridged.getServiceId()); - Assert.assertNull(resultAbridged.getBody()); + Assertions.assertNotNull(resultAbridged); + Assertions.assertEquals(HttpStatus.SC_NOT_IMPLEMENTED, resultAbridged.getStatus()); + Assertions.assertEquals(taskAbridged.getId(), resultAbridged.getId()); + Assertions.assertEquals(client.getInstanceId(), resultAbridged.getServiceId()); + Assertions.assertNull(resultAbridged.getBody()); } @Test public void testRunThrowsExceptionAPI() { TasksProcessor tasksProcessor = client.getTasksProcessor(); - Assert.assertNotNull(tasksProcessor); + Assertions.assertNotNull(tasksProcessor); OctaneTaskAbridged taskAbridged = dtoFactory.newDTO(OctaneTaskAbridged.class) .setId(UUID.randomUUID().toString()) @@ -286,34 +295,34 @@ public void testRunThrowsExceptionAPI() { runCommonAsserts(resultAbridged, taskAbridged.getId(), HttpStatus.SC_INTERNAL_SERVER_ERROR); TaskProcessingErrorBody errorBody = dtoFactory.dtoFromJson(resultAbridged.getBody(), TaskProcessingErrorBody.class); - Assert.assertNotNull(errorBody); - Assert.assertNotNull(errorBody.getErrorMessage()); - Assert.assertTrue(errorBody.getErrorMessage().contains("runtime exception")); + Assertions.assertNotNull(errorBody); + Assertions.assertNotNull(errorBody.getErrorMessage()); + Assertions.assertTrue(errorBody.getErrorMessage().contains("runtime exception")); } @Test public void testRunAPI() { TasksProcessor tasksProcessor = client.getTasksProcessor(); - Assert.assertNotNull(tasksProcessor); + Assertions.assertNotNull(tasksProcessor); OctaneTaskAbridged taskAbridged = dtoFactory.newDTO(OctaneTaskAbridged.class) .setId(UUID.randomUUID().toString()) .setUrl(OctaneSPEndpointSimulator.getSimulatorUrl() + APIPrefix + "/jobs/job-a/run"); OctaneResultAbridged resultAbridged = tasksProcessor.execute(taskAbridged); - Assert.assertNotNull(resultAbridged); - Assert.assertEquals(HttpStatus.SC_CREATED, resultAbridged.getStatus()); - Assert.assertEquals(taskAbridged.getId(), resultAbridged.getId()); - Assert.assertEquals(client.getInstanceId(), resultAbridged.getServiceId()); - Assert.assertNull(resultAbridged.getBody()); + Assertions.assertNotNull(resultAbridged); + Assertions.assertEquals(HttpStatus.SC_CREATED, resultAbridged.getStatus()); + Assertions.assertEquals(taskAbridged.getId(), resultAbridged.getId()); + Assertions.assertEquals(client.getInstanceId(), resultAbridged.getServiceId()); + Assertions.assertNull(resultAbridged.getBody()); } private void runCommonAsserts(OctaneResultAbridged resultAbridged, String taskId, int expectedStatus) { - Assert.assertNotNull(resultAbridged); - Assert.assertEquals(expectedStatus, resultAbridged.getStatus()); - Assert.assertEquals(ContentType.APPLICATION_JSON.getMimeType(), resultAbridged.getHeaders().get(HttpHeaders.CONTENT_TYPE)); - Assert.assertEquals(taskId, resultAbridged.getId()); - Assert.assertEquals(client.getInstanceId(), resultAbridged.getServiceId()); - Assert.assertNotNull(resultAbridged.getBody()); + Assertions.assertNotNull(resultAbridged); + Assertions.assertEquals(expectedStatus, resultAbridged.getStatus()); + Assertions.assertEquals(ContentType.APPLICATION_JSON.getMimeType(), resultAbridged.getHeaders().get(HttpHeaders.CONTENT_TYPE)); + Assertions.assertEquals(taskId, resultAbridged.getId()); + Assertions.assertEquals(client.getInstanceId(), resultAbridged.getServiceId()); + Assertions.assertNotNull(resultAbridged.getBody()); } } diff --git a/integrations-sdk/src/test/java/com/hp/octane/integrations/services/tests/TestsServiceNegativeTests.java b/integrations-sdk/src/test/java/com/hp/octane/integrations/services/tests/TestsServiceNegativeTests.java index fa74f317..e5275727 100644 --- a/integrations-sdk/src/test/java/com/hp/octane/integrations/services/tests/TestsServiceNegativeTests.java +++ b/integrations-sdk/src/test/java/com/hp/octane/integrations/services/tests/TestsServiceNegativeTests.java @@ -38,20 +38,23 @@ import com.hp.octane.integrations.dto.DTOFactory; import com.hp.octane.integrations.dto.tests.TestsResult; import com.hp.octane.integrations.testhelpers.OctaneSPEndpointSimulator; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.util.UUID; +import static org.junit.jupiter.api.Assertions.assertThrows; + public class TestsServiceNegativeTests { private static final DTOFactory dtoFactory = DTOFactory.getInstance(); private static OctaneClient client; - @BeforeClass + @BeforeAll public static void setupClient() { String inId = UUID.randomUUID().toString(); String sspId = UUID.randomUUID().toString(); @@ -59,127 +62,173 @@ public static void setupClient() { client = OctaneSDK.addClient(configuration, TestsServicePluginServicesTest.class); } - @AfterClass + @AfterAll public static void removeClient() { OctaneSDK.removeClient(client); } - @Test(expected = IllegalArgumentException.class) + @Test public void testA() { - new TestsServiceImpl(null, null, null, null); - } + assertThrows(IllegalArgumentException.class, () -> { + new TestsServiceImpl(null, null, null, null); + }); + } - @Test(expected = ClassCastException.class) + @Test public void testB() { - new TestsServiceImpl((OctaneSDK.SDKServicesConfigurer) new Object(), null, null, null); - } + assertThrows(ClassCastException.class, () -> { + new TestsServiceImpl((OctaneSDK.SDKServicesConfigurer) new Object(), null, null, null); + }); + } - @Test(expected = IllegalArgumentException.class) + @Test public void testC() { - TestsService.newInstance(null, null, null, null); - } + assertThrows(IllegalArgumentException.class, () -> + TestsService.newInstance(null, null, null, null)); + } - @Test(expected = ClassCastException.class) + @Test public void testD() { - TestsService.newInstance((OctaneSDK.SDKServicesConfigurer) new Object(), null, null, null); - } + assertThrows(ClassCastException.class, () -> + TestsService.newInstance((OctaneSDK.SDKServicesConfigurer) new Object(), null, null, null)); + } - @Test(expected = IllegalArgumentException.class) + @Test public void testE1() throws IOException { - TestsService testsService = client.getTestsService(); - ((TestsServiceImpl)testsService).isTestsResultRelevant(null, null); - } + assertThrows(IllegalArgumentException.class, () -> { + TestsService testsService = client.getTestsService(); + ((TestsServiceImpl) testsService).isTestsResultRelevant(null, null); + }); + } - @Test(expected = IllegalArgumentException.class) + @Test public void testE2() throws IOException { - TestsService testsService = client.getTestsService(); - ((TestsServiceImpl)testsService).isTestsResultRelevant("", null); - } + assertThrows(IllegalArgumentException.class, () -> { + TestsService testsService = client.getTestsService(); + ((TestsServiceImpl) testsService).isTestsResultRelevant("", null); + }); + } - @Test(expected = IllegalArgumentException.class) + @Test public void testF1() throws IOException { - TestsService testsService = client.getTestsService(); - TestsResult tr = null; - ((TestsServiceImpl)testsService).pushTestsResult(tr, null, null); - } - - @Test(expected = IllegalArgumentException.class) + assertThrows(IllegalArgumentException.class, () -> { + TestsService testsService = client.getTestsService(); + TestsResult tr = null; + ((TestsServiceImpl) testsService).pushTestsResult(tr, null, null); + }); + } + + @Test public void testF2() throws IOException { - TestsService testsService = client.getTestsService(); - ((TestsServiceImpl)testsService).pushTestsResult(dtoFactory.newDTO(TestsResult.class), null, null); - } - - @Test(expected = IllegalArgumentException.class) + assertThrows(IllegalArgumentException.class, () -> { + TestsService testsService = client.getTestsService(); + TestsResult newDTO = dtoFactory.newDTO(TestsResult.class); + ((TestsServiceImpl) testsService).pushTestsResult(newDTO, null, null); + }); + } + + @Test public void testF3() throws IOException { - TestsService testsService = client.getTestsService(); - ((TestsServiceImpl)testsService).pushTestsResult(dtoFactory.newDTO(TestsResult.class), "", null); - } - - @Test(expected = IllegalArgumentException.class) + assertThrows(IllegalArgumentException.class, () -> { + TestsService testsService = client.getTestsService(); + TestsResult newDTO = dtoFactory.newDTO(TestsResult.class); + ((TestsServiceImpl) testsService).pushTestsResult(newDTO, "", null); + }); + } + + @Test public void testF4() throws IOException { - TestsService testsService = client.getTestsService(); - ((TestsServiceImpl)testsService).pushTestsResult(dtoFactory.newDTO(TestsResult.class), "some", null); - } - - @Test(expected = IllegalArgumentException.class) + assertThrows(IllegalArgumentException.class, () -> { + TestsService testsService = client.getTestsService(); + TestsResult newDTO = dtoFactory.newDTO(TestsResult.class); + ((TestsServiceImpl) testsService).pushTestsResult(newDTO, "some", null); + }); + } + + @Test public void testF5() throws IOException { - TestsService testsService = client.getTestsService(); - ((TestsServiceImpl)testsService).pushTestsResult(dtoFactory.newDTO(TestsResult.class), "some", ""); - } + assertThrows(IllegalArgumentException.class, () -> { + TestsService testsService = client.getTestsService(); + TestsResult newDTO = dtoFactory.newDTO(TestsResult.class); + ((TestsServiceImpl) testsService).pushTestsResult(newDTO, "some", ""); + }); + } - @Test(expected = IllegalArgumentException.class) + @Test public void testG1() throws IOException { - TestsService testsService = client.getTestsService(); - InputStream is = null; - ((TestsServiceImpl)testsService).pushTestsResult(is, null, null); - } - - @Test(expected = IllegalArgumentException.class) + assertThrows(IllegalArgumentException.class, () -> { + TestsService testsService = client.getTestsService(); + InputStream is = null; + ((TestsServiceImpl) testsService).pushTestsResult(is, null, null); + }); + } + + @Test public void testG2() throws IOException { - TestsService testsService = client.getTestsService(); - ((TestsServiceImpl)testsService).pushTestsResult(new ByteArrayInputStream(new byte[]{}), null, null); - } - - @Test(expected = IllegalArgumentException.class) + assertThrows(IllegalArgumentException.class, () -> { + TestsService testsService = client.getTestsService(); + InputStream is = new ByteArrayInputStream(new byte[]{}); + ((TestsServiceImpl) testsService).pushTestsResult(is, null, null); + }); + } + + @Test public void testG3() throws IOException { - TestsService testsService = client.getTestsService(); - ((TestsServiceImpl)testsService).pushTestsResult(new ByteArrayInputStream(new byte[]{}), "", null); - } - - @Test(expected = IllegalArgumentException.class) + assertThrows(IllegalArgumentException.class, () -> { + TestsService testsService = client.getTestsService(); + InputStream is = new ByteArrayInputStream(new byte[]{}); + ((TestsServiceImpl) testsService).pushTestsResult(is, "", null); + }); + } + + @Test public void testG4() throws IOException { - TestsService testsService = client.getTestsService(); - ((TestsServiceImpl)testsService).pushTestsResult(new ByteArrayInputStream(new byte[]{}), "some", null); - } - - @Test(expected = IllegalArgumentException.class) + assertThrows(IllegalArgumentException.class, () -> { + TestsService testsService = client.getTestsService(); + InputStream is = new ByteArrayInputStream(new byte[]{}); + ((TestsServiceImpl) testsService).pushTestsResult(is, "some", null); + }); + } + + @Test public void testG5() throws IOException { - TestsService testsService = client.getTestsService(); - ((TestsServiceImpl)testsService).pushTestsResult(new ByteArrayInputStream(new byte[]{}), "some", ""); - } - - @Test(expected = IllegalArgumentException.class) + assertThrows(IllegalArgumentException.class, () -> { + TestsService testsService = client.getTestsService(); + InputStream is = new ByteArrayInputStream(new byte[]{}); + ((TestsServiceImpl) testsService).pushTestsResult(is, "some", ""); + }); + } + + @Test public void testH1() { - TestsService testsService = client.getTestsService(); - ((TestsServiceImpl)testsService).enqueuePushTestsResult(null, null, null); - } + assertThrows(IllegalArgumentException.class, () -> { + TestsService testsService = client.getTestsService(); + ((TestsServiceImpl) testsService).enqueuePushTestsResult(null, null, null); + }); + } - @Test(expected = IllegalArgumentException.class) + @Test public void testH2() { - TestsService testsService = client.getTestsService(); - testsService.enqueuePushTestsResult("", null, null); - } + assertThrows(IllegalArgumentException.class, () -> { + TestsService testsService = client.getTestsService(); + testsService.enqueuePushTestsResult("", null, null); + }); + } - @Test(expected = IllegalArgumentException.class) + @Test public void testH3() { - TestsService testsService = client.getTestsService(); - testsService.enqueuePushTestsResult("some", null, null); - } + assertThrows(IllegalArgumentException.class, () -> { + TestsService testsService = client.getTestsService(); + testsService.enqueuePushTestsResult("some", null, null); + }); + } - @Test(expected = IllegalArgumentException.class) + @Test public void testH4() { - TestsService testsService = client.getTestsService(); - testsService.enqueuePushTestsResult("some", "", null); - } + assertThrows(IllegalArgumentException.class, () -> { + TestsService testsService = client.getTestsService(); + testsService.enqueuePushTestsResult("some", "", null); + }); + } } diff --git a/integrations-sdk/src/test/java/com/hp/octane/integrations/services/vulnerabilities/ExistingIssuesInOctaneTest.java b/integrations-sdk/src/test/java/com/hp/octane/integrations/services/vulnerabilities/ExistingIssuesInOctaneTest.java index d94dd470..459f3af3 100644 --- a/integrations-sdk/src/test/java/com/hp/octane/integrations/services/vulnerabilities/ExistingIssuesInOctaneTest.java +++ b/integrations-sdk/src/test/java/com/hp/octane/integrations/services/vulnerabilities/ExistingIssuesInOctaneTest.java @@ -34,8 +34,8 @@ import com.hp.octane.integrations.OctaneConfiguration; import com.hp.octane.integrations.OctaneConfigurationIntern; import com.hp.octane.integrations.services.vulnerabilities.mocks.MockOctaneRestClient; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.ArrayList; @@ -48,7 +48,7 @@ public class ExistingIssuesInOctaneTest { public void emptyList() throws IOException { ExistingIssuesInOctane existingIssuesInOctane = buildExistingIssuesInOctane("[]"); List remoteIdsOpenVulnsFromOctane = existingIssuesInOctane.getRemoteIdsOpenVulnsFromOctane("Job1", "1", "Tag1"); - Assert.assertEquals(0, remoteIdsOpenVulnsFromOctane.size()); + Assertions.assertEquals(0, remoteIdsOpenVulnsFromOctane.size()); } @@ -70,9 +70,9 @@ public void nonEmptyList() throws IOException { ExistingIssuesInOctane existingIssuesInOctane = buildExistingIssuesInOctane(jsonVal); List remoteIdsOpenVulnsFromOctane = existingIssuesInOctane.getRemoteIdsOpenVulnsFromOctane("Job2", "2","Tag2"); - Assert.assertEquals("Id1",remoteIdsOpenVulnsFromOctane.get(0)); - Assert.assertEquals("Id2",remoteIdsOpenVulnsFromOctane.get(1)); - Assert.assertEquals("Id3",remoteIdsOpenVulnsFromOctane.get(2)); + Assertions.assertEquals("Id1",remoteIdsOpenVulnsFromOctane.getFirst()); + Assertions.assertEquals("Id2",remoteIdsOpenVulnsFromOctane.get(1)); + Assertions.assertEquals("Id3",remoteIdsOpenVulnsFromOctane.get(2)); } diff --git a/integrations-sdk/src/test/java/com/hp/octane/integrations/services/vulnerabilities/IssuesValidate.java b/integrations-sdk/src/test/java/com/hp/octane/integrations/services/vulnerabilities/IssuesValidate.java index ea09fe16..cf646c03 100644 --- a/integrations-sdk/src/test/java/com/hp/octane/integrations/services/vulnerabilities/IssuesValidate.java +++ b/integrations-sdk/src/test/java/com/hp/octane/integrations/services/vulnerabilities/IssuesValidate.java @@ -148,7 +148,7 @@ private void validateClosed(OctaneIssuesPushed octaneIssuesPushed, if(octaneIssues.size()!= 1){ throw new SSCTestFailure("Closed Issue was not pushed to Octane."); } - validateState(octaneIssues.get(0), "list_node.issue_state_node.closed", + validateState(octaneIssues.getFirst(), "list_node.issue_state_node.closed", "Close Issue was pushed to Octane but not with the right state."); } } @@ -171,11 +171,11 @@ private void validateNew(OctaneIssuesPushed octaneIssuesPushed, List { - Issues issues = new Issues(); - issues.setData(new ArrayList<>()); - ArrayList existingInOctane = new ArrayList<>(); - PackIssuesToOctaneUtils.packToOctaneIssues(issues.getData(), existingInOctane, - true); + Issues issues = new Issues(); + issues.setData(new ArrayList<>()); + ArrayList existingInOctane = new ArrayList<>(); + PackIssuesToOctaneUtils.packToOctaneIssues(issues.getData(), existingInOctane, + true); - } + }); + + } @Test public void packIssuesToClose() throws IOException { @@ -83,16 +87,16 @@ public void packIssuesToClose() throws IOException { PackIssuesToOctaneUtils.SortedIssues issueSortedIssues = PackIssuesToOctaneUtils.packToOctaneIssues(issues.getData(), toCloseInOctane, true); - Assert.assertEquals(2, issueSortedIssues.issuesToClose.size()); - Entity issueState1 = issueSortedIssues.issuesToClose.get(0).getState(); - Assert.assertEquals("list_node.issue_state_node.closed", issueState1.getId()); - Assert.assertEquals("list_node", issueState1.getType()); - Assert.assertEquals("Id1", issueSortedIssues.issuesToClose.get(0).getRemoteId()); + Assertions.assertEquals(2, issueSortedIssues.issuesToClose.size()); + Entity issueState1 = issueSortedIssues.issuesToClose.getFirst().getState(); + Assertions.assertEquals("list_node.issue_state_node.closed", issueState1.getId()); + Assertions.assertEquals("list_node", issueState1.getType()); + Assertions.assertEquals("Id1", issueSortedIssues.issuesToClose.getFirst().getRemoteId()); Entity issueState2 = issueSortedIssues.issuesToClose.get(1).getState(); - Assert.assertEquals("list_node.issue_state_node.closed", issueState2.getId()); - Assert.assertEquals("list_node", issueState2.getType()); - Assert.assertEquals("Id2", issueSortedIssues.issuesToClose.get(1).getRemoteId()); + Assertions.assertEquals("list_node.issue_state_node.closed", issueState2.getId()); + Assertions.assertEquals("list_node", issueState2.getType()); + Assertions.assertEquals("Id2", issueSortedIssues.issuesToClose.get(1).getRemoteId()); } @@ -104,13 +108,13 @@ public void packIssuesToNewAndUpdate() throws IOException { PackIssuesToOctaneUtils.SortedIssues issueSortedIssues = PackIssuesToOctaneUtils.packToOctaneIssues(issues.getData(), new ArrayList<>(), true); - Assert.assertEquals(2,issueSortedIssues.issuesToUpdate.size()); - Assert.assertEquals(2,issueSortedIssues.issuesRequiredExtendedData.size()); - Assert.assertEquals(0,issueSortedIssues.issuesToClose.size()); + Assertions.assertEquals(2,issueSortedIssues.issuesToUpdate.size()); + Assertions.assertEquals(2,issueSortedIssues.issuesRequiredExtendedData.size()); + Assertions.assertEquals(0,issueSortedIssues.issuesToClose.size()); List openOctaneIssues = createOctaneIssues(issueSortedIssues.issuesToUpdate, "Tag",idToDetails); - validateIssueMap(openOctaneIssues.get(0), + validateIssueMap(openOctaneIssues.getFirst(), "list_node.issue_state_node.new", "\\ABC\\DEF\\GHIJ.java", "1", @@ -126,7 +130,7 @@ public void packIssuesToNewAndUpdate() throws IOException { "Issue2"); - validateRemoteIdAndExtendedIssues(openOctaneIssues.get(0),"RemoteId1",idToDetails.get(1)); + validateRemoteIdAndExtendedIssues(openOctaneIssues.getFirst(),"RemoteId1",idToDetails.get(1)); validateRemoteIdAndExtendedIssues(openOctaneIssues.get(1),"RemoteId2",idToDetails.get(2)); } @@ -134,13 +138,13 @@ public void packIssuesToNewAndUpdate() throws IOException { private void validateRemoteIdAndExtendedIssues(OctaneIssue issue2AsMap, String remoteId1, IssueDetails issueDetails) { Map extended_data = (issue2AsMap.getExtendedData()); - Assert.assertEquals(issueDetails.getData().brief ,extended_data.get("summary")); - Assert.assertEquals(issueDetails.getData().recommendation, extended_data.get("recommendations")); - Assert.assertEquals(issueDetails.getData().tips, extended_data.get("tips")); - Assert.assertEquals(issueDetails.getData().detail, extended_data.get("explanation")); + Assertions.assertEquals(issueDetails.getData().brief ,extended_data.get("summary")); + Assertions.assertEquals(issueDetails.getData().recommendation, extended_data.get("recommendations")); + Assertions.assertEquals(issueDetails.getData().tips, extended_data.get("tips")); + Assertions.assertEquals(issueDetails.getData().detail, extended_data.get("explanation")); if(remoteId1 != null) { - Assert.assertEquals(remoteId1, issue2AsMap.getRemoteId()); + Assertions.assertEquals(remoteId1, issue2AsMap.getRemoteId()); } } @@ -156,10 +160,10 @@ public void packSomeToCloseAndSomeToNewAndUpdate() throws IOException { List octaneIssues = createOctaneIssues(issueSortedIssues.issuesToUpdate,"Tag", new HashMap<>()); - Assert.assertEquals(2,octaneIssues.size()); - Assert.assertEquals(2,issueSortedIssues.issuesToClose.size()); + Assertions.assertEquals(2,octaneIssues.size()); + Assertions.assertEquals(2,issueSortedIssues.issuesToClose.size()); - validateIssueMap(octaneIssues.get(0), + validateIssueMap(octaneIssues.getFirst(), "list_node.issue_state_node.new", "\\ABC\\DEF\\GHIJ.java", "1", @@ -176,13 +180,13 @@ public void packSomeToCloseAndSomeToNewAndUpdate() throws IOException { - validateIssueMap(issueSortedIssues.issuesToClose.get(0), + validateIssueMap(issueSortedIssues.issuesToClose.getFirst(), "list_node.issue_state_node.closed", null, "-1", null, null); - Assert.assertEquals(issueSortedIssues.issuesToClose.get(0).getRemoteId(), "XYZ"); + Assertions.assertEquals(issueSortedIssues.issuesToClose.getFirst().getRemoteId(), "XYZ"); validateIssueMap(issueSortedIssues.issuesToClose.get(1), @@ -191,7 +195,7 @@ public void packSomeToCloseAndSomeToNewAndUpdate() throws IOException { "-1", null, null); - Assert.assertEquals(issueSortedIssues.issuesToClose.get(1).getRemoteId(), "LMNO"); + Assertions.assertEquals(issueSortedIssues.issuesToClose.get(1).getRemoteId(), "LMNO"); } private Map getAllData() { @@ -221,19 +225,19 @@ private void validateIssueMap(OctaneIssue octaneIssue, String state, String loca String kingdom, String issueName) { if(state != null) { - Assert.assertEquals(state, octaneIssue.getState().getId()); + Assertions.assertEquals(state, octaneIssue.getState().getId()); } if(location != null) { - Assert.assertEquals(location, octaneIssue.getPrimaryLocationFull()); + Assertions.assertEquals(location, octaneIssue.getPrimaryLocationFull()); } if(!"-1".equals(line)) { - Assert.assertEquals(line, octaneIssue.getLine().toString()); + Assertions.assertEquals(line, octaneIssue.getLine().toString()); } if(kingdom != null) { - Assert.assertEquals(kingdom, octaneIssue.getExtendedData().get("kingdom")); + Assertions.assertEquals(kingdom, octaneIssue.getExtendedData().get("kingdom")); } if(issueName != null) { - Assert.assertEquals(issueName, octaneIssue.getExtendedData().get("issueName")); + Assertions.assertEquals(issueName, octaneIssue.getExtendedData().get("issueName")); } } diff --git a/integrations-sdk/src/test/java/com/hp/octane/integrations/services/vulnerabilities/SSCHandlerTest.java b/integrations-sdk/src/test/java/com/hp/octane/integrations/services/vulnerabilities/SSCHandlerTest.java index 415a7403..6f916668 100644 --- a/integrations-sdk/src/test/java/com/hp/octane/integrations/services/vulnerabilities/SSCHandlerTest.java +++ b/integrations-sdk/src/test/java/com/hp/octane/integrations/services/vulnerabilities/SSCHandlerTest.java @@ -37,9 +37,9 @@ import com.hp.octane.integrations.services.vulnerabilities.ssc.dto.Issues; import com.hp.octane.integrations.services.vulnerabilities.mocks.DummyContents; import com.hp.octane.integrations.services.vulnerabilities.mocks.MockSSCRestClient; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.Arrays; @@ -47,13 +47,14 @@ import static com.hp.octane.integrations.services.vulnerabilities.SSCTestUtils.*; import static org.easymock.EasyMock.*; +import static org.junit.jupiter.api.Assertions.assertThrows; public class SSCHandlerTest { VulnerabilitiesQueueItem queueItem; SSCProjectConfiguration configMock; - @Before + @BeforeEach public void prepareMembers(){ queueItem = new VulnerabilitiesQueueItem(); @@ -74,7 +75,7 @@ public void scanIsNotOverTest() throws IOException { artifactResponse)); SSCHandler sscHandler = new SSCHandler(queueItem, configMock, mockSSCRestClient); - Assert.assertFalse(sscHandler.isScanProcessFinished()); + Assertions.assertFalse(sscHandler.isScanProcessFinished()); } @Test @@ -91,24 +92,26 @@ public void scanIsOverButNoIssueTest() throws IOException { SSCHandler sscHandler = new SSCHandler(queueItem, configMock, mockSSCRestClient); Optional issuesIfScanCompleted = sscHandler.getIssuesIfScanCompleted(); - Assert.assertTrue(issuesIfScanCompleted.isPresent()); - Assert.assertEquals(0, issuesIfScanCompleted.get().getData().size()); + Assertions.assertTrue(issuesIfScanCompleted.isPresent()); + Assertions.assertEquals(0, issuesIfScanCompleted.get().getData().size()); } - @Test(expected = PermanentException.class) + @Test public void errorInScanTest() throws IOException { + assertThrows(PermanentException.class, () -> { - String projectResponse = getDummyProjectResponse(); - String projectVersionsResponse = getProjectVersionResponse(); - String artifactResponse = getArtificatResponse("ERROR_PROCESSING"); + String projectResponse = getDummyProjectResponse(); + String projectVersionsResponse = getProjectVersionResponse(); + String artifactResponse = getArtificatResponse("ERROR_PROCESSING"); - MockSSCRestClient mockSSCRestClient = new MockSSCRestClient(Arrays.asList(projectResponse, - projectVersionsResponse, - artifactResponse)); + MockSSCRestClient mockSSCRestClient = new MockSSCRestClient(Arrays.asList(projectResponse, + projectVersionsResponse, + artifactResponse)); - SSCHandler sscHandler = new SSCHandler(queueItem, configMock, mockSSCRestClient); - sscHandler.isScanProcessFinished(); + SSCHandler sscHandler = new SSCHandler(queueItem, configMock, mockSSCRestClient); + sscHandler.isScanProcessFinished(); + }); } @Test @@ -127,8 +130,8 @@ public void scanIsOverAndThereAreIssuesTest() throws IOException { SSCHandler sscHandler = new SSCHandler(queueItem, configMock, mockSSCRestClient); Optional issuesIfScanCompleted = sscHandler.getIssuesIfScanCompleted(); - Assert.assertTrue(issuesIfScanCompleted.isPresent()); - Assert.assertEquals(3, issuesIfScanCompleted.get().getData().size()); + Assertions.assertTrue(issuesIfScanCompleted.isPresent()); + Assertions.assertEquals(3, issuesIfScanCompleted.get().getData().size()); } diff --git a/integrations-sdk/src/test/java/com/hp/octane/integrations/services/vulnerabilities/SSCIntegrationTest.java b/integrations-sdk/src/test/java/com/hp/octane/integrations/services/vulnerabilities/SSCIntegrationTest.java index 30d97f7b..d5d7ee64 100644 --- a/integrations-sdk/src/test/java/com/hp/octane/integrations/services/vulnerabilities/SSCIntegrationTest.java +++ b/integrations-sdk/src/test/java/com/hp/octane/integrations/services/vulnerabilities/SSCIntegrationTest.java @@ -44,9 +44,13 @@ import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.eclipse.jetty.http.HttpMethod; -import org.junit.Assert; +import org.eclipse.jetty.io.Content; +import org.eclipse.jetty.server.Request; +import org.eclipse.jetty.util.Callback; +import org.junit.jupiter.api.Assertions; import java.io.IOException; +import java.nio.charset.StandardCharsets; import java.text.SimpleDateFormat; import java.util.*; import java.util.stream.Collectors; @@ -113,7 +117,7 @@ public void runAsQueueItem(){ }); } - Assert.assertEquals(clientAInstanceId + "|" + CIPluginSDKUtils.urlEncodeBase64("jobSSC1") + "|1", preFlightRequestCollectors.get(spIdA).get(0)); + Assertions.assertEquals(clientAInstanceId + "|" + CIPluginSDKUtils.urlEncodeBase64("jobSSC1") + "|1", preFlightRequestCollectors.get(spIdA).getFirst()); // // III @@ -154,7 +158,7 @@ private void validateRunResult() throws IOException, IssuesValidate.SSCTestFailu throw new RuntimeException("Unexpected push to octane was performed"); } }else { - String octaneIssues = this.pushVulnerabilitiesCollectors.get(spIdA).get(0); + String octaneIssues = this.pushVulnerabilitiesCollectors.get(spIdA).getFirst(); IssuesValidate validate = new IssuesValidate(); validate.validateOutput(octaneIssues, this.expectedOutput); } @@ -170,50 +174,52 @@ private Map initSPEPSimulatorsForSSC( OctaneSPEndpointSimulator simulator = OctaneSPEndpointSimulator.addInstance(spID); // vulnerabilities preflight API - simulator.installApiHandler(HttpMethod.GET, "^.*/vulnerabilities/preflight$", request -> { + simulator.installApiHandler(HttpMethod.GET, "^.*/vulnerabilities/preflight$", (request, response) -> { try { // retrieve query parameters - request.mergeQueryParameters("", request.getQueryString()); + String instanceId = Request.getParameters(request).getValue("instance-id"); + String jobCiId = Request.getParameters(request).getValue("job-ci-id"); + String buildCiId = Request.getParameters(request).getValue("build-ci-id"); preflightRequestsCollectors .computeIfAbsent(spID, sid -> new LinkedList<>()) - .add(request.getQueryParameters().getString("instance-id") + "|" + - request.getQueryParameters().getString("job-ci-id") + "|" + - request.getQueryParameters().getString("build-ci-id")); - request.getResponse().setStatus(HttpStatus.SC_OK); + .add(instanceId + "|" + jobCiId + "|" + buildCiId); + response.setStatus(HttpStatus.SC_OK); SimpleDateFormat simpleDateFormat = new SimpleDateFormat(DateUtils.octaneFormat); - request.getResponse().getWriter().write(getOctaneInput().baseline == null ? "true" : - simpleDateFormat.format(getOctaneInput().baseline)); - request.getResponse().getWriter().flush(); - } catch (IOException ioe) { - throw new OctaneSDKGeneralException("failed to write response", ioe); + String responseBody = getOctaneInput().baseline == null ? "true" : + simpleDateFormat.format(getOctaneInput().baseline); + response.getHeaders().put("Content-Type", "text/plain"); + System.out.println("PREFLTDBG writing body=" + responseBody); + OctaneSPEndpointSimulator.writeResponseBody(response, responseBody); + System.out.println("PREFLTDBG wrote body"); + } catch (Exception e) { + System.out.println("PREFLTDBG EXCEPTION " + e); + throw new OctaneSDKGeneralException("failed to write response", e); } }); // vulnerabilities push API - simulator.installApiHandler(HttpMethod.POST, "^.*/vulnerabilities$", request -> { + simulator.installApiHandler(HttpMethod.POST, "^.*/vulnerabilities$", (request, response) -> { try { - String rawVulnerabilitiesBody = CIPluginSDKUtils.inputStreamToUTF8String(new GZIPInputStream(request.getInputStream())); + String rawVulnerabilitiesBody = OctaneSPEndpointSimulator.readRequestBody(request); pushRequestCollectors .computeIfAbsent(spID, sid -> new LinkedList<>()) .add(rawVulnerabilitiesBody); - request.getResponse().setStatus(HttpStatus.SC_ACCEPTED); - request.getResponse().getWriter().write("{\"status\": \"queued\"}"); - request.getResponse().getWriter().flush(); - } catch (IOException ioe) { + response.setStatus(HttpStatus.SC_ACCEPTED); + response.getHeaders().put("Content-Type", "application/json"); + OctaneSPEndpointSimulator.writeResponseBody(response, "{\"status\": \"queued\"}"); + } catch (Exception ioe) { throw new OctaneSDKGeneralException("failed to write response", ioe); } }); // vulnerabilities push API - simulator.installApiHandler(HttpMethod.GET, "^.*/vulnerabilities/remote-issue-ids.*", request -> { + simulator.installApiHandler(HttpMethod.GET, "^.*/vulnerabilities/remote-issue-ids.*", (request, response) -> { try { - - request.getResponse().setStatus(HttpStatus.SC_OK); - - request.getResponse().getWriter().write(SSCTestUtils.getJson(this.getOctaneInput().remoteIds)); - request.getResponse().getWriter().flush(); - } catch (IOException ioe) { + response.setStatus(HttpStatus.SC_OK); + response.getHeaders().put("Content-Type", "application/json"); + OctaneSPEndpointSimulator.writeResponseBody(response, SSCTestUtils.getJson(this.getOctaneInput().remoteIds)); + } catch (Exception ioe) { throw new OctaneSDKGeneralException("failed to write response", ioe); } }); diff --git a/integrations-sdk/src/test/java/com/hp/octane/integrations/services/vulnerabilities/SSCProjectConnectorPagingTest.java b/integrations-sdk/src/test/java/com/hp/octane/integrations/services/vulnerabilities/SSCProjectConnectorPagingTest.java index 36192aca..f95ed41d 100644 --- a/integrations-sdk/src/test/java/com/hp/octane/integrations/services/vulnerabilities/SSCProjectConnectorPagingTest.java +++ b/integrations-sdk/src/test/java/com/hp/octane/integrations/services/vulnerabilities/SSCProjectConnectorPagingTest.java @@ -36,8 +36,8 @@ import com.hp.octane.integrations.services.vulnerabilities.mocks.DummyContents; import com.hp.octane.integrations.services.vulnerabilities.mocks.MockSSCRestClient; import com.hp.octane.integrations.services.vulnerabilities.ssc.dto.Issues; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.util.Arrays; @@ -57,10 +57,10 @@ public void pagingOfIssues(){ DummyContents.issuesPart2, DummyContents.issuesPart3))); Issues issues = sscProjectConnector.readIssues(1); - Assert.assertEquals(3,issues.getCount()); - Assert.assertEquals("Issue 1",issues.getData().get(0).issueName); - Assert.assertEquals("Issue 2",issues.getData().get(1).issueName); - Assert.assertEquals("Issue 3",issues.getData().get(2).issueName); + Assertions.assertEquals(3,issues.getCount()); + Assertions.assertEquals("Issue 1",issues.getData().getFirst().issueName); + Assertions.assertEquals("Issue 2",issues.getData().get(1).issueName); + Assertions.assertEquals("Issue 3",issues.getData().get(2).issueName); } diff --git a/integrations-sdk/src/test/java/com/hp/octane/integrations/services/vulnerabilities/VulnerabilitiesServiceFunctionalityTest.java b/integrations-sdk/src/test/java/com/hp/octane/integrations/services/vulnerabilities/VulnerabilitiesServiceFunctionalityTest.java index d345b231..4fedd8d7 100644 --- a/integrations-sdk/src/test/java/com/hp/octane/integrations/services/vulnerabilities/VulnerabilitiesServiceFunctionalityTest.java +++ b/integrations-sdk/src/test/java/com/hp/octane/integrations/services/vulnerabilities/VulnerabilitiesServiceFunctionalityTest.java @@ -46,10 +46,15 @@ import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.eclipse.jetty.http.HttpMethod; -import org.junit.Assert; -import org.junit.Test; +import org.eclipse.jetty.io.Content; +import org.eclipse.jetty.server.Request; +import org.eclipse.jetty.util.Callback; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; import java.io.IOException; +import java.nio.charset.StandardCharsets; import java.util.Collection; import java.util.LinkedHashMap; import java.util.LinkedList; @@ -57,12 +62,13 @@ import java.util.Map; import java.util.Set; import java.util.UUID; +import java.util.zip.GZIPInputStream; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.*; +import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import java.util.stream.Stream; -import java.util.zip.GZIPInputStream; /** * Octane SDK functional sanity test @@ -74,7 +80,8 @@ public class VulnerabilitiesServiceFunctionalityTest { private static final Logger logger = LogManager.getLogger(VulnerabilitiesServiceFunctionalityTest.class); - @Test(timeout = 20000) + @Test + @Timeout(value = 20000, unit = TimeUnit.MILLISECONDS) public void testVulnerabilitiesFunctional() { Map simulators = null; @@ -99,8 +106,8 @@ public void testVulnerabilitiesFunctional() { OctaneConfiguration configA = new OctaneConfigurationIntern(clientAInstanceId, OctaneSPEndpointSimulator.getSimulatorUrl(), spIdA); OctaneClient clientA = OctaneSDK.addClient(configA, VulnerabilitiesServicePluginServicesTest.class); VulnerabilitiesService vulnerabilitiesServiceA = clientA.getVulnerabilitiesService(); - Assert.assertFalse(preflightRequestCollectors.containsKey(spIdA)); - Assert.assertFalse(preflightRequestCollectors.containsKey(spIdB)); + Assertions.assertFalse(preflightRequestCollectors.containsKey(spIdA)); + Assertions.assertFalse(preflightRequestCollectors.containsKey(spIdB)); // // II @@ -122,10 +129,10 @@ public void testVulnerabilitiesFunctional() { return null; } }); - Assert.assertEquals(clientAInstanceId + "|" + CIPluginSDKUtils.urlEncodeBase64("job-preflight-true") + "|1", preflightRequestCollectors.get(spIdA).get(0)); - Assert.assertEquals(clientAInstanceId + "|" + CIPluginSDKUtils.urlEncodeBase64("job-preflight-false") + "|1", preflightRequestCollectors.get(spIdA).get(1)); - Assert.assertEquals(clientBInstanceId + "|" + CIPluginSDKUtils.urlEncodeBase64("job-preflight-true") + "|1", preflightRequestCollectors.get(spIdB).get(0)); - Assert.assertEquals(clientBInstanceId + "|" + CIPluginSDKUtils.urlEncodeBase64("job-preflight-false") + "|1", preflightRequestCollectors.get(spIdB).get(1)); + Assertions.assertEquals(clientAInstanceId + "|" + CIPluginSDKUtils.urlEncodeBase64("job-preflight-true") + "|1", preflightRequestCollectors.get(spIdA).getFirst()); + Assertions.assertEquals(clientAInstanceId + "|" + CIPluginSDKUtils.urlEncodeBase64("job-preflight-false") + "|1", preflightRequestCollectors.get(spIdA).get(1)); + Assertions.assertEquals(clientBInstanceId + "|" + CIPluginSDKUtils.urlEncodeBase64("job-preflight-true") + "|1", preflightRequestCollectors.get(spIdB).getFirst()); + Assertions.assertEquals(clientBInstanceId + "|" + CIPluginSDKUtils.urlEncodeBase64("job-preflight-false") + "|1", preflightRequestCollectors.get(spIdB).get(1)); // // III @@ -149,7 +156,8 @@ public void testVulnerabilitiesFunctional() { } } - @Test(timeout = 20000) + @Test + @Timeout(value = 20000, unit = TimeUnit.MILLISECONDS) public void testVulnerabilitiesFunctionalSSC() { Map simulators = null; @@ -186,7 +194,7 @@ public void testVulnerabilitiesFunctionalSSC() { } }); - Assert.assertEquals(clientAInstanceId + "|" + CIPluginSDKUtils.urlEncodeBase64("jobSSC1") + "|1", preflightRequestCollectors.get(spIdA).get(0)); + Assertions.assertEquals(clientAInstanceId + "|" + CIPluginSDKUtils.urlEncodeBase64("jobSSC1") + "|1", preflightRequestCollectors.get(spIdA).getFirst()); OctaneSDK.removeClient(clientA); @@ -200,7 +208,8 @@ public void testVulnerabilitiesFunctionalSSC() { } } - @Test(timeout = 20000) + @Test + @Timeout(value = 20000, unit = TimeUnit.MILLISECONDS) public void testABUpdatedCClosedDMissingENewNoBaseline() throws IOException { Issues.Issue issueA = new Issues.Issue(); @@ -243,10 +252,11 @@ public void testABUpdatedCClosedDMissingENewNoBaseline() throws IOException { expectedPushToOctane); String errorMsg = sscIntegrationTest.runAndGetErrorMsg(); - Assert.assertNull(errorMsg); + Assertions.assertNull(errorMsg); } - @Test(timeout = 20000) + @Test + @Timeout(value = 20000, unit = TimeUnit.MILLISECONDS) public void testABUpdatedCClosedDMissingENewFGBeforeBaseline() throws IOException { @@ -311,10 +321,11 @@ public void testABUpdatedCClosedDMissingENewFGBeforeBaseline() throws IOExceptio expectedPushToOctane); String errorMsg = sscIntegrationTest.runAndGetErrorMsg(); - Assert.assertNull(errorMsg); + Assertions.assertNull(errorMsg); } - @Test(timeout = 20000) + @Test + @Timeout(value = 20000, unit = TimeUnit.MILLISECONDS) public void testABDMissingENewFGBeforeBaseline() throws IOException { @@ -377,10 +388,11 @@ public void testABDMissingENewFGBeforeBaseline() throws IOException { SSCIntegrationTest sscIntegrationTest = new SSCIntegrationTest(octaneInput, sscInput, expectedPushToOctane); String errorMsg = sscIntegrationTest.runAndGetErrorMsg(); - Assert.assertNull(errorMsg); + Assertions.assertNull(errorMsg); } - @Test(timeout = 20000) + @Test + @Timeout(value = 20000, unit = TimeUnit.MILLISECONDS) public void testABCClosedENEW() throws IOException { @@ -407,10 +419,11 @@ public void testABCClosedENEW() throws IOException { SSCIntegrationTest sscIntegrationTest = new SSCIntegrationTest(octaneInput, sscInput, expectedPushToOctane); String errorMsg = sscIntegrationTest.runAndGetErrorMsg(); - Assert.assertNull(errorMsg); + Assertions.assertNull(errorMsg); } - @Test(timeout = 20000) + @Test + @Timeout(value = 20000, unit = TimeUnit.MILLISECONDS) public void testNoPushToOctane() throws IOException { @@ -426,7 +439,7 @@ public void testNoPushToOctane() throws IOException { SSCIntegrationTest sscIntegrationTest = new SSCIntegrationTest(octaneInput, sscInput, expectedPushToOctane); String errorMsg = sscIntegrationTest.runAndGetErrorMsg(); - Assert.assertNull(errorMsg); + Assertions.assertNull(errorMsg); } private Map initSPEPSimulators( @@ -439,33 +452,38 @@ private Map initSPEPSimulators( OctaneSPEndpointSimulator simulator = OctaneSPEndpointSimulator.addInstance(spID); // vulnerabilities preflight API - simulator.installApiHandler(HttpMethod.GET, "^.*/vulnerabilities/preflight$", request -> { + simulator.installApiHandler(HttpMethod.GET, "^.*/vulnerabilities/preflight$", (request, response) -> { try { // retrieve query parameters - request.mergeQueryParameters("", request.getQueryString()); + String instanceId = Request.getParameters(request).getValue("instance-id"); + String jobCiId = Request.getParameters(request).getValue("job-ci-id"); + String buildCiId = Request.getParameters(request).getValue("build-ci-id"); preflightRequestsCollectors .computeIfAbsent(spID, sid -> new LinkedList<>()) - .add(request.getQueryParameters().getString("instance-id") + "|" + - request.getQueryParameters().getString("job-ci-id") + "|" + - request.getQueryParameters().getString("build-ci-id")); - request.getResponse().setStatus(HttpStatus.SC_OK); - request.getResponse().getWriter().write(request.getQueryParameters().getString("job-ci-id").contains("true") ? "true" : "false"); - request.getResponse().getWriter().flush(); - } catch (IOException ioe) { - throw new OctaneSDKGeneralException("failed to write response", ioe); + .add(instanceId + "|" + jobCiId + "|" + buildCiId); + response.setStatus(HttpStatus.SC_OK); + response.getHeaders().put("Content-Type", "text/plain"); + Content.Sink.write(response, true, jobCiId.contains("true") ? "true" : "false", Callback.NOOP); + } catch (Exception e) { + throw new OctaneSDKGeneralException("failed to write response", e); } }); // vulnerabilities push API - simulator.installApiHandler(HttpMethod.POST, "^.*/vulnerabilities$", request -> { + simulator.installApiHandler(HttpMethod.POST, "^.*/vulnerabilities$", (request, response) -> { try { - String rawVulnerabilitiesBody = CIPluginSDKUtils.inputStreamToUTF8String(new GZIPInputStream(request.getInputStream())); + String rawVulnerabilitiesBody = Content.Source.asString(request, StandardCharsets.UTF_8); + // Decompress if needed (if Content-Encoding is gzip) + if ("gzip".equalsIgnoreCase(request.getHeaders().get("Content-Encoding"))) { + byte[] compressed = rawVulnerabilitiesBody.getBytes(StandardCharsets.ISO_8859_1); + rawVulnerabilitiesBody = CIPluginSDKUtils.inputStreamToUTF8String(new GZIPInputStream(new java.io.ByteArrayInputStream(compressed))); + } pushRequestCollectors .computeIfAbsent(spID, sid -> new LinkedList<>()) .add(rawVulnerabilitiesBody); - request.getResponse().setStatus(HttpStatus.SC_ACCEPTED); - request.getResponse().getWriter().write("{\"status\": \"queued\"}"); - request.getResponse().getWriter().flush(); + response.setStatus(HttpStatus.SC_ACCEPTED); + response.getHeaders().put("Content-Type", "application/json"); + Content.Sink.write(response, true, "{\"status\": \"queued\"}", Callback.NOOP); } catch (IOException ioe) { throw new OctaneSDKGeneralException("failed to write response", ioe); } @@ -487,34 +505,34 @@ private Map initSPEPSimulatorsForSSC( OctaneSPEndpointSimulator simulator = OctaneSPEndpointSimulator.addInstance(spID); // vulnerabilities preflight API - simulator.installApiHandler(HttpMethod.GET, "^.*/vulnerabilities/preflight$", request -> { + simulator.installApiHandler(HttpMethod.GET, "^.*/vulnerabilities/preflight$", (request, response) -> { try { // retrieve query parameters - request.mergeQueryParameters("", request.getQueryString()); + String instanceId = Request.getParameters(request).getValue("instance-id"); + String jobCiId = Request.getParameters(request).getValue("job-ci-id"); + String buildCiId = Request.getParameters(request).getValue("build-ci-id"); preflightRequestsCollectors .computeIfAbsent(spID, sid -> new LinkedList<>()) - .add(request.getQueryParameters().getString("instance-id") + "|" + - request.getQueryParameters().getString("job-ci-id") + "|" + - request.getQueryParameters().getString("build-ci-id")); - request.getResponse().setStatus(HttpStatus.SC_OK); - request.getResponse().getWriter().write("true"); - request.getResponse().getWriter().flush(); - } catch (IOException ioe) { - throw new OctaneSDKGeneralException("failed to write response", ioe); + .add(instanceId + "|" + jobCiId + "|" + buildCiId); + response.setStatus(HttpStatus.SC_OK); + response.getHeaders().put("Content-Type", "text/plain"); + OctaneSPEndpointSimulator.writeResponseBody(response, "true"); + } catch (Exception e) { + throw new OctaneSDKGeneralException("failed to write response", e); } }); // vulnerabilities push API - simulator.installApiHandler(HttpMethod.POST, "^.*/vulnerabilities$", request -> { + simulator.installApiHandler(HttpMethod.POST, "^.*/vulnerabilities$", (request, response) -> { try { - String rawVulnerabilitiesBody = CIPluginSDKUtils.inputStreamToUTF8String(new GZIPInputStream(request.getInputStream())); + String rawVulnerabilitiesBody = OctaneSPEndpointSimulator.readRequestBody(request); pushRequestCollectors .computeIfAbsent(spID, sid -> new LinkedList<>()) .add(rawVulnerabilitiesBody); - request.getResponse().setStatus(HttpStatus.SC_ACCEPTED); - request.getResponse().getWriter().write("{\"status\": \"queued\"}"); - request.getResponse().getWriter().flush(); - } catch (IOException ioe) { + response.setStatus(HttpStatus.SC_ACCEPTED); + response.getHeaders().put("Content-Type", "application/json"); + OctaneSPEndpointSimulator.writeResponseBody(response, "{\"status\": \"queued\"}"); + } catch (Exception ioe) { throw new OctaneSDKGeneralException("failed to write response", ioe); } }); @@ -554,5 +572,4 @@ private void removeSPEPSimulators(Collection simulato } } } -} - +} \ No newline at end of file diff --git a/integrations-sdk/src/test/java/com/hp/octane/integrations/services/vulnerabilities/VulnerabilitiesServiceNegativeTests.java b/integrations-sdk/src/test/java/com/hp/octane/integrations/services/vulnerabilities/VulnerabilitiesServiceNegativeTests.java index 341b514e..fdf00125 100644 --- a/integrations-sdk/src/test/java/com/hp/octane/integrations/services/vulnerabilities/VulnerabilitiesServiceNegativeTests.java +++ b/integrations-sdk/src/test/java/com/hp/octane/integrations/services/vulnerabilities/VulnerabilitiesServiceNegativeTests.java @@ -36,97 +36,113 @@ import com.hp.octane.integrations.dto.general.CIPluginInfo; import com.hp.octane.integrations.dto.general.CIServerInfo; import com.hp.octane.integrations.services.queueing.QueueingService; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.util.UUID; +import static org.junit.jupiter.api.Assertions.assertThrows; + public class VulnerabilitiesServiceNegativeTests { private static final DTOFactory dtoFactory = DTOFactory.getInstance(); - @Test(expected = IllegalArgumentException.class) + @Test public void testA() { - new VulnerabilitiesServiceImpl(null, null, null,null, null); - } + assertThrows(IllegalArgumentException.class, () -> { + new VulnerabilitiesServiceImpl(null, null, null, null, null); + }); + } - @Test(expected = ClassCastException.class) + @Test public void testB() { - new VulnerabilitiesServiceImpl( (QueueingService)new Object(), null,null,null, null); - } + assertThrows(ClassCastException.class, () -> { + new VulnerabilitiesServiceImpl((QueueingService) new Object(), null, null, null, null); + }); + } - @Test(expected = IllegalArgumentException.class) + @Test public void testC() { - VulnerabilitiesService.newInstance(null, null, null, null, null); - } + assertThrows(IllegalArgumentException.class, () -> + VulnerabilitiesService.newInstance(null, null, null, null, null)); + } - @Test(expected = ClassCastException.class) + @Test public void testD() { - VulnerabilitiesService.newInstance((QueueingService)new Object(), null,null,null, null); - } + assertThrows(ClassCastException.class, () -> + VulnerabilitiesService.newInstance((QueueingService) new Object(), null, null, null, null)); + } // enqueue API negative testing validation - @Test(expected = IllegalArgumentException.class) + @Test public void testE1() { - OctaneConfiguration configuration = new OctaneConfigurationIntern(UUID.randomUUID().toString(), "http://localhost:8080", UUID.randomUUID().toString()); - OctaneClient client = OctaneSDK.addClient(configuration, PluginServices.class); - Assert.assertNotNull(client); + assertThrows(IllegalArgumentException.class, () -> { + OctaneConfiguration configuration = new OctaneConfigurationIntern(UUID.randomUUID().toString(), "http://localhost:8080", UUID.randomUUID().toString()); + OctaneClient client = OctaneSDK.addClient(configuration, PluginServices.class); + Assertions.assertNotNull(client); + + VulnerabilitiesService vulnerabilitiesService = client.getVulnerabilitiesService(); + try { + vulnerabilitiesService.enqueueRetrieveAndPushVulnerabilities(null, null, ToolType.SSC, 0, 0, null, null); + } finally { + OctaneSDK.removeClient(client); + } + }); + } - VulnerabilitiesService vulnerabilitiesService = client.getVulnerabilitiesService(); - try { - vulnerabilitiesService.enqueueRetrieveAndPushVulnerabilities(null, null, ToolType.SSC,0, 0,null, null); - } finally { - OctaneSDK.removeClient(client); - } - } - - @Test(expected = IllegalArgumentException.class) + @Test public void testE2() { - OctaneConfiguration configuration = new OctaneConfigurationIntern(UUID.randomUUID().toString(), "http://localhost:8080", UUID.randomUUID().toString()); - OctaneClient client = OctaneSDK.addClient(configuration, PluginServices.class); - Assert.assertNotNull(client); + assertThrows(IllegalArgumentException.class, () -> { + OctaneConfiguration configuration = new OctaneConfigurationIntern(UUID.randomUUID().toString(), "http://localhost:8080", UUID.randomUUID().toString()); + OctaneClient client = OctaneSDK.addClient(configuration, PluginServices.class); + Assertions.assertNotNull(client); + + VulnerabilitiesService vulnerabilitiesService = client.getVulnerabilitiesService(); + try { + vulnerabilitiesService.enqueueRetrieveAndPushVulnerabilities("", null, ToolType.SSC, 0, 0, null, null); + } finally { + OctaneSDK.removeClient(client); + } + }); + } - VulnerabilitiesService vulnerabilitiesService = client.getVulnerabilitiesService(); - try { - vulnerabilitiesService.enqueueRetrieveAndPushVulnerabilities("", null, ToolType.SSC,0, 0,null, null); - } finally { - OctaneSDK.removeClient(client); - } - } - - @Test(expected = IllegalArgumentException.class) + @Test public void testE3() { - OctaneConfiguration configuration = new OctaneConfigurationIntern(UUID.randomUUID().toString(), "http://localhost:8080", UUID.randomUUID().toString()); - OctaneClient client = OctaneSDK.addClient(configuration, PluginServices.class); - Assert.assertNotNull(client); - - VulnerabilitiesService vulnerabilitiesService = client.getVulnerabilitiesService(); - try { - vulnerabilitiesService.enqueueRetrieveAndPushVulnerabilities("job-id", null, ToolType.SSC, 0, 0,null, null); - } finally { - OctaneSDK.removeClient(client); - } - } + assertThrows(IllegalArgumentException.class, () -> { + OctaneConfiguration configuration = new OctaneConfigurationIntern(UUID.randomUUID().toString(), "http://localhost:8080", UUID.randomUUID().toString()); + OctaneClient client = OctaneSDK.addClient(configuration, PluginServices.class); + Assertions.assertNotNull(client); + + VulnerabilitiesService vulnerabilitiesService = client.getVulnerabilitiesService(); + try { + vulnerabilitiesService.enqueueRetrieveAndPushVulnerabilities("job-id", null, ToolType.SSC, 0, 0, null, null); + } finally { + OctaneSDK.removeClient(client); + } + }); + } - @Test(expected = IllegalArgumentException.class) + @Test public void testE4() { - OctaneConfiguration configuration = new OctaneConfigurationIntern(UUID.randomUUID().toString(), "http://localhost:8080", UUID.randomUUID().toString()); - OctaneClient client = OctaneSDK.addClient(configuration, PluginServices.class); - Assert.assertNotNull(client); - - VulnerabilitiesService vulnerabilitiesService = client.getVulnerabilitiesService(); - try { - vulnerabilitiesService.enqueueRetrieveAndPushVulnerabilities("job-id", "", ToolType.SSC,0, 0,null, null); - } finally { - OctaneSDK.removeClient(client); - } - } + assertThrows(IllegalArgumentException.class, () -> { + OctaneConfiguration configuration = new OctaneConfigurationIntern(UUID.randomUUID().toString(), "http://localhost:8080", UUID.randomUUID().toString()); + OctaneClient client = OctaneSDK.addClient(configuration, PluginServices.class); + Assertions.assertNotNull(client); + + VulnerabilitiesService vulnerabilitiesService = client.getVulnerabilitiesService(); + try { + vulnerabilitiesService.enqueueRetrieveAndPushVulnerabilities("job-id", "", ToolType.SSC, 0, 0, null, null); + } finally { + OctaneSDK.removeClient(client); + } + }); + } // this one is the OK one @Test public void testE5() { OctaneConfiguration configuration = new OctaneConfigurationIntern(UUID.randomUUID().toString(), "http://localhost:8080", UUID.randomUUID().toString()); OctaneClient client = OctaneSDK.addClient(configuration, PluginServices.class); - Assert.assertNotNull(client); + Assertions.assertNotNull(client); VulnerabilitiesService vulnerabilitiesService = client.getVulnerabilitiesService(); try { diff --git a/integrations-sdk/src/test/java/com/hp/octane/integrations/services/vulnerabilities/VulnerabilitiesTests.java b/integrations-sdk/src/test/java/com/hp/octane/integrations/services/vulnerabilities/VulnerabilitiesTests.java index 7bde9dc9..365a2eb7 100644 --- a/integrations-sdk/src/test/java/com/hp/octane/integrations/services/vulnerabilities/VulnerabilitiesTests.java +++ b/integrations-sdk/src/test/java/com/hp/octane/integrations/services/vulnerabilities/VulnerabilitiesTests.java @@ -38,8 +38,8 @@ import com.hp.octane.integrations.services.vulnerabilities.ssc.SSCHandler; import com.hp.octane.integrations.services.vulnerabilities.ssc.dto.Issues; import com.hp.octane.integrations.services.vulnerabilities.ssc.SSCProjectConnector; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.util.Arrays; import java.util.HashMap; @@ -68,10 +68,10 @@ public void wellFormedURLS() { String artifactsURL = sscProjectConnector.getArtifactsURL(100, 1000); String urlForProjectVersion = sscProjectConnector.getURLForProjectVersion(500); - Assert.assertEquals(projectIdURL, "projects?q=name:project"); - Assert.assertEquals(newIssuesURL, "projectVersions/1/issues?showhidden=false&showremoved=false&showsuppressed=false"); - Assert.assertEquals(artifactsURL, "projectVersions/100/artifacts?limit=1000"); - Assert.assertEquals(urlForProjectVersion, "projects/500/versions?q=name:version"); + Assertions.assertEquals(projectIdURL, "projects?q=name:project"); + Assertions.assertEquals(newIssuesURL, "projectVersions/1/issues?showhidden=false&showremoved=false&showsuppressed=false"); + Assertions.assertEquals(artifactsURL, "projectVersions/100/artifacts?limit=1000"); + Assertions.assertEquals(urlForProjectVersion, "projects/500/versions?q=name:version"); } @Test @@ -94,9 +94,9 @@ public void analysisSSCToOctaneWellTransformed() { List octaneIssues = createOctaneIssues(sscIssues.getData(),"Tag", new HashMap<>()); for (int i = 0; i < 4; i++) { if (i != 3) { - Assert.assertEquals("list_node.issue_analysis_node.reviewed", octaneIssues.get(i).getAnalysis().getId()); + Assertions.assertEquals("list_node.issue_analysis_node.reviewed", octaneIssues.get(i).getAnalysis().getId()); } else { - Assert.assertNull(octaneIssues.get(i).getAnalysis()); + Assertions.assertNull(octaneIssues.get(i).getAnalysis()); } } } @@ -127,9 +127,9 @@ public void stateOctaneWellTransformed() { for (int i = 0; i < 5; i++) { if (i != 4) { - Assert.assertEquals(expectedValues[i], octaneIssues.get(i).getState().getId()); + Assertions.assertEquals(expectedValues[i], octaneIssues.get(i).getState().getId()); } else { - Assert.assertNull(octaneIssues.get(i).getState()); + Assertions.assertNull(octaneIssues.get(i).getState()); } } } @@ -145,16 +145,16 @@ public void extendedData() { issue.removedDate = "removedDate"; Issues sscIssues = new Issues(); - sscIssues.setData(Arrays.asList(issue)); + sscIssues.setData(List.of(issue)); SSCHandler sscHandler = new SSCHandler(); List octaneIssues = createOctaneIssues(sscIssues.getData(), "Tag", new HashMap<>()); - Assert.assertEquals(octaneIssues.get(0).getExtendedData().get("issueName"), "name"); - Assert.assertEquals(octaneIssues.get(0).getExtendedData().get("likelihood"), "2.5"); - Assert.assertEquals(octaneIssues.get(0).getExtendedData().get("kingdom"), "kingdom"); - Assert.assertEquals(octaneIssues.get(0).getExtendedData().get("impact"), "2.5"); - Assert.assertEquals(octaneIssues.get(0).getExtendedData().get("confidence"), "confidence"); - Assert.assertEquals(octaneIssues.get(0).getExtendedData().get("removedDate"), "removedDate"); + Assertions.assertEquals("name", octaneIssues.getFirst().getExtendedData().get("issueName")); + Assertions.assertEquals("2.5", octaneIssues.getFirst().getExtendedData().get("likelihood")); + Assertions.assertEquals("kingdom", octaneIssues.getFirst().getExtendedData().get("kingdom")); + Assertions.assertEquals("2.5", octaneIssues.getFirst().getExtendedData().get("impact")); + Assertions.assertEquals("confidence", octaneIssues.getFirst().getExtendedData().get("confidence")); + Assertions.assertEquals("removedDate", octaneIssues.getFirst().getExtendedData().get("removedDate")); } @Test @@ -171,75 +171,77 @@ public void simpleFields() { SSCHandler sscHandler = new SSCHandler(); List octaneIssues = createOctaneIssues(sscIssues.getData(),"Tag", new HashMap<>()); - Assert.assertEquals(octaneIssues.get(0).getPrimaryLocationFull(), "fullFileName"); - Assert.assertEquals(String.valueOf(octaneIssues.get(0).getLine()), String.valueOf(100)); - Assert.assertEquals(octaneIssues.get(0).getRemoteId(), "ID_ID_ID"); - Assert.assertNotNull(octaneIssues.get(0).getIntroducedDate()); - Assert.assertEquals(octaneIssues.get(0).getExternalLink(), "hRef"); + Assertions.assertEquals(octaneIssues.getFirst().getPrimaryLocationFull(), "fullFileName"); + Assertions.assertEquals(String.valueOf(octaneIssues.getFirst().getLine()), String.valueOf(100)); + Assertions.assertEquals(octaneIssues.getFirst().getRemoteId(), "ID_ID_ID"); + Assertions.assertNotNull(octaneIssues.getFirst().getIntroducedDate()); + Assertions.assertEquals(octaneIssues.getFirst().getExternalLink(), "hRef"); } @Test public void deserializeIssues(){ Issues issues = SSCProjectConnector.stringToObject(sampleSSCIssues, Issues.class); - Assert.assertEquals(1,issues.getCount()); - Assert.assertEquals(1,issues.getData().size()); - Assert.assertEquals("pom.xml",issues.getData().get(0).fullFileName); + Assertions.assertEquals(1,issues.getCount()); + Assertions.assertEquals(1,issues.getData().size()); + Assertions.assertEquals("pom.xml",issues.getData().getFirst().fullFileName); } - private final String sampleSSCIssues = "{\n"+ - " \"data\": [\n"+ - " {\n"+ - " \"bugURL\": null,\n"+ - " \"hidden\": false,\n"+ - " \"issueName\": \"Build Misconfiguration: External Maven Dependency Repository\",\n"+ - " \"folderGuid\": \"bb824e8d-b401-40be-13bd-5d156696a685\",\n"+ - " \"lastScanId\": 155,\n"+ - " \"engineType\": \"SCA\",\n"+ - " \"issueStatus\": \"Unreviewed\",\n"+ - " \"friority\": \"Low\",\n"+ - " \"analyzer\": \"Configuration\",\n"+ - " \"primaryLocation\": \"pom.xml\",\n"+ - " \"reviewed\": null,\n"+ - " \"id\": 3708,\n"+ - " \"suppressed\": false,\n"+ - " \"hasAttachments\": false,\n"+ - " \"engineCategory\": \"STATIC\",\n"+ - " \"projectVersionName\": null,\n"+ - " \"removedDate\": null,\n"+ - " \"severity\": 2.0,\n"+ - " \"_href\": \"http://myd-vma00564.swinfra.net:8180/ssc/api/v1/projectVersions/116/issues/3708\",\n"+ - " \"displayEngineType\": \"SCA\",\n"+ - " \"foundDate\": \"2018-10-09T07:43:16.000+0000\",\n"+ - " \"confidence\": 5.0,\n"+ - " \"impact\": 2.0,\n"+ - " \"primaryRuleGuid\": \"FF57412F-DD28-44DE-8F4F-0AD39620768C\",\n"+ - " \"projectVersionId\": 116,\n"+ - " \"scanStatus\": \"UPDATED\",\n"+ - " \"audited\": false,\n"+ - " \"kingdom\": \"Environment\",\n"+ - " \"folderId\": 215,\n"+ - " \"revision\": 0,\n"+ - " \"likelihood\": 0.8,\n"+ - " \"removed\": false,\n"+ - " \"issueInstanceId\": \"87E3EC5CC8154C006783CC461A6DDEEB\",\n"+ - " \"hasCorrelatedIssues\": false,\n"+ - " \"primaryTag\": null,\n"+ - " \"lineNumber\": 3,\n"+ - " \"projectName\": null,\n"+ - " \"fullFileName\": \"pom.xml\",\n"+ - " \"primaryTagValueAutoApplied\": false\n"+ - " }\n"+ - " ],\n"+ - " \"count\": 1,\n"+ - " \"responseCode\": 200,\n"+ - " \"links\": {\n"+ - " \"last\": {\n"+ - " \"href\": \"http://myd-vma00564.swinfra.net:8180/ssc/api/v1/projectVersions/116/issues?q=[issue_age]:updated&qm=issues&showhidden=false&showremoved=false&showsuppressed=false&start=0\"\n"+ - " },\n"+ - " \"first\": {\n"+ - " \"href\": \"http://myd-vma00564.swinfra.net:8180/ssc/api/v1/projectVersions/116/issues?q=[issue_age]:updated&qm=issues&showhidden=false&showremoved=false&showsuppressed=false&start=0\"\n"+ - " }\n"+ - " }\n"+ - "}"; -} + private final String sampleSSCIssues = """ + { + "data": [ + { + "bugURL": null, + "hidden": false, + "issueName": "Build Misconfiguration: External Maven Dependency Repository", + "folderGuid": "bb824e8d-b401-40be-13bd-5d156696a685", + "lastScanId": 155, + "engineType": "SCA", + "issueStatus": "Unreviewed", + "friority": "Low", + "analyzer": "Configuration", + "primaryLocation": "pom.xml", + "reviewed": null, + "id": 3708, + "suppressed": false, + "hasAttachments": false, + "engineCategory": "STATIC", + "projectVersionName": null, + "removedDate": null, + "severity": 2.0, + "_href": "http://myd-vma00564.swinfra.net:8180/ssc/api/v1/projectVersions/116/issues/3708", + "displayEngineType": "SCA", + "foundDate": "2018-10-09T07:43:16.000+0000", + "confidence": 5.0, + "impact": 2.0, + "primaryRuleGuid": "FF57412F-DD28-44DE-8F4F-0AD39620768C", + "projectVersionId": 116, + "scanStatus": "UPDATED", + "audited": false, + "kingdom": "Environment", + "folderId": 215, + "revision": 0, + "likelihood": 0.8, + "removed": false, + "issueInstanceId": "87E3EC5CC8154C006783CC461A6DDEEB", + "hasCorrelatedIssues": false, + "primaryTag": null, + "lineNumber": 3, + "projectName": null, + "fullFileName": "pom.xml", + "primaryTagValueAutoApplied": false + } + ], + "count": 1, + "responseCode": 200, + "links": { + "last": { + "href": "http://myd-vma00564.swinfra.net:8180/ssc/api/v1/projectVersions/116/issues?q=[issue_age]:updated&qm=issues&showhidden=false&showremoved=false&showsuppressed=false&start=0" + }, + "first": { + "href": "http://myd-vma00564.swinfra.net:8180/ssc/api/v1/projectVersions/116/issues?q=[issue_age]:updated&qm=issues&showhidden=false&showremoved=false&showsuppressed=false&start=0" + } + } + }\ + """; +} \ No newline at end of file diff --git a/integrations-sdk/src/test/java/com/hp/octane/integrations/services/vulnerabilities/mocks/DummyContents.java b/integrations-sdk/src/test/java/com/hp/octane/integrations/services/vulnerabilities/mocks/DummyContents.java index eebd23cb..d644137d 100644 --- a/integrations-sdk/src/test/java/com/hp/octane/integrations/services/vulnerabilities/mocks/DummyContents.java +++ b/integrations-sdk/src/test/java/com/hp/octane/integrations/services/vulnerabilities/mocks/DummyContents.java @@ -32,171 +32,177 @@ package com.hp.octane.integrations.services.vulnerabilities.mocks; public class DummyContents { - public static final String issuesPart1 = "{\n"+ - " \"data\": [\n"+ - " {\n"+ - " \"bugURL\": null,\n"+ - " \"hidden\": false,\n"+ - " \"issueName\": \"Issue 1\",\n"+ - " \"folderGuid\": \"bb824e8d-b401-40be-13bd-5d156696a685\",\n"+ - " \"lastScanId\": 155,\n"+ - " \"engineType\": \"SCA\",\n"+ - " \"issueStatus\": \"Unreviewed\",\n"+ - " \"friority\": \"Low\",\n"+ - " \"analyzer\": \"Configuration\",\n"+ - " \"primaryLocation\": \"pom.xml\",\n"+ - " \"reviewed\": null,\n"+ - " \"id\": 3708,\n"+ - " \"suppressed\": false,\n"+ - " \"hasAttachments\": false,\n"+ - " \"engineCategory\": \"STATIC\",\n"+ - " \"projectVersionName\": null,\n"+ - " \"removedDate\": null,\n"+ - " \"severity\": 2.0,\n"+ - " \"_href\": \"http://myd-vma00564.swinfra.net:8180/ssc/api/v1/projectVersions/116/issues/3708\",\n"+ - " \"displayEngineType\": \"SCA\",\n"+ - " \"foundDate\": \"2018-10-09T07:43:16.000+0000\",\n"+ - " \"confidence\": 5.0,\n"+ - " \"impact\": 2.0,\n"+ - " \"primaryRuleGuid\": \"FF57412F-DD28-44DE-8F4F-0AD39620768C\",\n"+ - " \"projectVersionId\": 116,\n"+ - " \"scanStatus\": \"UPDATED\",\n"+ - " \"audited\": false,\n"+ - " \"kingdom\": \"Environment\",\n"+ - " \"folderId\": 215,\n"+ - " \"revision\": 0,\n"+ - " \"likelihood\": 0.8,\n"+ - " \"removed\": false,\n"+ - " \"issueInstanceId\": \"87E3EC5CC8154C006783CC461A6DDEEB\",\n"+ - " \"hasCorrelatedIssues\": false,\n"+ - " \"primaryTag\": null,\n"+ - " \"lineNumber\": 3,\n"+ - " \"projectName\": null,\n"+ - " \"fullFileName\": \"pom.xml\",\n"+ - " \"primaryTagValueAutoApplied\": false\n"+ - " }\n"+ - " ],\n"+ - " \"count\": 3,\n"+ - " \"responseCode\": 200,\n"+ - " \"links\": {\n"+ - " \"last\": {\n"+ - " \"href\": \"http://myd-vma00564.swinfra.net:8180/ssc/api/v1/projectVersions/116/issues?q=[issue_age]:updated&qm=issues&showhidden=false&showremoved=false&showsuppressed=false&start=0\"\n"+ - " },\n"+ - " \"first\": {\n"+ - " \"href\": \"http://myd-vma00564.swinfra.net:8180/ssc/api/v1/projectVersions/116/issues?q=[issue_age]:updated&qm=issues&showhidden=false&showremoved=false&showsuppressed=false&start=0\"\n"+ - " }\n"+ - " }\n"+ - "}"; + public static final String issuesPart1 = """ + { + "data": [ + { + "bugURL": null, + "hidden": false, + "issueName": "Issue 1", + "folderGuid": "bb824e8d-b401-40be-13bd-5d156696a685", + "lastScanId": 155, + "engineType": "SCA", + "issueStatus": "Unreviewed", + "friority": "Low", + "analyzer": "Configuration", + "primaryLocation": "pom.xml", + "reviewed": null, + "id": 3708, + "suppressed": false, + "hasAttachments": false, + "engineCategory": "STATIC", + "projectVersionName": null, + "removedDate": null, + "severity": 2.0, + "_href": "http://myd-vma00564.swinfra.net:8180/ssc/api/v1/projectVersions/116/issues/3708", + "displayEngineType": "SCA", + "foundDate": "2018-10-09T07:43:16.000+0000", + "confidence": 5.0, + "impact": 2.0, + "primaryRuleGuid": "FF57412F-DD28-44DE-8F4F-0AD39620768C", + "projectVersionId": 116, + "scanStatus": "UPDATED", + "audited": false, + "kingdom": "Environment", + "folderId": 215, + "revision": 0, + "likelihood": 0.8, + "removed": false, + "issueInstanceId": "87E3EC5CC8154C006783CC461A6DDEEB", + "hasCorrelatedIssues": false, + "primaryTag": null, + "lineNumber": 3, + "projectName": null, + "fullFileName": "pom.xml", + "primaryTagValueAutoApplied": false + } + ], + "count": 3, + "responseCode": 200, + "links": { + "last": { + "href": "http://myd-vma00564.swinfra.net:8180/ssc/api/v1/projectVersions/116/issues?q=[issue_age]:updated&qm=issues&showhidden=false&showremoved=false&showsuppressed=false&start=0" + }, + "first": { + "href": "http://myd-vma00564.swinfra.net:8180/ssc/api/v1/projectVersions/116/issues?q=[issue_age]:updated&qm=issues&showhidden=false&showremoved=false&showsuppressed=false&start=0" + } + } + }\ + """; - public static final String issuesPart2 = "{\n"+ - " \"data\": [\n"+ - " {\n"+ - " \"bugURL\": null,\n"+ - " \"hidden\": false,\n"+ - " \"issueName\": \"Issue 2\",\n"+ - " \"folderGuid\": \"bb824e8d-b401-40be-13bd-5d156696a686\",\n"+ - " \"lastScanId\": 155,\n"+ - " \"engineType\": \"SCA\",\n"+ - " \"issueStatus\": \"Unreviewed\",\n"+ - " \"friority\": \"Low\",\n"+ - " \"analyzer\": \"Configuration\",\n"+ - " \"primaryLocation\": \"pom.xml\",\n"+ - " \"reviewed\": null,\n"+ - " \"id\": 3708,\n"+ - " \"suppressed\": false,\n"+ - " \"hasAttachments\": false,\n"+ - " \"engineCategory\": \"STATIC\",\n"+ - " \"projectVersionName\": null,\n"+ - " \"removedDate\": null,\n"+ - " \"severity\": 2.0,\n"+ - " \"_href\": \"http://myd-vma00564.swinfra.net:8180/ssc/api/v1/projectVersions/116/issues/3708\",\n"+ - " \"displayEngineType\": \"SCA\",\n"+ - " \"foundDate\": \"2018-10-09T07:43:16.000+0000\",\n"+ - " \"confidence\": 5.0,\n"+ - " \"impact\": 2.0,\n"+ - " \"primaryRuleGuid\": \"FF57412F-DD28-44DE-8F4F-0AD39620768C\",\n"+ - " \"projectVersionId\": 116,\n"+ - " \"scanStatus\": \"UPDATED\",\n"+ - " \"audited\": false,\n"+ - " \"kingdom\": \"Environment\",\n"+ - " \"folderId\": 215,\n"+ - " \"revision\": 0,\n"+ - " \"likelihood\": 0.8,\n"+ - " \"removed\": false,\n"+ - " \"issueInstanceId\": \"87E3EC5CC8154C006783CC461A6DDEEB\",\n"+ - " \"hasCorrelatedIssues\": false,\n"+ - " \"primaryTag\": null,\n"+ - " \"lineNumber\": 3,\n"+ - " \"projectName\": null,\n"+ - " \"fullFileName\": \"pom.xml\",\n"+ - " \"primaryTagValueAutoApplied\": false\n"+ - " }\n"+ - " ],\n"+ - " \"count\": 3,\n"+ - " \"responseCode\": 200,\n"+ - " \"links\": {\n"+ - " \"last\": {\n"+ - " \"href\": \"http://myd-vma00564.swinfra.net:8180/ssc/api/v1/projectVersions/116/issues?q=[issue_age]:updated&qm=issues&showhidden=false&showremoved=false&showsuppressed=false&start=0\"\n"+ - " },\n"+ - " \"first\": {\n"+ - " \"href\": \"http://myd-vma00564.swinfra.net:8180/ssc/api/v1/projectVersions/116/issues?q=[issue_age]:updated&qm=issues&showhidden=false&showremoved=false&showsuppressed=false&start=0\"\n"+ - " }\n"+ - " }\n"+ - "}"; + public static final String issuesPart2 = """ + { + "data": [ + { + "bugURL": null, + "hidden": false, + "issueName": "Issue 2", + "folderGuid": "bb824e8d-b401-40be-13bd-5d156696a686", + "lastScanId": 155, + "engineType": "SCA", + "issueStatus": "Unreviewed", + "friority": "Low", + "analyzer": "Configuration", + "primaryLocation": "pom.xml", + "reviewed": null, + "id": 3708, + "suppressed": false, + "hasAttachments": false, + "engineCategory": "STATIC", + "projectVersionName": null, + "removedDate": null, + "severity": 2.0, + "_href": "http://myd-vma00564.swinfra.net:8180/ssc/api/v1/projectVersions/116/issues/3708", + "displayEngineType": "SCA", + "foundDate": "2018-10-09T07:43:16.000+0000", + "confidence": 5.0, + "impact": 2.0, + "primaryRuleGuid": "FF57412F-DD28-44DE-8F4F-0AD39620768C", + "projectVersionId": 116, + "scanStatus": "UPDATED", + "audited": false, + "kingdom": "Environment", + "folderId": 215, + "revision": 0, + "likelihood": 0.8, + "removed": false, + "issueInstanceId": "87E3EC5CC8154C006783CC461A6DDEEB", + "hasCorrelatedIssues": false, + "primaryTag": null, + "lineNumber": 3, + "projectName": null, + "fullFileName": "pom.xml", + "primaryTagValueAutoApplied": false + } + ], + "count": 3, + "responseCode": 200, + "links": { + "last": { + "href": "http://myd-vma00564.swinfra.net:8180/ssc/api/v1/projectVersions/116/issues?q=[issue_age]:updated&qm=issues&showhidden=false&showremoved=false&showsuppressed=false&start=0" + }, + "first": { + "href": "http://myd-vma00564.swinfra.net:8180/ssc/api/v1/projectVersions/116/issues?q=[issue_age]:updated&qm=issues&showhidden=false&showremoved=false&showsuppressed=false&start=0" + } + } + }\ + """; - public static final String issuesPart3 = "{\n"+ - " \"data\": [\n"+ - " {\n"+ - " \"bugURL\": null,\n"+ - " \"hidden\": false,\n"+ - " \"issueName\": \"Issue 3\",\n"+ - " \"folderGuid\": \"bb824e8d-b401-40be-13bd-5d156696a687\",\n"+ - " \"lastScanId\": 155,\n"+ - " \"engineType\": \"SCA\",\n"+ - " \"issueStatus\": \"Unreviewed\",\n"+ - " \"friority\": \"Low\",\n"+ - " \"analyzer\": \"Configuration\",\n"+ - " \"primaryLocation\": \"pom.xml\",\n"+ - " \"reviewed\": null,\n"+ - " \"id\": 3708,\n"+ - " \"suppressed\": false,\n"+ - " \"hasAttachments\": false,\n"+ - " \"engineCategory\": \"STATIC\",\n"+ - " \"projectVersionName\": null,\n"+ - " \"removedDate\": null,\n"+ - " \"severity\": 2.0,\n"+ - " \"_href\": \"http://myd-vma00564.swinfra.net:8180/ssc/api/v1/projectVersions/116/issues/3708\",\n"+ - " \"displayEngineType\": \"SCA\",\n"+ - " \"foundDate\": \"2018-10-09T07:43:16.000+0000\",\n"+ - " \"confidence\": 5.0,\n"+ - " \"impact\": 2.0,\n"+ - " \"primaryRuleGuid\": \"FF57412F-DD28-44DE-8F4F-0AD39620768C\",\n"+ - " \"projectVersionId\": 116,\n"+ - " \"scanStatus\": \"UPDATED\",\n"+ - " \"audited\": false,\n"+ - " \"kingdom\": \"Environment\",\n"+ - " \"folderId\": 215,\n"+ - " \"revision\": 0,\n"+ - " \"likelihood\": 0.8,\n"+ - " \"removed\": false,\n"+ - " \"issueInstanceId\": \"87E3EC5CC8154C006783CC461A6DDEEB\",\n"+ - " \"hasCorrelatedIssues\": false,\n"+ - " \"primaryTag\": null,\n"+ - " \"lineNumber\": 3,\n"+ - " \"projectName\": null,\n"+ - " \"fullFileName\": \"pom.xml\",\n"+ - " \"primaryTagValueAutoApplied\": false\n"+ - " }\n"+ - " ],\n"+ - " \"count\": 3,\n"+ - " \"responseCode\": 200,\n"+ - " \"links\": {\n"+ - " \"last\": {\n"+ - " \"href\": \"http://myd-vma00564.swinfra.net:8180/ssc/api/v1/projectVersions/116/issues?q=[issue_age]:updated&qm=issues&showhidden=false&showremoved=false&showsuppressed=false&start=0\"\n"+ - " },\n"+ - " \"first\": {\n"+ - " \"href\": \"http://myd-vma00564.swinfra.net:8180/ssc/api/v1/projectVersions/116/issues?q=[issue_age]:updated&qm=issues&showhidden=false&showremoved=false&showsuppressed=false&start=0\"\n"+ - " }\n"+ - " }\n"+ - "}"; + public static final String issuesPart3 = """ + { + "data": [ + { + "bugURL": null, + "hidden": false, + "issueName": "Issue 3", + "folderGuid": "bb824e8d-b401-40be-13bd-5d156696a687", + "lastScanId": 155, + "engineType": "SCA", + "issueStatus": "Unreviewed", + "friority": "Low", + "analyzer": "Configuration", + "primaryLocation": "pom.xml", + "reviewed": null, + "id": 3708, + "suppressed": false, + "hasAttachments": false, + "engineCategory": "STATIC", + "projectVersionName": null, + "removedDate": null, + "severity": 2.0, + "_href": "http://myd-vma00564.swinfra.net:8180/ssc/api/v1/projectVersions/116/issues/3708", + "displayEngineType": "SCA", + "foundDate": "2018-10-09T07:43:16.000+0000", + "confidence": 5.0, + "impact": 2.0, + "primaryRuleGuid": "FF57412F-DD28-44DE-8F4F-0AD39620768C", + "projectVersionId": 116, + "scanStatus": "UPDATED", + "audited": false, + "kingdom": "Environment", + "folderId": 215, + "revision": 0, + "likelihood": 0.8, + "removed": false, + "issueInstanceId": "87E3EC5CC8154C006783CC461A6DDEEB", + "hasCorrelatedIssues": false, + "primaryTag": null, + "lineNumber": 3, + "projectName": null, + "fullFileName": "pom.xml", + "primaryTagValueAutoApplied": false + } + ], + "count": 3, + "responseCode": 200, + "links": { + "last": { + "href": "http://myd-vma00564.swinfra.net:8180/ssc/api/v1/projectVersions/116/issues?q=[issue_age]:updated&qm=issues&showhidden=false&showremoved=false&showsuppressed=false&start=0" + }, + "first": { + "href": "http://myd-vma00564.swinfra.net:8180/ssc/api/v1/projectVersions/116/issues?q=[issue_age]:updated&qm=issues&showhidden=false&showremoved=false&showsuppressed=false&start=0" + } + } + }\ + """; } diff --git a/integrations-sdk/src/test/java/com/hp/octane/integrations/testhelpers/OctaneSPEndpointSimulator.java b/integrations-sdk/src/test/java/com/hp/octane/integrations/testhelpers/OctaneSPEndpointSimulator.java index deecdfec..46e66ca8 100644 --- a/integrations-sdk/src/test/java/com/hp/octane/integrations/testhelpers/OctaneSPEndpointSimulator.java +++ b/integrations-sdk/src/test/java/com/hp/octane/integrations/testhelpers/OctaneSPEndpointSimulator.java @@ -36,19 +36,22 @@ import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.eclipse.jetty.http.HttpMethod; +import org.eclipse.jetty.io.Content; import org.eclipse.jetty.server.Handler; import org.eclipse.jetty.server.Request; +import org.eclipse.jetty.server.Response; import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.server.handler.AbstractHandler; -import org.eclipse.jetty.server.handler.HandlerCollection; +import org.eclipse.jetty.util.Callback; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import java.io.ByteArrayInputStream; import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; import java.util.LinkedHashMap; import java.util.Map; -import java.util.function.Consumer; +import java.util.function.BiConsumer; import java.util.regex.Pattern; +import java.util.zip.GZIPInputStream; /** * Each Octane Shared Space Endpoint simulator instance will function as an isolated context for tests targeting specific shared space @@ -56,7 +59,7 @@ * Each instance is thread and scope safe */ -public class OctaneSPEndpointSimulator extends AbstractHandler { +public class OctaneSPEndpointSimulator extends Handler.Abstract { private static final Logger logger = LogManager.getLogger(OctaneSPEndpointSimulator.class); // simulator's factory static content @@ -64,7 +67,7 @@ public class OctaneSPEndpointSimulator extends AbstractHandler { private static final int DEFAULT_PORT = 3333; private static final Map serverSimulators = new LinkedHashMap<>(); private static Server server; - private static HandlerCollection handlers; + private static Handler.Sequence handlers; private static Integer selectedPort; /** @@ -120,7 +123,7 @@ private static void startServer() { String rawPort = System.getProperty("octane.server.simulator.port"); server = new Server(rawPort == null ? (selectedPort = DEFAULT_PORT) : (selectedPort = Integer.parseInt(rawPort))); try { - handlers = new HandlerCollection(true); + handlers = new Handler.Sequence(); server.setHandler(handlers); server.start(); logger.info("SUCCESSFULLY started, listening on port " + selectedPort); @@ -134,10 +137,15 @@ private static void startServer() { // private final String API_HANDLER_KEY_JOINER = " # "; private final Pattern signInApiPattern = Pattern.compile("/authentication/sign_in"); - private final Map> apiHandlersRegistry = new LinkedHashMap<>(); + private final Map> apiHandlersRegistry = new LinkedHashMap<>(); private final String sp; private String octaneVersion = "15.1.1"; + // Jetty 12: the request callback must be passed to the async body write, otherwise the response + // is finalized before the body is flushed. We expose it to the (callback-less) API handlers via ThreadLocal. + private static final ThreadLocal CURRENT_CALLBACK = new ThreadLocal<>(); + private static final ThreadLocal RESPONSE_WRITTEN = new ThreadLocal<>(); + private OctaneSPEndpointSimulator(String sp) { this.sp = sp; @@ -153,42 +161,84 @@ public String getSharedSpaceId() { } @Override - public void handle(String s, Request request, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException { - if (request.isHandled()) { - return; - } + public boolean handle(Request request, Response response, Callback callback) throws Exception { + String pathInfo = Request.getPathInContext(request); + String method = request.getMethod(); - if (signInApiPattern.matcher(request.getPathInfo()).matches()) { - OctaneSecuritySimulationUtils.signIn(request); - return; + if (signInApiPattern.matcher(pathInfo).matches()) { + OctaneSecuritySimulationUtils.signIn(request, response); + callback.succeeded(); + return true; } - if (!OctaneSecuritySimulationUtils.authenticate(request)) { - return; + if (!OctaneSecuritySimulationUtils.authenticate(request, response)) { + callback.succeeded(); + return true; } - if (!request.getPathInfo().startsWith("/api/shared_spaces/" + sp + "/") && !s.startsWith("/internal-api/shared_spaces/" + sp + "/")) { - return; + if (!pathInfo.startsWith("/api/shared_spaces/" + sp + "/") && !pathInfo.startsWith("/internal-api/shared_spaces/" + sp + "/")) { + return false; } - apiHandlersRegistry.keySet().stream() - .filter(apiHandlerKey -> { - String[] keyParts = apiHandlerKey.split(API_HANDLER_KEY_JOINER); - return request.getMethod().compareTo(keyParts[0]) == 0 && Pattern.compile(keyParts[1]).matcher(request.getPathInfo()).matches(); + BiConsumer apiHandler = apiHandlersRegistry.entrySet().stream() + .filter(entry -> { + String[] keyParts = entry.getKey().split(API_HANDLER_KEY_JOINER); + return method.compareTo(keyParts[0]) == 0 && Pattern.compile(keyParts[1]).matcher(pathInfo).matches(); }) + .map(Map.Entry::getValue) .findFirst() - .ifPresent(apiPattern -> { - apiHandlersRegistry.get(apiPattern).accept(request); - request.setHandled(true); - }); - - if (!request.isHandled()) { - request.getResponse().setStatus(HttpStatus.SC_NOT_FOUND); - request.setHandled(true); + .orElse(null); + + if (apiHandler != null) { + CURRENT_CALLBACK.set(callback); + RESPONSE_WRITTEN.set(Boolean.FALSE); + try { + apiHandler.accept(request, response); + } finally { + boolean written = Boolean.TRUE.equals(RESPONSE_WRITTEN.get()); + CURRENT_CALLBACK.remove(); + RESPONSE_WRITTEN.remove(); + // if the handler wrote a body, the write already owns the callback; otherwise complete it here + if (!written) { + callback.succeeded(); + } + } + return true; + } + + response.setStatus(HttpStatus.SC_NOT_FOUND); + callback.succeeded(); + return true; + } + + /** + * Writes a response body and completes the current request callback (Jetty 12 async-safe). + * API handlers MUST use this instead of {@code Content.Sink.write(..., Callback.NOOP)} when returning a body. + */ + public static void writeResponseBody(Response response, String content) { + Callback cb = CURRENT_CALLBACK.get(); + RESPONSE_WRITTEN.set(Boolean.TRUE); + Content.Sink.write(response, true, content, cb != null ? cb : Callback.NOOP); + } + + /** + * Reads the full request body as a UTF-8 string, transparently gunzipping when Content-Encoding is gzip. + * Jetty 12's {@code Content.Source.asString(UTF_8)} strictly validates UTF-8 and fails on binary (gzip) bodies, + * so we read raw bytes first. + */ + public static String readRequestBody(Request request) { + try (InputStream is = Content.Source.asInputStream(request)) { + byte[] bytes = is.readAllBytes(); + if ("gzip".equalsIgnoreCase(request.getHeaders().get("Content-Encoding"))) { + return CIPluginSDKUtils.inputStreamToUTF8String(new GZIPInputStream(new ByteArrayInputStream(bytes))); + } + return new String(bytes, StandardCharsets.UTF_8); + } catch (IOException e) { + throw new RuntimeException(e); } } - public void installApiHandler(HttpMethod method, String pattern, Consumer apiHandler) { + public void installApiHandler(HttpMethod method, String pattern, BiConsumer apiHandler) { String handlerKey = method + API_HANDLER_KEY_JOINER + pattern; if (apiHandlersRegistry.containsKey(handlerKey)) { logger.warn("api handler for '" + handlerKey + "' already installed and will be replaced"); @@ -201,23 +251,18 @@ public void removeApiHandler(HttpMethod method, String pattern) { } private void installDefaultConnectivityStatusApiHandler() { - installApiHandler(HttpMethod.GET, "^.*/analytics/ci/servers/connectivity/status$", request -> { - request.getResponse().setStatus(HttpStatus.SC_OK); - try { - String msg = "{\"supportedSdkVersion\": \"1.0.0\", \"octaneVersion\": \"" + octaneVersion + "\"}"; - request.getResponse().getWriter().write(msg); - } catch (IOException e) { - e.printStackTrace(); - } - request.setHandled(true); + installApiHandler(HttpMethod.GET, "^.*/analytics/ci/servers/connectivity/status$", (request, response) -> { + response.setStatus(HttpStatus.SC_OK); + String msg = "{\"supportedSdkVersion\": \"1.0.0\", \"octaneVersion\": \"" + octaneVersion + "\"}"; + response.getHeaders().put("Content-Type", "application/json"); + writeResponseBody(response, msg); }); } private void installNOOPTasksApiHandler() { - installApiHandler(HttpMethod.GET, "^.*tasks$", request -> { + installApiHandler(HttpMethod.GET, "^.*tasks$", (request, response) -> { CIPluginSDKUtils.doWait(3000); - request.getResponse().setStatus(HttpStatus.SC_NO_CONTENT); - request.setHandled(true); + response.setStatus(HttpStatus.SC_NO_CONTENT); }); } diff --git a/integrations-sdk/src/test/java/com/hp/octane/integrations/testhelpers/OctaneSecuritySimulationUtils.java b/integrations-sdk/src/test/java/com/hp/octane/integrations/testhelpers/OctaneSecuritySimulationUtils.java index 79ec23a7..40144574 100644 --- a/integrations-sdk/src/test/java/com/hp/octane/integrations/testhelpers/OctaneSecuritySimulationUtils.java +++ b/integrations-sdk/src/test/java/com/hp/octane/integrations/testhelpers/OctaneSecuritySimulationUtils.java @@ -33,13 +33,16 @@ import com.hp.octane.integrations.utils.CIPluginSDKUtils; import org.apache.http.HttpStatus; +import org.eclipse.jetty.http.HttpCookie; +import org.eclipse.jetty.http.HttpHeader; +import org.eclipse.jetty.io.Content; import org.eclipse.jetty.server.Request; +import org.eclipse.jetty.server.Response; -import javax.servlet.http.Cookie; import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.List; import java.util.Map; -import java.util.stream.Collectors; -import java.util.stream.Stream; class OctaneSecuritySimulationUtils { private static final String SECURITY_COOKIE_NAME = "LWSSO_COOKIE_KEY"; @@ -48,42 +51,34 @@ class OctaneSecuritySimulationUtils { private OctaneSecuritySimulationUtils() { } - static void signIn(Request request) throws IOException { - String body = CIPluginSDKUtils.inputStreamToUTF8String(request.getInputStream()); + static void signIn(Request request, Response response) throws IOException { + String body = Content.Source.asString(request, StandardCharsets.UTF_8); Map json = CIPluginSDKUtils.getObjectMapper().readValue(body, Map.class); String client = (String) json.get("client_id"); String secret = (String) json.get("client_secret"); - Cookie securityCookie = createSecurityCookie(client, secret); - request.getResponse().addCookie(securityCookie); - request.setHandled(true); + response.getHeaders().add(HttpHeader.SET_COOKIE, buildSetCookieHeader(client, secret)); } - static boolean authenticate(Request request) { - if (request.getCookies() != null) { - for (Cookie cookie : request.getCookies()) { + static boolean authenticate(Request request, Response response) { + List cookies = Request.getCookies(request); + if (cookies != null) { + for (HttpCookie cookie : cookies) { if (SECURITY_COOKIE_NAME.equals(cookie.getName())) { String[] securityItems = cookie.getValue().split(SECURITY_TOKEN_SEPARATOR); long issuedAt = Long.parseLong(securityItems[2]); if (System.currentTimeMillis() - issuedAt > 2000) { - Cookie securityCookie = createSecurityCookie(securityItems[0], securityItems[1]); - request.getResponse().addCookie(securityCookie); + response.getHeaders().add(HttpHeader.SET_COOKIE, buildSetCookieHeader(securityItems[0], securityItems[1])); } return true; } } } - request.getResponse().setStatus(HttpStatus.SC_UNAUTHORIZED); - request.setHandled(true); + response.setStatus(HttpStatus.SC_UNAUTHORIZED); return false; } - static private Cookie createSecurityCookie(String client, String secret) { - Cookie result = new Cookie( - SECURITY_COOKIE_NAME, - String.join(SECURITY_TOKEN_SEPARATOR, Stream.of(client, secret, String.valueOf(System.currentTimeMillis())).collect(Collectors.toList())) - ); - result.setHttpOnly(true); - result.setDomain(".localhost"); - return result; + static private String buildSetCookieHeader(String client, String secret) { + String value = String.join(SECURITY_TOKEN_SEPARATOR, client, secret, String.valueOf(System.currentTimeMillis())); + return SECURITY_COOKIE_NAME + "=" + value + "; Path=/; HttpOnly"; } } diff --git a/integrations-sdk/src/test/java/com/hp/octane/integrations/testhelpers/RestServerSimulator.java b/integrations-sdk/src/test/java/com/hp/octane/integrations/testhelpers/RestServerSimulator.java index 012dfd39..1cba6fc0 100644 --- a/integrations-sdk/src/test/java/com/hp/octane/integrations/testhelpers/RestServerSimulator.java +++ b/integrations-sdk/src/test/java/com/hp/octane/integrations/testhelpers/RestServerSimulator.java @@ -31,34 +31,68 @@ */ package com.hp.octane.integrations.testhelpers; +import com.hp.octane.integrations.utils.CIPluginSDKUtils; import org.apache.http.HttpStatus; +import org.eclipse.jetty.io.Content; +import org.eclipse.jetty.server.Handler; import org.eclipse.jetty.server.Request; +import org.eclipse.jetty.server.Response; import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.server.handler.AbstractHandler; -import org.eclipse.jetty.server.handler.HandlerCollection; +import org.eclipse.jetty.util.Callback; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import java.io.ByteArrayInputStream; import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; -import java.util.function.Consumer; +import java.util.function.BiConsumer; import java.util.function.Predicate; import java.util.regex.Pattern; +import java.util.zip.GZIPInputStream; -public class RestServerSimulator extends AbstractHandler { +public class RestServerSimulator extends Handler.Abstract { private int selectedPort; private Server server; private List handlingRules = new ArrayList<>(); private List receivedRequests = new ArrayList<>(); + // Jetty 12: the request callback must be passed to the async body write, otherwise the response + // is finalized before the body is flushed. We expose it to the (callback-less) rule handlers via ThreadLocal. + private static final ThreadLocal CURRENT_CALLBACK = new ThreadLocal<>(); + private static final ThreadLocal RESPONSE_WRITTEN = new ThreadLocal<>(); + + /** + * Writes a response body and completes the current request callback (Jetty 12 async-safe). + * Rule handlers MUST use this instead of {@code Content.Sink.write(..., Callback.NOOP)} when returning a body. + */ + public static void writeResponseBody(Response response, String content) { + Callback cb = CURRENT_CALLBACK.get(); + RESPONSE_WRITTEN.set(Boolean.TRUE); + Content.Sink.write(response, true, content, cb != null ? cb : Callback.NOOP); + } + + /** + * Reads the full request body as a UTF-8 string, transparently gunzipping when Content-Encoding is gzip. + */ + public static String readRequestBody(Request request) { + try (InputStream is = Content.Source.asInputStream(request)) { + byte[] bytes = is.readAllBytes(); + if ("gzip".equalsIgnoreCase(request.getHeaders().get("Content-Encoding"))) { + return CIPluginSDKUtils.inputStreamToUTF8String(new GZIPInputStream(new ByteArrayInputStream(bytes))); + } + return new String(bytes, StandardCharsets.UTF_8); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + public static class RequestHandlingRule{ public String urlPattern; public Predicate condition; - public Consumer operationOnRequest; - public RequestHandlingRule(String urlPattern, Predicate cond, Consumer op){ + public BiConsumer operationOnRequest; + public RequestHandlingRule(String urlPattern, Predicate cond, BiConsumer op){ this.urlPattern = urlPattern; this.condition = cond; this.operationOnRequest = op; @@ -71,7 +105,7 @@ public RestServerSimulator(int port){ public void startServer() { - HandlerCollection handlers = new HandlerCollection(true); + Handler.Sequence handlers = new Handler.Sequence(); handlers.addHandler(this); server = new Server(selectedPort); server.setHandler(handlers); @@ -83,7 +117,7 @@ public void startServer() { } public void addRule(String urlPatter, Predicate condition, - Consumer operationOnRequest) { + BiConsumer operationOnRequest) { handlingRules.add(new RequestHandlingRule(urlPatter, condition, operationOnRequest)); } @@ -101,16 +135,19 @@ public void endSimulation(){ } @Override - public void handle(String s, Request request, - HttpServletRequest httpServletRequest, - HttpServletResponse httpServletResponse) throws IOException, ServletException { + public boolean handle(Request request, Response response, Callback callback) throws Exception { try { + // Jetty 12: getPathInContext() returns the path WITHOUT the query string. Several rule patterns + // (e.g. SSC ".../projects?q=name:...") rely on the query, so match against path + "?" + query. + String pathInContext = Request.getPathInContext(request); + String rawQuery = request.getHttpURI().getQuery(); + String matchTarget = rawQuery == null ? pathInContext : pathInContext + "?" + rawQuery; for (RequestHandlingRule handlingRule : handlingRules) { boolean urlMatch = true, requestMatch = true; if (handlingRule.urlPattern != null && - !Pattern.compile(handlingRule.urlPattern).matcher(request.getOriginalURI()).matches()) { + !Pattern.compile(handlingRule.urlPattern).matcher(matchTarget).matches()) { urlMatch = false; } if (handlingRule.condition != null && @@ -118,15 +155,26 @@ public void handle(String s, Request request, requestMatch = false; } if (urlMatch && requestMatch) { - handlingRule.operationOnRequest.accept(request); - request.setHandled(true); - break; + CURRENT_CALLBACK.set(callback); + RESPONSE_WRITTEN.set(Boolean.FALSE); + try { + handlingRule.operationOnRequest.accept(request, response); + } finally { + boolean written = Boolean.TRUE.equals(RESPONSE_WRITTEN.get()); + CURRENT_CALLBACK.remove(); + RESPONSE_WRITTEN.remove(); + // if the handler wrote a body, the write already owns the callback; otherwise complete it here + if (!written) { + callback.succeeded(); + } + } + return true; } } - if (!request.isHandled()) { - request.setHandled(true); - request.getResponse().setStatus(HttpStatus.SC_NOT_FOUND); - } + + response.setStatus(HttpStatus.SC_NOT_FOUND); + callback.succeeded(); + return true; }finally { addRequestAsReceived(request); diff --git a/integrations-sdk/src/test/java/com/hp/octane/integrations/testhelpers/SSCServerSimulator.java b/integrations-sdk/src/test/java/com/hp/octane/integrations/testhelpers/SSCServerSimulator.java index 01926a28..49627525 100644 --- a/integrations-sdk/src/test/java/com/hp/octane/integrations/testhelpers/SSCServerSimulator.java +++ b/integrations-sdk/src/test/java/com/hp/octane/integrations/testhelpers/SSCServerSimulator.java @@ -38,11 +38,13 @@ import com.hp.octane.integrations.services.vulnerabilities.ssc.dto.ProjectVersions; import com.hp.octane.integrations.services.vulnerabilities.ssc.dto.Projects; import org.apache.http.HttpStatus; +import org.eclipse.jetty.io.Content; import org.eclipse.jetty.server.Request; +import org.eclipse.jetty.server.Response; +import org.eclipse.jetty.util.Callback; -import java.io.IOException; import java.util.Arrays; -import java.util.function.Consumer; +import java.util.function.BiConsumer; public class SSCServerSimulator extends RestServerSimulator{ @@ -69,7 +71,7 @@ public static synchronized SSCServerSimulator instance(){ } public void setDefaultAuth() { - setAuthHanler(request -> { + setAuthHanler((request, response) -> { try { AuthToken.AuthTokenData authTokenData = new AuthToken.AuthTokenData(); authTokenData.token = "DUMMY TOKEN"; @@ -77,15 +79,15 @@ public void setDefaultAuth() { AuthToken authToken = new AuthToken(); authToken.setData(authTokenData); - request.getResponse().setStatus(HttpStatus.SC_OK); - request.getResponse().getWriter().write(SSCTestUtils.getJson(authToken)); - request.getResponse().getWriter().flush(); - } catch (IOException e) { - e.printStackTrace(); + response.setStatus(HttpStatus.SC_OK); + response.getHeaders().put("Content-Type", "application/json"); + Content.Sink.write(response, true, SSCTestUtils.getJson(authToken), Callback.NOOP); + } catch (Exception e) { + throw new RuntimeException("Failed to set auth", e); } }); } - public void setAuthHanler(Consumer authHandler) { + public void setAuthHanler(BiConsumer authHandler) { SSCServerSimulator.instance().addRule("^.*/api/v1/tokens.*", t->t.getMethod().equalsIgnoreCase("post"), authHandler); @@ -102,11 +104,11 @@ private void setIssueDetails() { addRule("^.*/api/v1/issueDetails/.*", t -> t.getMethod().equalsIgnoreCase("get"), - request -> { + (request, response) -> { try { - request.getResponse().setStatus(HttpStatus.SC_OK); - String originalURI = request.getOriginalURI(); - String issueId = originalURI.substring(originalURI.lastIndexOf("/")); + response.setStatus(HttpStatus.SC_OK); + String pathInContext = Request.getPathInContext(request); + String issueId = pathInContext.substring(pathInContext.lastIndexOf("/")); IssueDetails issueDetails = new IssueDetails(); IssueDetails.IssueDetailsData issueDetailsData = new IssueDetails.IssueDetailsData(); issueDetailsData.tips = "tips:" + issueId; @@ -115,10 +117,10 @@ private void setIssueDetails() { issueDetailsData.brief = "brief:" + issueId; issueDetails.setData(issueDetailsData); String json = SSCTestUtils.getJson(issueDetails); - request.getResponse().getWriter().write(json); - request.getResponse().getWriter().flush(); - } catch (IOException e) { - e.printStackTrace(); + response.getHeaders().put("Content-Type", "application/json"); + Content.Sink.write(response, true, json, Callback.NOOP); + } catch (Exception e) { + throw new RuntimeException("Failed to set issue details", e); } }); } @@ -127,14 +129,14 @@ public void setIssues(SSCInput sequence) { addRule("^.*/api/v1/projectVersions/" + sequence.projectVersionId + "/issues.*", t -> t.getMethod().equalsIgnoreCase("get"), - request -> { + (request, response) -> { try { - request.getResponse().setStatus(HttpStatus.SC_OK); + response.setStatus(HttpStatus.SC_OK); String json = SSCTestUtils.getJson(sequence.getIssuesToReturn()); - request.getResponse().getWriter().write(json); - request.getResponse().getWriter().flush(); - } catch (IOException e) { - e.printStackTrace(); + response.getHeaders().put("Content-Type", "application/json"); + Content.Sink.write(response, true, json, Callback.NOOP); + } catch (Exception e) { + throw new RuntimeException("Failed to set issues", e); } }); } @@ -143,14 +145,14 @@ public void setArtifacts(SSCInput sequence) { addRule("^.*/api/v1/projectVersions/" + sequence.projectVersionId + "/artifacts.*", t -> t.getMethod().equalsIgnoreCase("get"), - request -> { + (request, response) -> { try { - request.getResponse().setStatus(HttpStatus.SC_OK); + response.setStatus(HttpStatus.SC_OK); String json = SSCTestUtils.getJson(sequence.artifacts); - request.getResponse().getWriter().write(json); - request.getResponse().getWriter().flush(); - } catch (IOException e) { - e.printStackTrace(); + response.getHeaders().put("Content-Type", "application/json"); + Content.Sink.write(response, true, json, Callback.NOOP); + } catch (Exception e) { + throw new RuntimeException("Failed to set artifacts", e); } }); @@ -160,32 +162,35 @@ public void setProjectVersion(SSCInput sequence) { instance().addRule("^.*/api/v1/projects/"+sequence.projectId+"/versions\\?q=name:.*", t->t.getMethod().equalsIgnoreCase("get") && queryIsAboutProjectName("name",sequence.projectVersionName,t), - request-> { + (request, response) -> { try { ProjectVersions projectVersions = new ProjectVersions(); projectVersions.setCount(1); ProjectVersions.ProjectVersion projectVersion = new ProjectVersions.ProjectVersion(); projectVersion.id = sequence.projectVersionId; projectVersions.setData(Arrays.asList(projectVersion)); - request.getResponse().setStatus(HttpStatus.SC_OK); - request.getResponse().getWriter().write(SSCTestUtils.getJson(projectVersions)); - request.getResponse().getWriter().flush(); - } catch (IOException e) { - e.printStackTrace(); + response.setStatus(HttpStatus.SC_OK); + response.getHeaders().put("Content-Type", "application/json"); + Content.Sink.write(response, true, SSCTestUtils.getJson(projectVersions), Callback.NOOP); + } catch (Exception e) { + throw new RuntimeException("Failed to set project version", e); } }); } public boolean queryIsAboutProjectName(String paramName, String paramValue, Request request) { - request.mergeQueryParameters("", request.getQueryString()); - String queryString = request.getQueryParameters().getString("q"); - return queryString != null && queryString.substring((paramName + ":").length()).startsWith(paramValue); + try { + String queryString = Request.getParameters(request).getValue("q"); + return queryString != null && queryString.substring((paramName + ":").length()).startsWith(paramValue); + } catch (Exception e) { + return false; + } } public void setProject(SSCInput sequence) { addRule("^.*/api/v1/projects\\?q=name:.*", t->t.getMethod().equalsIgnoreCase("get") && queryIsAboutProjectName("name",sequence.projectName, t), - request-> { + (request, response) -> { try { Projects projects = new Projects(); projects.setCount(1); @@ -193,12 +198,13 @@ public void setProject(SSCInput sequence) { project.id = sequence.projectId; project.name = sequence.projectName; projects.setData(Arrays.asList(project)); - request.getResponse().setStatus(HttpStatus.SC_OK); - request.getResponse().getWriter().write(SSCTestUtils.getJson(projects)); - request.getResponse().getWriter().flush(); - } catch (IOException e) { - e.printStackTrace(); + response.setStatus(HttpStatus.SC_OK); + response.getHeaders().put("Content-Type", "application/json"); + RestServerSimulator.writeResponseBody(response, SSCTestUtils.getJson(projects)); + } catch (Exception e) { + throw new RuntimeException("Failed to set project", e); } }); } } + diff --git a/integrations-sdk/src/test/java/com/hp/octane/integrations/uft/items/UftUtilsTests.java b/integrations-sdk/src/test/java/com/hp/octane/integrations/uft/items/UftUtilsTests.java index f895a675..f1cfad19 100644 --- a/integrations-sdk/src/test/java/com/hp/octane/integrations/uft/items/UftUtilsTests.java +++ b/integrations-sdk/src/test/java/com/hp/octane/integrations/uft/items/UftUtilsTests.java @@ -32,19 +32,19 @@ package com.hp.octane.integrations.uft.items; import com.hp.octane.integrations.uft.UftTestDiscoveryUtils; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; public class UftUtilsTests { @Test public void UftTestDiscoveryUtilsConvertToHtmlFormatIfRequired1() { - Assert.assertEquals("aa",UftTestDiscoveryUtils.convertToHtmlFormatIfRequired("aa")); + Assertions.assertEquals("aa",UftTestDiscoveryUtils.convertToHtmlFormatIfRequired("aa")); } @Test public void UftTestDiscoveryUtilsConvertToHtmlFormatIfRequired2() { - Assert.assertEquals("

aa

\n

bb

\n",UftTestDiscoveryUtils.convertToHtmlFormatIfRequired("aa\nbb")); + Assertions.assertEquals("

aa

\n

bb

\n",UftTestDiscoveryUtils.convertToHtmlFormatIfRequired("aa\nbb")); } } diff --git a/integrations-sdk/src/test/java/com/hp/octane/integrations/utils/CIPluginSDKUtilsTest.java b/integrations-sdk/src/test/java/com/hp/octane/integrations/utils/CIPluginSDKUtilsTest.java index 08aa90cc..4ea5886b 100644 --- a/integrations-sdk/src/test/java/com/hp/octane/integrations/utils/CIPluginSDKUtilsTest.java +++ b/integrations-sdk/src/test/java/com/hp/octane/integrations/utils/CIPluginSDKUtilsTest.java @@ -32,20 +32,23 @@ package com.hp.octane.integrations.utils; import com.hp.octane.integrations.exceptions.OctaneSDKGeneralException; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.io.ByteArrayInputStream; import java.io.IOException; import java.net.URL; import java.nio.charset.StandardCharsets; +import static org.junit.jupiter.api.Assertions.assertThrows; + public class CIPluginSDKUtilsTest { - @Test(expected = IllegalArgumentException.class) + @Test public void testDoWaitBadParameter() { - CIPluginSDKUtils.doWait(0); - } + assertThrows(IllegalArgumentException.class, () -> + CIPluginSDKUtils.doWait(0)); + } @Test public void testDoWaitNoInterrupt() { @@ -54,7 +57,7 @@ public void testDoWaitNoInterrupt() { CIPluginSDKUtils.doWait(timeToWait); long ended = System.currentTimeMillis(); - Assert.assertTrue(ended - started >= timeToWait); + Assertions.assertTrue(ended - started >= timeToWait); } @Test @@ -69,18 +72,20 @@ public void testDoWaitWithInterrupt() { }).start(); CIPluginSDKUtils.doWait(timeToWait); long ended = System.currentTimeMillis(); - Assert.assertTrue(ended - started >= timeToWait); + Assertions.assertTrue(ended - started >= timeToWait); } - @Test(expected = IllegalArgumentException.class) + @Test public void testDoBreakableWaitBadParameterA() { - CIPluginSDKUtils.doBreakableWait(0, null); - } + assertThrows(IllegalArgumentException.class, () -> + CIPluginSDKUtils.doBreakableWait(0, null)); + } - @Test(expected = IllegalArgumentException.class) + @Test public void testDoBreakableWaitBadParameterB() { - CIPluginSDKUtils.doBreakableWait(1, null); - } + assertThrows(IllegalArgumentException.class, () -> + CIPluginSDKUtils.doBreakableWait(1, null)); + } @Test public void testDoBreakableWaitNoInterrupt() { @@ -90,7 +95,7 @@ public void testDoBreakableWaitNoInterrupt() { CIPluginSDKUtils.doBreakableWait(timeToWait, monitor); long ended = System.currentTimeMillis(); - Assert.assertTrue(ended - started >= timeToWait); + Assertions.assertTrue(ended - started >= timeToWait); } @Test @@ -108,7 +113,7 @@ public void testDoBreakableWaitWithInterruptErroneous() { }).start(); CIPluginSDKUtils.doBreakableWait(timeToWait, monitor); long ended = System.currentTimeMillis(); - Assert.assertTrue(ended - started >= timeToWait); + Assertions.assertTrue(ended - started >= timeToWait); } @Test @@ -125,34 +130,37 @@ public void testDoBreakableWaitWithInterruptIntentional() { }).start(); CIPluginSDKUtils.doBreakableWait(timeToWait, monitor); long ended = System.currentTimeMillis(); - Assert.assertTrue(ended - started > timeToWait / 2); - Assert.assertTrue(ended - started < timeToWait); + Assertions.assertTrue(ended - started > timeToWait / 2); + Assertions.assertTrue(ended - started < timeToWait); } - @Test(expected = IllegalArgumentException.class) + @Test public void testInputStreamToStringA() throws IOException { - CIPluginSDKUtils.inputStreamToUTF8String(null); - } + assertThrows(IllegalArgumentException.class, () -> + CIPluginSDKUtils.inputStreamToUTF8String(null)); + } - @Test(expected = IllegalArgumentException.class) + @Test public void testInputStreamToStringB() throws IOException { - CIPluginSDKUtils.inputStreamToString(null, null); - } + assertThrows(IllegalArgumentException.class, () -> + CIPluginSDKUtils.inputStreamToString(null, null)); + } - @Test(expected = IllegalArgumentException.class) + @Test public void testInputStreamToStringC() throws IOException { - CIPluginSDKUtils.inputStreamToString(new ByteArrayInputStream("some text".getBytes()), null); - } + assertThrows(IllegalArgumentException.class, () -> + CIPluginSDKUtils.inputStreamToString(new ByteArrayInputStream("some text".getBytes()), null)); + } @Test public void testInputStreamToStringD() throws IOException { String text = "some text to test"; String test = CIPluginSDKUtils.inputStreamToString(new ByteArrayInputStream(text.getBytes(StandardCharsets.UTF_8.name())), StandardCharsets.UTF_8); - Assert.assertEquals(text, test); + Assertions.assertEquals(text, test); test = CIPluginSDKUtils.inputStreamToString(new ByteArrayInputStream(text.getBytes()), StandardCharsets.UTF_8); - Assert.assertEquals(text, test); + Assertions.assertEquals(text, test); } @Test @@ -160,7 +168,7 @@ public void testInputStreamToStringE() throws IOException { String text = "some text to test וגם בעברית и по русски чуток"; String test = CIPluginSDKUtils.inputStreamToString(new ByteArrayInputStream(text.getBytes(StandardCharsets.UTF_8.name())), StandardCharsets.UTF_8); - Assert.assertEquals(text, test); + Assertions.assertEquals(text, test); // the case below may fail on unpredictable default charset in different environments, temporary disabled // test = CIPluginSDKUtils.inputStreamToString(new ByteArrayInputStream(text.getBytes()), Charset.defaultCharset()); @@ -171,140 +179,143 @@ public void testInputStreamToStringE() throws IOException { public void testInputStreamToStringF() throws IOException { String text = "some text to test וגם בעברית и по русски чуток"; String test = CIPluginSDKUtils.inputStreamToUTF8String(new ByteArrayInputStream(text.getBytes(StandardCharsets.UTF_8.name()))); - Assert.assertEquals(text, test); + Assertions.assertEquals(text, test); } @Test public void testsParseURLPos() { URL url = CIPluginSDKUtils.parseURL("http://localhost:8080"); - Assert.assertNotNull(url); + Assertions.assertNotNull(url); } - @Test(expected = IllegalArgumentException.class) + @Test public void testsParseURLNeg1() { - CIPluginSDKUtils.parseURL("something-wrong-here"); - } + assertThrows(IllegalArgumentException.class, () -> + CIPluginSDKUtils.parseURL("something-wrong-here")); + } - @Test(expected = IllegalArgumentException.class) + @Test public void testsParseURLNeg2() { - CIPluginSDKUtils.parseURL(null); - } + assertThrows(IllegalArgumentException.class, () -> + CIPluginSDKUtils.parseURL(null)); + } - @Test(expected = IllegalArgumentException.class) + @Test public void testsParseURLNeg3() { - CIPluginSDKUtils.parseURL(""); - } + assertThrows(IllegalArgumentException.class, () -> + CIPluginSDKUtils.parseURL("")); + } @Test public void testURLEncodePathParamsPos() { String encoded = CIPluginSDKUtils.urlEncodePathParam("some string to . be in path"); - Assert.assertEquals("some%20string%20to%20.%20be%20in%20path", encoded); + Assertions.assertEquals("some%20string%20to%20.%20be%20in%20path", encoded); } @Test public void testURLEncodePathParamsNeg1() { String encoded = CIPluginSDKUtils.urlEncodePathParam(null); - Assert.assertNull(encoded); + Assertions.assertNull(encoded); } @Test public void testURLEncodePathParamsPos2() { String encoded = CIPluginSDKUtils.urlEncodePathParam(""); - Assert.assertEquals("", encoded); + Assertions.assertEquals("", encoded); } @Test public void testURLEncodeQueryParamsPos() { String encoded = CIPluginSDKUtils.urlEncodeQueryParam("some string to . be in path"); - Assert.assertEquals("some+string+to+.+be+in+path", encoded); + Assertions.assertEquals("some+string+to+.+be+in+path", encoded); } @Test public void testURLEncodeQueryParamsNeg1() { String encoded = CIPluginSDKUtils.urlEncodeQueryParam(null); - Assert.assertNull(encoded); + Assertions.assertNull(encoded); } @Test public void testURLEncodeQueryParamsPos2() { String encoded = CIPluginSDKUtils.urlEncodeQueryParam(""); - Assert.assertEquals("", encoded); + Assertions.assertEquals("", encoded); } // is non-proxy host tests @Test public void testIsNotProxyHostNeg() { boolean result = CIPluginSDKUtils.isNonProxyHost(null, null); - Assert.assertFalse(result); + Assertions.assertFalse(result); result = CIPluginSDKUtils.isNonProxyHost("", null); - Assert.assertFalse(result); + Assertions.assertFalse(result); result = CIPluginSDKUtils.isNonProxyHost("some", null); - Assert.assertFalse(result); + Assertions.assertFalse(result); result = CIPluginSDKUtils.isNonProxyHost("some", ""); - Assert.assertFalse(result); + Assertions.assertFalse(result); } @Test public void testIsNotProxyHost() { boolean result = CIPluginSDKUtils.isNonProxyHost("some", "some"); - Assert.assertTrue(result); + Assertions.assertTrue(result); result = CIPluginSDKUtils.isNonProxyHost("some.host", "some"); - Assert.assertTrue(result); + Assertions.assertTrue(result); result = CIPluginSDKUtils.isNonProxyHost("some", "some.host"); - Assert.assertFalse(result); + Assertions.assertFalse(result); } @Test public void testIsNotProxyHostWildcard() { boolean result = CIPluginSDKUtils.isNonProxyHost("some", "some*"); - Assert.assertTrue(result); + Assertions.assertTrue(result); result = CIPluginSDKUtils.isNonProxyHost("some.host", "*me.ho*"); - Assert.assertTrue(result); + Assertions.assertTrue(result); result = CIPluginSDKUtils.isNonProxyHost("some", "s*e"); - Assert.assertTrue(result); + Assertions.assertTrue(result); } @Test public void testIsNotProxyHostWildcardMulti() { boolean result = CIPluginSDKUtils.isNonProxyHost("some", "localhost|some*"); - Assert.assertTrue(result); + Assertions.assertTrue(result); result = CIPluginSDKUtils.isNonProxyHost("some.host", "*me.ho*|localhost"); - Assert.assertTrue(result); + Assertions.assertTrue(result); result = CIPluginSDKUtils.isNonProxyHost("some", "first|s*e|last"); - Assert.assertTrue(result); + Assertions.assertTrue(result); result = CIPluginSDKUtils.isNonProxyHost("some", "first|s*e||||last"); - Assert.assertTrue(result); + Assertions.assertTrue(result); result = CIPluginSDKUtils.isNonProxyHost("some", "first |s*e||| |la,st"); - Assert.assertTrue(result); + Assertions.assertTrue(result); } @Test public void testIsNotProxyHostWildcardMultiWithQuotations() { boolean result = CIPluginSDKUtils.isNonProxyHost("some", "'localhost|some*'"); - Assert.assertTrue(result); + Assertions.assertTrue(result); result = CIPluginSDKUtils.isNonProxyHost("some.host", "\"*me.ho*|localhost\""); - Assert.assertTrue(result); + Assertions.assertTrue(result); result = CIPluginSDKUtils.isNonProxyHost("some", "\"first|s*e|last\""); - Assert.assertTrue(result); + Assertions.assertTrue(result); result = CIPluginSDKUtils.isNonProxyHost("some", "\"first|s*e||||last\""); - Assert.assertTrue(result); + Assertions.assertTrue(result); result = CIPluginSDKUtils.isNonProxyHost("some", "'first |s*e||| |la,st'"); - Assert.assertTrue(result); + Assertions.assertTrue(result); } private Object objectFromForeignThread() { diff --git a/integrations-sdk/src/test/java/com/hp/octane/integrations/utils/OctaneUrlParserTest.java b/integrations-sdk/src/test/java/com/hp/octane/integrations/utils/OctaneUrlParserTest.java index d2c82478..97ba414b 100644 --- a/integrations-sdk/src/test/java/com/hp/octane/integrations/utils/OctaneUrlParserTest.java +++ b/integrations-sdk/src/test/java/com/hp/octane/integrations/utils/OctaneUrlParserTest.java @@ -32,8 +32,8 @@ package com.hp.octane.integrations.utils; import com.hp.octane.integrations.exceptions.OctaneSDKGeneralException; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.io.ByteArrayInputStream; import java.io.IOException; @@ -49,22 +49,22 @@ public class OctaneUrlParserTest { @Test public void test1() { OctaneUrlParser parser = OctaneUrlParser.parse("https://center.almoctane.com/ui/?p=1001%2F1002#/team-backlog/stories"); - Assert.assertEquals("https://center.almoctane.com", parser.getLocation()); - Assert.assertEquals("1001", parser.getSharedSpace()); + Assertions.assertEquals("https://center.almoctane.com", parser.getLocation()); + Assertions.assertEquals("1001", parser.getSharedSpace()); } @Test public void test2() { OctaneUrlParser parser = OctaneUrlParser.parse("http://localhost:8080/ui/?admin&p=1001/1002#/settings/workspace/devops/build-servers"); - Assert.assertEquals("http://localhost:8080", parser.getLocation()); - Assert.assertEquals("1001", parser.getSharedSpace()); + Assertions.assertEquals("http://localhost:8080", parser.getLocation()); + Assertions.assertEquals("1001", parser.getSharedSpace()); } @Test public void testWithContext1() { OctaneUrlParser parser = OctaneUrlParser.parse("https://myd-hvm01967.swinfra.net:8447/web-context/ui/?admin&p=1002/500#/settings/shared-space/applications"); - Assert.assertEquals("https://myd-hvm01967.swinfra.net:8447/web-context", parser.getLocation()); - Assert.assertEquals("1002", parser.getSharedSpace()); + Assertions.assertEquals("https://myd-hvm01967.swinfra.net:8447/web-context", parser.getLocation()); + Assertions.assertEquals("1002", parser.getSharedSpace()); } diff --git a/integrations-sdk/src/test/java/pullrequestsandbranches/FetchHandlerTests.java b/integrations-sdk/src/test/java/pullrequestsandbranches/FetchHandlerTests.java index 969c0cf9..e6eaaeb6 100644 --- a/integrations-sdk/src/test/java/pullrequestsandbranches/FetchHandlerTests.java +++ b/integrations-sdk/src/test/java/pullrequestsandbranches/FetchHandlerTests.java @@ -37,8 +37,8 @@ import com.hp.octane.integrations.services.pullrequestsandbranches.github.GithubCloudFetchHandler; import com.hp.octane.integrations.services.pullrequestsandbranches.github.GithubServerFetchHandler; import com.hp.octane.integrations.services.pullrequestsandbranches.rest.authentication.NoCredentialsStrategy; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; public class FetchHandlerTests { @@ -47,10 +47,10 @@ public void githubCloudTest() { GithubCloudFetchHandler handler = new GithubCloudFetchHandler(new NoCredentialsStrategy()); String result = handler.getRepoApiPath("https://github.com/jenkinsci/hpe-application-automation-tools-plugin.git"); - Assert.assertEquals("getRepoApiPath for https failed", "https://api.github.com/repos/jenkinsci/hpe-application-automation-tools-plugin", result); + Assertions.assertEquals("https://api.github.com/repos/jenkinsci/hpe-application-automation-tools-plugin", result, "getRepoApiPath for https failed"); result = handler.getApiPath("https://github.com/jenkinsci/hpe-application-automation-tools-plugin.git"); - Assert.assertEquals("getApiPath for https failed", "https://api.github.com", result); + Assertions.assertEquals("https://api.github.com", result, "getApiPath for https failed"); } @Test @@ -58,11 +58,11 @@ public void githubServerTest() { GithubServerFetchHandler handler = new GithubServerFetchHandler(new NoCredentialsStrategy()); String result = handler.getRepoApiPath("https://github.houston.softwaregrp.net/MQM/mqm.git"); - Assert.assertEquals("getRepoApiPath for https failed", "https://github.houston.softwaregrp.net/api/v3/repos/MQM/mqm", result); + Assertions.assertEquals("https://github.houston.softwaregrp.net/api/v3/repos/MQM/mqm", result, "getRepoApiPath for https failed"); result = handler.getApiPath("https://github.houston.softwaregrp.net/MQM/mqm.git"); - Assert.assertEquals("getApiPath for https failed", "https://github.houston.softwaregrp.net/api/v3", result); + Assertions.assertEquals("https://github.houston.softwaregrp.net/api/v3", result, "getApiPath for https failed"); } @Test @@ -70,10 +70,10 @@ public void bitbucketServerTest() { BitbucketServerFetchHandler handler = new BitbucketServerFetchHandler(new NoCredentialsStrategy()); String result = handler.getRepoApiPath("http://localhost:8990/scm/proj/rep1.git"); - Assert.assertEquals("getRepoApiPath for https failed", "http://localhost:8990/rest/api/1.0/projects/proj/repos/rep1", result); + Assertions.assertEquals("http://localhost:8990/rest/api/1.0/projects/proj/repos/rep1", result, "getRepoApiPath for https failed"); result = handler.getRepoApiPath("http://localhost:8990/scm/~admin/rep1.git"); - Assert.assertEquals("getRepoApiPath for https failed", "http://localhost:8990/rest/api/1.0/users/admin/repos/rep1", result); + Assertions.assertEquals("http://localhost:8990/rest/api/1.0/users/admin/repos/rep1", result, "getRepoApiPath for https failed"); } @Test @@ -81,8 +81,8 @@ public void bitbucketParseLinks() throws JsonProcessingException { String body = "{\"slug\":\"simple-tests\",\"id\":1,\"name\":\"simple-tests\",\"hierarchyId\":\"3652cee12ecd25817b22\",\"scmId\":\"git\",\"state\":\"AVAILABLE\",\"statusMessage\":\"Available\",\"forkable\":true,\"project\":{\"key\":\"TES\",\"id\":2,\"name\":\"tests\",\"public\":false,\"type\":\"NORMAL\",\"links\":{\"self\":[{\"href\":\"http://myd-hvm02624.swinfra.net:7990/projects/TES\"}]}},\"public\":true,\"links\":{\"clone\":[{\"href\":\"ssh://git@myd-hvm02624.swinfra.net:7999/tes/simple-tests.git\",\"name\":\"ssh\"},{\"href\":\"http://myd-hvm02624.swinfra.net:7990/scm/tes/simple-tests.git\",\"name\":\"http\"}],\"self\":[{\"href\":\"http://myd-hvm02624.swinfra.net:7990/projects/TES/repos/simple-tests/browse\"}]}}"; BitbucketServerFetchHandler handler = new BitbucketServerFetchHandler(new NoCredentialsStrategy()); SCMRepositoryLinks links = handler.parseSCMRepositoryLinks(body); - Assert.assertEquals("ssh://git@myd-hvm02624.swinfra.net:7999/tes/simple-tests.git", links.getSshUrl()); - Assert.assertEquals("http://myd-hvm02624.swinfra.net:7990/scm/tes/simple-tests.git", links.getHttpUrl()); + Assertions.assertEquals("ssh://git@myd-hvm02624.swinfra.net:7999/tes/simple-tests.git", links.getSshUrl()); + Assertions.assertEquals("http://myd-hvm02624.swinfra.net:7990/scm/tes/simple-tests.git", links.getHttpUrl()); } @Test @@ -90,7 +90,7 @@ public void githubServerParseLinks() throws JsonProcessingException { String body = "{\"id\":237845737,\"node_id\":\"MDEwOlJlcG9zaXRvcnkyMzc4NDU3Mzc=\",\"name\":\"trial\",\"full_name\":\"radislavB/trial\",\"private\":false,\"owner\":{\"login\":\"radislavB\",\"id\":20180777,\"node_id\":\"MDQ6VXNlcjIwMTgwNzc3\",\"avatar_url\":\"https://avatars.githubusercontent.com/u/20180777?v=4\",\"gravatar_id\":\"\",\"url\":\"https://api.github.com/users/radislavB\",\"html_url\":\"https://github.com/radislavB\",\"followers_url\":\"https://api.github.com/users/radislavB/followers\",\"following_url\":\"https://api.github.com/users/radislavB/following{/other_user}\",\"gists_url\":\"https://api.github.com/users/radislavB/gists{/gist_id}\",\"starred_url\":\"https://api.github.com/users/radislavB/starred{/owner}{/repo}\",\"subscriptions_url\":\"https://api.github.com/users/radislavB/subscriptions\",\"organizations_url\":\"https://api.github.com/users/radislavB/orgs\",\"repos_url\":\"https://api.github.com/users/radislavB/repos\",\"events_url\":\"https://api.github.com/users/radislavB/events{/privacy}\",\"received_events_url\":\"https://api.github.com/users/radislavB/received_events\",\"type\":\"User\",\"site_admin\":false},\"html_url\":\"https://github.com/radislavB/trial\",\"description\":\"trial\",\"fork\":false,\"url\":\"https://api.github.com/repos/radislavB/trial\",\"forks_url\":\"https://api.github.com/repos/radislavB/trial/forks\",\"keys_url\":\"https://api.github.com/repos/radislavB/trial/keys{/key_id}\",\"collaborators_url\":\"https://api.github.com/repos/radislavB/trial/collaborators{/collaborator}\",\"teams_url\":\"https://api.github.com/repos/radislavB/trial/teams\",\"hooks_url\":\"https://api.github.com/repos/radislavB/trial/hooks\",\"issue_events_url\":\"https://api.github.com/repos/radislavB/trial/issues/events{/number}\",\"events_url\":\"https://api.github.com/repos/radislavB/trial/events\",\"assignees_url\":\"https://api.github.com/repos/radislavB/trial/assignees{/user}\",\"branches_url\":\"https://api.github.com/repos/radislavB/trial/branches{/branch}\",\"tags_url\":\"https://api.github.com/repos/radislavB/trial/tags\",\"blobs_url\":\"https://api.github.com/repos/radislavB/trial/git/blobs{/sha}\",\"git_tags_url\":\"https://api.github.com/repos/radislavB/trial/git/tags{/sha}\",\"git_refs_url\":\"https://api.github.com/repos/radislavB/trial/git/refs{/sha}\",\"trees_url\":\"https://api.github.com/repos/radislavB/trial/git/trees{/sha}\",\"statuses_url\":\"https://api.github.com/repos/radislavB/trial/statuses/{sha}\",\"languages_url\":\"https://api.github.com/repos/radislavB/trial/languages\",\"stargazers_url\":\"https://api.github.com/repos/radislavB/trial/stargazers\",\"contributors_url\":\"https://api.github.com/repos/radislavB/trial/contributors\",\"subscribers_url\":\"https://api.github.com/repos/radislavB/trial/subscribers\",\"subscription_url\":\"https://api.github.com/repos/radislavB/trial/subscription\",\"commits_url\":\"https://api.github.com/repos/radislavB/trial/commits{/sha}\",\"git_commits_url\":\"https://api.github.com/repos/radislavB/trial/git/commits{/sha}\",\"comments_url\":\"https://api.github.com/repos/radislavB/trial/comments{/number}\",\"issue_comment_url\":\"https://api.github.com/repos/radislavB/trial/issues/comments{/number}\",\"contents_url\":\"https://api.github.com/repos/radislavB/trial/contents/{+path}\",\"compare_url\":\"https://api.github.com/repos/radislavB/trial/compare/{base}...{head}\",\"merges_url\":\"https://api.github.com/repos/radislavB/trial/merges\",\"archive_url\":\"https://api.github.com/repos/radislavB/trial/{archive_format}{/ref}\",\"downloads_url\":\"https://api.github.com/repos/radislavB/trial/downloads\",\"issues_url\":\"https://api.github.com/repos/radislavB/trial/issues{/number}\",\"pulls_url\":\"https://api.github.com/repos/radislavB/trial/pulls{/number}\",\"milestones_url\":\"https://api.github.com/repos/radislavB/trial/milestones{/number}\",\"notifications_url\":\"https://api.github.com/repos/radislavB/trial/notifications{?since,all,participating}\",\"labels_url\":\"https://api.github.com/repos/radislavB/trial/labels{/name}\",\"releases_url\":\"https://api.github.com/repos/radislavB/trial/releases{/id}\",\"deployments_url\":\"https://api.github.com/repos/radislavB/trial/deployments\",\"created_at\":\"2020-02-02T22:21:33Z\",\"updated_at\":\"2021-03-04T12:02:08Z\",\"pushed_at\":\"2021-03-04T12:02:06Z\",\"git_url\":\"git://github.com/radislavB/trial.git\",\"ssh_url\":\"git@github.com:radislavB/trial.git\",\"clone_url\":\"https://github.com/radislavB/trial.git\",\"svn_url\":\"https://github.com/radislavB/trial\",\"homepage\":null,\"size\":45,\"stargazers_count\":0,\"watchers_count\":0,\"language\":null,\"has_issues\":true,\"has_projects\":true,\"has_downloads\":true,\"has_wiki\":true,\"has_pages\":false,\"forks_count\":0,\"mirror_url\":null,\"archived\":false,\"disabled\":false,\"open_issues_count\":4,\"license\":null,\"forks\":0,\"open_issues\":4,\"watchers\":0,\"default_branch\":\"master\",\"permissions\":{\"admin\":true,\"push\":true,\"pull\":true},\"temp_clone_token\":\"\",\"allow_squash_merge\":true,\"allow_merge_commit\":true,\"allow_rebase_merge\":true,\"delete_branch_on_merge\":false,\"network_count\":0,\"subscribers_count\":1}"; GithubServerFetchHandler handler = new GithubServerFetchHandler(new NoCredentialsStrategy()); SCMRepositoryLinks links = handler.parseSCMRepositoryLinks(body); - Assert.assertEquals("git@github.com:radislavB/trial.git", links.getSshUrl()); - Assert.assertEquals("https://github.com/radislavB/trial.git", links.getHttpUrl()); + Assertions.assertEquals("git@github.com:radislavB/trial.git", links.getSshUrl()); + Assertions.assertEquals("https://github.com/radislavB/trial.git", links.getHttpUrl()); } } diff --git a/integrations-sdk/src/test/java/pullrequestsandbranches/PullRequestParsingTests.java b/integrations-sdk/src/test/java/pullrequestsandbranches/PullRequestParsingTests.java index 6425cb05..05214d45 100644 --- a/integrations-sdk/src/test/java/pullrequestsandbranches/PullRequestParsingTests.java +++ b/integrations-sdk/src/test/java/pullrequestsandbranches/PullRequestParsingTests.java @@ -31,8 +31,8 @@ */ package pullrequestsandbranches; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.io.*; import java.nio.charset.Charset; @@ -48,7 +48,7 @@ public void testBitbucketServerBranchesParsing() throws IOException { com.hp.octane.integrations.services.pullrequestsandbranches.bitbucketserver.JsonConverter.convertCollection( json, com.hp.octane.integrations.services.pullrequestsandbranches.bitbucketserver.pojo.Branch.class); - Assert.assertEquals(10, list.getSize()); + Assertions.assertEquals(10, list.getSize()); } @@ -58,7 +58,7 @@ public void testBitbucketServerPullRequestsParsing() throws IOException { com.hp.octane.integrations.services.pullrequestsandbranches.bitbucketserver.pojo.EntityCollection list = com.hp.octane.integrations.services.pullrequestsandbranches.bitbucketserver.JsonConverter.convertCollection( json, com.hp.octane.integrations.services.pullrequestsandbranches.bitbucketserver.pojo.PullRequest.class); - Assert.assertEquals(11, list.getSize()); + Assertions.assertEquals(11, list.getSize()); } @@ -66,14 +66,14 @@ public void testBitbucketServerPullRequestsParsing() throws IOException { public void testGithubServerPullRequestsParsing() throws IOException { String json = readResourceAsString("githubServerPullRequests.json"); List list = com.hp.octane.integrations.services.pullrequestsandbranches.github.JsonConverter.convertCollection(json, com.hp.octane.integrations.services.pullrequestsandbranches.github.pojo.PullRequest.class); - Assert.assertEquals(5, list.size()); + Assertions.assertEquals(5, list.size()); } @Test public void testGithubCloudPullRequestsParsing() throws IOException { String json = readResourceAsString("githubCloudPullRequests.json"); List list = com.hp.octane.integrations.services.pullrequestsandbranches.github.JsonConverter.convertCollection(json, com.hp.octane.integrations.services.pullrequestsandbranches.github.pojo.PullRequest.class); - Assert.assertEquals(30, list.size()); + Assertions.assertEquals(30, list.size()); } public String readResourceAsString(String resourceName) throws IOException { diff --git a/integrations-sdk/src/test/java/testresults/gherkin/GherkinTestResultsCollectorTest.java b/integrations-sdk/src/test/java/testresults/gherkin/GherkinTestResultsCollectorTest.java index 94be34ff..142ea0d5 100644 --- a/integrations-sdk/src/test/java/testresults/gherkin/GherkinTestResultsCollectorTest.java +++ b/integrations-sdk/src/test/java/testresults/gherkin/GherkinTestResultsCollectorTest.java @@ -34,8 +34,8 @@ import com.hp.octane.integrations.testresults.GherkinUtils; import com.hp.octane.integrations.testresults.GherkinXmlWritableTestResult; import com.hp.octane.integrations.testresults.XmlWritableTestResult; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import org.xml.sax.SAXException; import javax.xml.parsers.ParserConfigurationException; @@ -46,6 +46,8 @@ import java.util.List; import java.util.Map; +import static org.junit.jupiter.api.Assertions.assertThrows; + public class GherkinTestResultsCollectorTest { String file0 = "OctaneGherkinResults0.xml"; @@ -77,39 +79,41 @@ public void testConstruct() throws ParserConfigurationException, IOException, SA @Test public void testGetResults() throws ParserConfigurationException, IOException, SAXException { List gherkinTestsResults = GherkinUtils.parseFiles(getFilesFromFolder("f1")); - Assert.assertEquals(3, gherkinTestsResults.size()); - validateGherkinTestResult((GherkinXmlWritableTestResult) gherkinTestsResults.get(0), "test Feature1", 21, "Failed"); + Assertions.assertEquals(3, gherkinTestsResults.size()); + validateGherkinTestResult((GherkinXmlWritableTestResult) gherkinTestsResults.getFirst(), "test Feature1", 21, "Failed"); validateGherkinTestResult((GherkinXmlWritableTestResult) gherkinTestsResults.get(1), "test Feature10", 21, "Failed"); validateGherkinTestResult((GherkinXmlWritableTestResult) gherkinTestsResults.get(2), "test Feature2", 21, "Passed"); } - @Test(expected = IllegalArgumentException.class) + @Test public void testXmlHasNoVersion() throws ParserConfigurationException, IOException, SAXException { - GherkinUtils.parseFiles(Arrays.asList(new File(getRootResource("f2", file0)))); + assertThrows(IllegalArgumentException.class, () -> + GherkinUtils.parseFiles(Arrays.asList(new File(getRootResource("f2", file0))))); } - @Test(expected = IllegalArgumentException.class) + @Test public void testXmlHasHigherVersion() throws ParserConfigurationException, IOException, SAXException { - GherkinUtils.parseFiles(Arrays.asList(new File(getRootResource("f3", file1)))); + assertThrows(IllegalArgumentException.class, () -> + GherkinUtils.parseFiles(Arrays.asList(new File(getRootResource("f3", file1))))); } @Test public void testTemplateWithCounter() { String folder = new File(getRootResource("f3", file0)).getParent(); List files = GherkinUtils.findGherkinFilesByTemplateWithCounter(folder, "OctaneGherkinResults%s.xml", 0); - Assert.assertEquals(file0, files.get(0).getName()); - Assert.assertEquals(file1, files.get(1).getName()); + Assertions.assertEquals(file0, files.getFirst().getName()); + Assertions.assertEquals(file1, files.get(1).getName()); } private void validateGherkinTestResult(GherkinXmlWritableTestResult gherkinTestResult, String name, long duration, String status) { validateAttributes(gherkinTestResult, name, duration, status); - Assert.assertNotNull(gherkinTestResult.getXmlElement()); + Assertions.assertNotNull(gherkinTestResult.getXmlElement()); } private void validateAttributes(GherkinXmlWritableTestResult gherkinTestResult, String name, long duration, String status) { Map attributes = gherkinTestResult.getAttributes(); - Assert.assertEquals(name, attributes.get("name")); - Assert.assertEquals(String.valueOf(duration), attributes.get("duration")); - Assert.assertEquals(status, attributes.get("status")); + Assertions.assertEquals(name, attributes.get("name")); + Assertions.assertEquals(String.valueOf(duration), attributes.get("duration")); + Assertions.assertEquals(status, attributes.get("status")); } } diff --git a/integrations-sdk/src/test/java/uftTest/MbtTests.java b/integrations-sdk/src/test/java/uftTest/MbtTests.java index 3c23ad78..11f468cc 100644 --- a/integrations-sdk/src/test/java/uftTest/MbtTests.java +++ b/integrations-sdk/src/test/java/uftTest/MbtTests.java @@ -39,8 +39,8 @@ import com.hp.octane.integrations.uft.ufttestresults.schema.UftResultIterationData; import com.hp.octane.integrations.uft.ufttestresults.schema.UftResultStepData; import com.hp.octane.integrations.uft.ufttestresults.schema.UftResultStepParameter; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.io.File; import java.net.URL; @@ -52,10 +52,10 @@ public class MbtTests { public void parseConfiguration() { URL url = getClass().getResource("mbtExample1.json"); MbtData mbtData = DTOFactory.getInstance().dtoFromJsonFile(new File(url.getFile()), MbtData.class); - Assert.assertEquals(4, mbtData.getUnits().size()); - Assert.assertEquals(6, mbtData.getData().getParameters().size()); - Assert.assertEquals(2, mbtData.getData().getIterations().size()); - mbtData.getData().getIterations().forEach(strings -> Assert.assertEquals(6, strings.size())); + Assertions.assertEquals(4, mbtData.getUnits().size()); + Assertions.assertEquals(6, mbtData.getData().getParameters().size()); + Assertions.assertEquals(2, mbtData.getData().getIterations().size()); + mbtData.getData().getIterations().forEach(strings -> Assertions.assertEquals(6, strings.size())); mbtData.getUnits().forEach(mbtUnit -> System.out.println(mbtUnit.getName() + ", parameters: " + Optional.ofNullable(mbtUnit.getParameters()).orElse(Collections.emptyList()).stream().map(MbtUnitParameter::getParameterId).collect(Collectors.joining(", ")))); mbtData.getData().getParameters().forEach(System.out::println); @@ -67,7 +67,7 @@ public void testComputeResourcePath() { String osName = System.getProperty("os.name"); if (osName.toLowerCase(Locale.ROOT).contains("windows")) { String path = MfMBTConverter.computeResourcePath("..\\ss", "c:\\aa\\bb"); - Assert.assertEquals("c:\\aa\\ss", path.toLowerCase(Locale.ROOT)); + Assertions.assertEquals("c:\\aa\\ss", path.toLowerCase(Locale.ROOT)); } } @@ -75,8 +75,8 @@ public void testComputeResourcePath() { public void readActionResults1() { File file = new File(getClass().getResource("run_mbt_results_with_errors.xml").getFile()); List resultData = UftTestResultsUtils.getMBTData(file); - Assert.assertEquals(1, resultData.size()); - UftResultStepData data1 = resultData.get(0).getSteps().get(0); + Assertions.assertEquals(1, resultData.size()); + UftResultStepData data1 = resultData.getFirst().getSteps().getFirst(); String errorMessage = "Cannot find the \"password\" object's parent \"Micro Focus MyFlight Sample\" (class WpfWindow).
Verify that parent properties match an object currently displayed in your application.

Object's physical description:
wpftypename = window
regexpwndtitle = Micro Focus MyFlight Sample Application
devname = Micro Focus MyFlight Sample Application
(Warning). "; validateAction(23, "Passed", errorMessage, "Action1 [Two test_same function 2]", data1, Collections.EMPTY_LIST, null); } @@ -85,11 +85,11 @@ public void readActionResults1() { public void readActionResults2() { File file = new File(getClass().getResource("run_mbt_results_8_successful.xml").getFile()); List iterations = UftTestResultsUtils.getMBTData(file); - List resultData = iterations.get(0).getSteps(); - Assert.assertEquals(8, resultData.size()); + List resultData = iterations.getFirst().getSteps(); + Assertions.assertEquals(8, resultData.size()); List inputParameters = Arrays.asList(new UftResultStepParameter("username", "john", "System.String"), new UftResultStepParameter("password", "HP", "System.String")); - validateAction(1, "Done", "", "Launch App [FlightGUIBU2]", resultData.get(0), Collections.EMPTY_LIST, null); + validateAction(1, "Done", "", "Launch App [FlightGUIBU2]", resultData.getFirst(), Collections.EMPTY_LIST, null); validateAction(3, "Done", "", "Login [FlightGUIBU2]", resultData.get(1), inputParameters, null); validateAction(1, "Done", "", "Search Order Tab [FlightGUIBU2]", resultData.get(2), Collections.EMPTY_LIST, null); inputParameters = Arrays.asList(new UftResultStepParameter("Name", "john", "System.String")); @@ -106,27 +106,27 @@ public void readActionResults2() { public void readActionResults3() { File file = new File(getClass().getResource("run_mbt_results_with2_runs.xml").getFile()); List iterations = UftTestResultsUtils.getMBTData(file); - Assert.assertEquals(2, iterations.size()); - List resultData1 = iterations.get(0).getSteps(); + Assertions.assertEquals(2, iterations.size()); + List resultData1 = iterations.getFirst().getSteps(); List resultData2 = iterations.get(1).getSteps(); - Assert.assertEquals(1, resultData1.size()); - Assert.assertEquals(1, resultData2.size()); + Assertions.assertEquals(1, resultData1.size()); + Assertions.assertEquals(1, resultData2.size()); List inputParameters = Arrays.asList(new UftResultStepParameter("parameter1", "4", "System.Double"), new UftResultStepParameter("parameter2", "2", "System.Double")); - validateAction(11, "Done", "", "Action1 [FUNCTION-TEST1]", resultData1.get(0), inputParameters, null); + validateAction(11, "Done", "", "Action1 [FUNCTION-TEST1]", resultData1.getFirst(), inputParameters, null); inputParameters = Arrays.asList(new UftResultStepParameter("parameter1", "3", "System.Double"), new UftResultStepParameter("parameter2", "1", "System.Double")); - validateAction(9, "Done", "", "Action1 [FUNCTION-TEST1]", resultData2.get(0), inputParameters, null); + validateAction(9, "Done", "", "Action1 [FUNCTION-TEST1]", resultData2.getFirst(), inputParameters, null); } private void validateAction(long duration, String result, String errorMessage, String lastParent, UftResultStepData data, List inputParameters, List outputParameters) { - Assert.assertEquals(errorMessage, data.getMessage()); - Assert.assertEquals("Action", data.getType()); - Assert.assertEquals(duration, data.getDuration()); - Assert.assertEquals(result, data.getResult()); - Assert.assertEquals(3, data.getParents().size()); - Assert.assertEquals(lastParent, data.getParents().get(2)); - Assert.assertEquals(inputParameters, data.getInputParameters()); - Assert.assertEquals(outputParameters, data.getOutputParameters()); + Assertions.assertEquals(errorMessage, data.getMessage()); + Assertions.assertEquals("Action", data.getType()); + Assertions.assertEquals(duration, data.getDuration()); + Assertions.assertEquals(result, data.getResult()); + Assertions.assertEquals(3, data.getParents().size()); + Assertions.assertEquals(lastParent, data.getParents().get(2)); + Assertions.assertEquals(inputParameters, data.getInputParameters()); + Assertions.assertEquals(outputParameters, data.getOutputParameters()); } @Test @@ -134,8 +134,8 @@ public void testNameEncodingWithoutIllegalChars() { String name = "my name"; String encoded = MfMBTConverter.encodeTestNameIfRequired(name); String decoded = MfMBTConverter.decodeTestNameIfRequired(encoded); - Assert.assertEquals(name, decoded); - Assert.assertEquals(name, encoded); + Assertions.assertEquals(name, decoded); + Assertions.assertEquals(name, encoded); } @Test @@ -143,8 +143,8 @@ public void testNameEncodingWithIllegalChars() { String name = "my name^*"; String encoded = MfMBTConverter.encodeTestNameIfRequired(name); String decoded = MfMBTConverter.decodeTestNameIfRequired(encoded); - Assert.assertEquals(name, decoded); - Assert.assertNotEquals(name, encoded); + Assertions.assertEquals(name, decoded); + Assertions.assertNotEquals(name, encoded); } @Test @@ -152,8 +152,8 @@ public void testNameEncodingWithEndingSpace() { String name = "my name "; String encoded = MfMBTConverter.encodeTestNameIfRequired(name); String decoded = MfMBTConverter.decodeTestNameIfRequired(encoded); - Assert.assertEquals(name, decoded); - Assert.assertNotEquals(name, encoded); + Assertions.assertEquals(name, decoded); + Assertions.assertNotEquals(name, encoded); } diff --git a/integrations-sdk/src/test/java/uftTest/RunResultsTestGetAggregatedError.java b/integrations-sdk/src/test/java/uftTest/RunResultsTestGetAggregatedError.java index 07d45948..bd528b07 100644 --- a/integrations-sdk/src/test/java/uftTest/RunResultsTestGetAggregatedError.java +++ b/integrations-sdk/src/test/java/uftTest/RunResultsTestGetAggregatedError.java @@ -33,8 +33,8 @@ import com.hp.octane.integrations.uft.ufttestresults.UftTestResultsUtils; import com.hp.octane.integrations.uft.ufttestresults.schema.UftResultStepData; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.io.File; import java.net.URL; @@ -46,38 +46,44 @@ public class RunResultsTestGetAggregatedError { public void testOneError() { String err = getAggregatedError("run_results.xml"); String expected = "Cannot identify the object \"rabbit\" (of class WebElement)."; - Assert.assertEquals(expected, err); + Assertions.assertEquals(expected, err); } @Test public void testDuplicatedErrors() { String err = getAggregatedError("run_results_duplicatedErrors.xml"); - String expected = "The following add-in(s) were associated with your test, but are not currently loaded: WinForms, WPF. (Warning). \n" + - "ActiveX component can't create object: 'WpfWindow'. "; - Assert.assertEquals(expected, err); + String expected = """ + The following add-in(s) were associated with your test, but are not currently loaded: WinForms, WPF. (Warning).\s + ActiveX component can't create object: 'WpfWindow'.\s\ + """; + Assertions.assertEquals(expected, err); } @Test public void testResultForGUITestWithFail() { String err = getAggregatedError("run_results_GUITestWithFail.xml"); - String expected = "This step always fail. \n" + - "This step always warn (Warning). "; - Assert.assertEquals(expected, err); + String expected = """ + This step always fail.\s + This step always warn (Warning).\s\ + """; + Assertions.assertEquals(expected, err); } @Test public void testResultForGUITestWithWarning() { String err = getAggregatedError("run_results_GUITestWithWarning.xml"); - String expected = "This step is always ends with warning (Warning). \n" + - "This step is also always ends with warning (Warning). "; - Assert.assertEquals(expected, err); + String expected = """ + This step is always ends with warning (Warning).\s + This step is also always ends with warning (Warning).\s\ + """; + Assertions.assertEquals(expected, err); } @Test public void testResultForComputerLocked() { String err = getAggregatedError("run_results_computer_locked.xml"); String expected = "The Micro Focus Unified Functional Testing computer is locked or logged off."; - Assert.assertEquals(expected, err); + Assertions.assertEquals(expected, err); } diff --git a/integrations-sdk/src/test/java/uftTest/UftTestDiscoveryUtilsTests.java b/integrations-sdk/src/test/java/uftTest/UftTestDiscoveryUtilsTests.java index 1db45e5a..f65a7f9d 100644 --- a/integrations-sdk/src/test/java/uftTest/UftTestDiscoveryUtilsTests.java +++ b/integrations-sdk/src/test/java/uftTest/UftTestDiscoveryUtilsTests.java @@ -34,8 +34,8 @@ import com.hp.octane.integrations.dto.executor.impl.TestingToolType; import com.hp.octane.integrations.uft.UftTestDiscoveryUtils; import com.hp.octane.integrations.uft.items.*; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import org.w3c.dom.Document; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; @@ -60,7 +60,7 @@ public class UftTestDiscoveryUtilsTests { public void scanTest(){ File root = new File("c:\\dev\\plugins\\_uft\\UftTests\\"); UftTestDiscoveryResult result = UftTestDiscoveryUtils.doFullDiscovery(root, TestingToolType.MBT); - Assert.assertNotNull(result); + Assertions.assertNotNull(result); } @Test @@ -72,7 +72,7 @@ public void readDescriptionTest() { File folderPath = new File(getClass().getResource("description").getFile()); Document document = getDocument(folderPath, UftTestType.GUI); String description = com.hp.octane.integrations.uft.UftTestDiscoveryUtils.getTestDescription(document, UftTestType.GUI); - Assert.assertEquals("myDesc333", description); + Assertions.assertEquals("myDesc333", description); } @@ -112,21 +112,21 @@ public void readParameterFile() { File mbtTestRootPath = new File(getClass().getClassLoader().getResource("mbt-tests").getFile()); UftTestDiscoveryResult result = UftTestDiscoveryUtils.doFullDiscovery(mbtTestRootPath, TestingToolType.MBT); - Assert.assertNotNull("null discovery result", result); + Assertions.assertNotNull(result, "null discovery result"); List actions = result.getAllTests().stream() .map(AutomatedTest::getActions) .flatMap(Collection::stream) .collect(Collectors.toList()); - Assert.assertFalse("no actions were found", actions.isEmpty()); - Assert.assertEquals("wrong number of actions were found", 14, actions.size()); + Assertions.assertFalse(actions.isEmpty(), "no actions were found"); + Assertions.assertEquals(14, actions.size(), "wrong number of actions were found"); List parameters = actions.stream() .map(UftTestAction::getParameters) .flatMap(Collection::stream) .collect(Collectors.toList()); - Assert.assertFalse("no parameters were found", parameters.isEmpty()); - Assert.assertEquals("wrong number of parameters were found", 13, parameters.size()); + Assertions.assertFalse(parameters.isEmpty(), "no parameters were found"); + Assertions.assertEquals(13, parameters.size(), "wrong number of parameters were found"); } } diff --git a/pom.xml b/pom.xml index 26b9b858..539a2051 100644 --- a/pom.xml +++ b/pom.xml @@ -94,39 +94,50 @@ - 3.1.0 - 3.0.0-M1 - 3.0.0-M2 - 3.1.0 - 3.8.0 - 3.0.1 - 3.1.1 - 3.3.0 - 1.6 - 1.6.8 + 21 + 21 + + 3.5.0 + 3.1.4 + 3.6.3 + 3.5.0 + 3.15.0 + 3.4.0 + 3.5.0 + 3.12.0 + 3.2.8 + 1.7.0 UTF-8 - 4.13.1 - 3.5.1 - 3.0.0-M2 - 0.8.2 - 3.1.9 + 5.6.0 + 3.5.6 + 0.8.15 + 4.9.8.5 + 2.22.0 + 1.22.0 + 5.0.0 2026 - - junit - junit - ${junit.version} - easymock org.easymock ${easymock.version} + + + commons-io + commons-io + ${commons-io.version} + + + commons-codec + commons-codec + ${commons-codec.version} + @@ -136,7 +147,7 @@ maven-clean-plugin org.apache.maven.plugins - ${maven-clean-plugin.verion} + ${maven-clean-plugin.version} maven-resources-plugin @@ -148,8 +159,7 @@ org.apache.maven.plugins ${maven-compiler-plugin.version} - 1.8 - 1.8 + ${java.level} @@ -176,13 +186,13 @@ org.apache.maven.plugins ${maven-javadoc-plugin.version} - 8 + ${java.level} maven-install-plugin org.apache.maven.plugins - ${maven-install-plugin.verion} + ${maven-install-plugin.version} @@ -206,7 +216,7 @@ spotbugs-maven-plugin com.github.spotbugs - ${spotbugs.version} + ${spotbugs-maven-plugin.version} max 20 @@ -218,13 +228,6 @@ - - - spotbugs - com.github.spotbugs - ${spotbugs.version} - - maven-surefire-plugin @@ -247,7 +250,7 @@ com.mycila license-maven-plugin - 4.6 + ${license-maven-plugin.version}