diff --git a/.github/workflows/gradle.yml b/.github/workflows/gradle.yml index 0fe345e..fffa472 100644 --- a/.github/workflows/gradle.yml +++ b/.github/workflows/gradle.yml @@ -17,10 +17,10 @@ jobs: steps: - uses: actions/checkout@v2 - - name: Set up JDK 1.8 + - name: Set up JDK 11 uses: actions/setup-java@v1 with: - java-version: 1.8 + java-version: 11 - name: Grant execute permission for gradlew run: chmod +x gradlew diff --git a/build.gradle b/build.gradle index 180302e..478bd6d 100644 --- a/build.gradle +++ b/build.gradle @@ -25,7 +25,6 @@ buildscript { } dependencies { - implementation 'com.squareup.okhttp3:okhttp:3.11.0' implementation 'com.google.code.gson:gson:2.8.6' implementation group: 'ch.qos.logback', name: 'logback-classic', version: '1.2.3' testImplementation group: 'org.testng', name: 'testng', version: '7.3.0' diff --git a/jitpack.yml b/jitpack.yml new file mode 100644 index 0000000..46c8529 --- /dev/null +++ b/jitpack.yml @@ -0,0 +1,2 @@ +jdk: + - openjdk11 \ No newline at end of file diff --git a/src/main/java/io/visual_regression_tracker/sdk_java/VisualRegressionTracker.java b/src/main/java/io/visual_regression_tracker/sdk_java/VisualRegressionTracker.java index 76b6b8e..826cd6d 100644 --- a/src/main/java/io/visual_regression_tracker/sdk_java/VisualRegressionTracker.java +++ b/src/main/java/io/visual_regression_tracker/sdk_java/VisualRegressionTracker.java @@ -1,68 +1,55 @@ package io.visual_regression_tracker.sdk_java; -import java.io.IOException; -import java.util.Optional; -import java.util.concurrent.TimeUnit; - import com.google.gson.Gson; import io.visual_regression_tracker.sdk_java.request.BuildRequest; import io.visual_regression_tracker.sdk_java.request.TestRunRequest; import io.visual_regression_tracker.sdk_java.response.BuildResponse; import io.visual_regression_tracker.sdk_java.response.TestRunResponse; import lombok.extern.slf4j.Slf4j; -import okhttp3.MediaType; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.RequestBody; -import okhttp3.Response; + +import java.io.IOException; +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.time.Duration; + +enum METHOD { + GET, + POST, + PATCH +} @Slf4j public class VisualRegressionTracker { private static final String TRACKER_NOT_STARTED = "Visual Regression Tracker has not been started"; protected static final String API_KEY_HEADER = "apiKey"; - protected static final MediaType JSON = MediaType.get("application/json; charset=utf-8"); protected Gson gson; protected VisualRegressionTrackerConfig configuration; protected PathProvider paths; protected String buildId; protected String projectId; - protected OkHttpClient client; public VisualRegressionTracker(VisualRegressionTrackerConfig trackerConfig) { configuration = trackerConfig; paths = new PathProvider(trackerConfig.getApiUrl()); - client = new OkHttpClient.Builder() - .connectTimeout(configuration.getHttpTimeoutInSeconds(), TimeUnit.SECONDS) - .readTimeout(configuration.getHttpTimeoutInSeconds(), TimeUnit.SECONDS) - .writeTimeout(configuration.getHttpTimeoutInSeconds(), TimeUnit.SECONDS) - .build(); gson = new Gson(); } - public BuildResponse start() throws IOException { + public BuildResponse start() throws IOException, InterruptedException { String projectName = configuration.getProject(); String branch = configuration.getBranchName(); String ciBuildId = configuration.getCiBuildId(); BuildRequest newBuild = BuildRequest.builder() - .branchName(branch) - .project(projectName) - .ciBuildId(ciBuildId) - .build(); - - RequestBody body = RequestBody.create(JSON, gson.toJson(newBuild)); - - Request request = new Request.Builder() - .url(paths.getBuildPath()) - .addHeader(API_KEY_HEADER, configuration.getApiKey()) - .post(body) - .build(); - + .branchName(branch) + .project(projectName) + .ciBuildId(ciBuildId) + .build(); log.info("Starting Visual Regression Tracker for project <{}> and branch <{}>", projectName, branch); - - Response response = client.newCall(request).execute(); - + HttpRequest.BodyPublisher body = HttpRequest.BodyPublishers.ofString(gson.toJson(newBuild)); + HttpResponse response = getResponse(METHOD.POST, paths.getBuildPath(), body); BuildResponse buildResponse = handleResponse(response, BuildResponse.class); buildId = buildResponse.getId(); @@ -73,27 +60,22 @@ public BuildResponse start() throws IOException { return buildResponse; } - public void stop() throws IOException { + public void stop() throws IOException, InterruptedException { if (!isStarted()) { throw new TestRunException(TRACKER_NOT_STARTED); } - Request request = new Request.Builder() - .url(paths.getBuildPathForBuild(buildId)) - .addHeader(API_KEY_HEADER, configuration.getApiKey()) - .patch(RequestBody.create(JSON, "")) - .build(); - log.info("Stopping Visual Regression Tracker for buildId <{}>", buildId); - Response response = client.newCall(request).execute(); + HttpRequest.BodyPublisher body = HttpRequest.BodyPublishers.ofString(""); + HttpResponse response = getResponse(METHOD.PATCH, paths.getBuildPathForBuild(buildId), body); handleResponse(response, Object.class); log.info("Visual Regression Tracker is stopped for buildId <{}>", buildId); } public TestRunResult track(String name, String imageBase64, TestRunOptions testRunOptions) - throws IOException { + throws IOException, InterruptedException { log.info("Tracking test run <{}> with options <{}> for buildId <{}>", name, testRunOptions, buildId); TestRunResponse testResultDTO = submitTestRun(name, imageBase64, testRunOptions); @@ -121,7 +103,7 @@ public TestRunResult track(String name, String imageBase64, TestRunOptions testR return new TestRunResult(testResultDTO, this.paths); } - public TestRunResult track(String name, String imageBase64) throws IOException { + public TestRunResult track(String name, String imageBase64) throws IOException, InterruptedException { return track(name, imageBase64, TestRunOptions.builder().build()); } @@ -130,46 +112,61 @@ protected boolean isStarted() { } protected TestRunResponse submitTestRun(String name, String imageBase64, - TestRunOptions testRunOptions) throws IOException { + TestRunOptions testRunOptions) throws IOException, InterruptedException { if (!isStarted()) { throw new TestRunException(TRACKER_NOT_STARTED); } TestRunRequest newTestRun = TestRunRequest.builder() - .projectId(projectId) - .buildId(buildId) - .branchName(configuration.getBranchName()) - .name(name) - .imageBase64(imageBase64) - .os(testRunOptions.getOs()) - .browser(testRunOptions.getBrowser()) - .viewport(testRunOptions.getViewport()) - .device(testRunOptions.getDevice()) - .diffTollerancePercent(testRunOptions.getDiffTollerancePercent()) - .ignoreAreas(testRunOptions.getIgnoreAreas()) - .build(); - - RequestBody body = RequestBody.create(JSON, gson.toJson(newTestRun)); - - Request request = new Request.Builder() - .url(paths.getTestRunPath()) - .addHeader(API_KEY_HEADER, configuration.getApiKey()) - .post(body) - .build(); - - Response response = client.newCall(request).execute(); + .projectId(projectId) + .buildId(buildId) + .branchName(configuration.getBranchName()) + .name(name) + .imageBase64(imageBase64) + .os(testRunOptions.getOs()) + .browser(testRunOptions.getBrowser()) + .viewport(testRunOptions.getViewport()) + .device(testRunOptions.getDevice()) + .diffTollerancePercent(testRunOptions.getDiffTollerancePercent()) + .ignoreAreas(testRunOptions.getIgnoreAreas()) + .build(); + + HttpRequest.BodyPublisher body = HttpRequest.BodyPublishers.ofString(gson.toJson(newTestRun)); + HttpResponse response = getResponse(METHOD.POST, paths.getTestRunPath(), body); return handleResponse(response, TestRunResponse.class); } - protected T handleResponse(Response response, Class classOfT) throws IOException { - String responseBody = Optional.ofNullable(response.body()) - .orElseThrow(() -> new TestRunException("Cannot get response body")) - .string(); + private HttpResponse getResponse(METHOD method, String url, HttpRequest.BodyPublisher body) throws IOException, InterruptedException { + HttpRequest.Builder requestBuilder = HttpRequest.newBuilder() + .timeout(Duration.ofSeconds(configuration.getHttpTimeoutInSeconds())) + .header(API_KEY_HEADER, configuration.getApiKey()) + .header("Content-Type", "application/json;charset=UTF-8") + .uri(URI.create(url)); + HttpRequest request = getRequest(method, body, requestBuilder); + HttpResponse response = HttpClient.newBuilder() + .version(HttpClient.Version.HTTP_1_1) + .connectTimeout(Duration.ofSeconds(configuration.getHttpTimeoutInSeconds())) + .build() + .send(request, HttpResponse.BodyHandlers.ofString()); + return response; + } + + protected HttpRequest getRequest(METHOD method, HttpRequest.BodyPublisher body, HttpRequest.Builder requestBuilder) { + switch (method) { + case PATCH: + return requestBuilder.method("PATCH", body).build(); + case POST: + return requestBuilder.POST(body).build(); + default: + throw new UnsupportedOperationException("This method is not yet supported."); + } + } - if (!response.isSuccessful()) { + protected T handleResponse(HttpResponse response, Class classOfT) { + String responseBody = response.body(); + if (!String.valueOf(response.statusCode()).startsWith("2")) { throw new TestRunException(responseBody); } - return gson.fromJson(responseBody, classOfT); } } diff --git a/src/test/java/io/visual_regression_tracker/sdk_java/MockHttpClient.java b/src/test/java/io/visual_regression_tracker/sdk_java/MockHttpClient.java new file mode 100644 index 0000000..888bb0a --- /dev/null +++ b/src/test/java/io/visual_regression_tracker/sdk_java/MockHttpClient.java @@ -0,0 +1,130 @@ +package io.visual_regression_tracker.sdk_java; + +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLParameters; +import javax.net.ssl.SSLSession; +import java.net.Authenticator; +import java.net.CookieHandler; +import java.net.ProxySelector; +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpHeaders; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.time.Duration; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.Executor; + +public class MockHttpClient extends HttpClient { + + private final String body; + private int statusCode; + + public MockHttpClient(int statusCode, String body) { + this.statusCode = statusCode; + this.body = body; + } + + @Override + public Optional cookieHandler() { + return null; + } + + @Override + public Optional connectTimeout() { + return null; + } + + @Override + public Redirect followRedirects() { + return null; + } + + @Override + public Optional proxy() { + return null; + } + + @Override + public SSLContext sslContext() { + return null; + } + + @Override + public SSLParameters sslParameters() { + return null; + } + + @Override + public Optional authenticator() { + return null; + } + + @Override + public Version version() { + return null; + } + + @Override + public Optional executor() { + return null; + } + + @Override + public HttpResponse send(HttpRequest request, HttpResponse.BodyHandler responseBodyHandler) { + HttpResponse httpResponse = new HttpResponse() { + @Override + public int statusCode() { + return statusCode; + } + + @Override + public HttpRequest request() { + return null; + } + + @Override + public Optional previousResponse() { + return Optional.empty(); + } + + @Override + public HttpHeaders headers() { + return null; + } + + @Override + public Object body() { + return body; + } + + @Override + public Optional sslSession() { + return Optional.empty(); + } + + @Override + public URI uri() { + return null; + } + + @Override + public Version version() { + return null; + } + }; + return httpResponse; + } + + @Override + public CompletableFuture> sendAsync(HttpRequest request, HttpResponse.BodyHandler responseBodyHandler) { + return null; + } + + @Override + public CompletableFuture> + sendAsync(HttpRequest x, HttpResponse.BodyHandler y, HttpResponse.PushPromiseHandler z) { + return null; + } +} diff --git a/src/test/java/io/visual_regression_tracker/sdk_java/VisualRegressionTrackerTest.java b/src/test/java/io/visual_regression_tracker/sdk_java/VisualRegressionTrackerTest.java index 2775a00..ab15169 100644 --- a/src/test/java/io/visual_regression_tracker/sdk_java/VisualRegressionTrackerTest.java +++ b/src/test/java/io/visual_regression_tracker/sdk_java/VisualRegressionTrackerTest.java @@ -1,11 +1,5 @@ package io.visual_regression_tracker.sdk_java; -import java.io.IOException; -import java.net.SocketTimeoutException; -import java.util.Arrays; -import java.util.Objects; -import java.util.concurrent.TimeUnit; - import ch.qos.logback.classic.Level; import ch.qos.logback.classic.Logger; import ch.qos.logback.classic.spi.ILoggingEvent; @@ -16,10 +10,6 @@ import io.visual_regression_tracker.sdk_java.response.BuildResponse; import io.visual_regression_tracker.sdk_java.response.TestRunResponse; import lombok.SneakyThrows; -import okhttp3.Protocol; -import okhttp3.Request; -import okhttp3.Response; -import okhttp3.ResponseBody; import okhttp3.mockwebserver.MockResponse; import okhttp3.mockwebserver.MockWebServer; import okhttp3.mockwebserver.RecordedRequest; @@ -29,6 +19,14 @@ import org.testng.annotations.DataProvider; import org.testng.annotations.Test; +import java.io.IOException; +import java.net.http.HttpClient; +import java.net.http.HttpResponse; +import java.net.http.HttpTimeoutException; +import java.util.Arrays; +import java.util.Objects; +import java.util.concurrent.TimeUnit; + import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; @@ -87,18 +85,18 @@ public void tearDown() { @Test public void shouldStartBuild() throws IOException, InterruptedException { BuildRequest buildRequest = BuildRequest.builder() - .branchName(this.config.getBranchName()) - .project(this.config.getProject()) - .ciBuildId(this.config.getCiBuildId()) - .build(); + .branchName(this.config.getBranchName()) + .project(this.config.getProject()) + .ciBuildId(this.config.getCiBuildId()) + .build(); BuildResponse buildResponse = BuildResponse.builder() - .id(BUILD_ID) - .projectId(PROJECT_ID) - .ciBuildId(CI_BUILD_ID) - .build(); + .id(BUILD_ID) + .projectId(PROJECT_ID) + .ciBuildId(CI_BUILD_ID) + .build(); server.enqueue(new MockResponse() - .setResponseCode(200) - .setBody(gson.toJson(buildResponse))); + .setResponseCode(200) + .setBody(gson.toJson(buildResponse))); BuildResponse result = vrt.start(); @@ -117,11 +115,11 @@ public void shouldStopBuild() throws IOException, InterruptedException { vrt.buildId = BUILD_ID; vrt.projectId = PROJECT_ID; BuildResponse buildResponse = BuildResponse.builder() - .id(BUILD_ID) - .build(); + .id(BUILD_ID) + .build(); server.enqueue(new MockResponse() - .setResponseCode(200) - .setBody(gson.toJson(buildResponse))); + .setResponseCode(200) + .setBody(gson.toJson(buildResponse))); vrt.stop(); @@ -133,41 +131,41 @@ public void shouldStopBuild() throws IOException, InterruptedException { @Test(expectedExceptions = TestRunException.class, expectedExceptionsMessageRegExp = "Visual Regression Tracker has not been started") - public void stopShouldThrowExceptionIfNotStarted() throws IOException { + public void stopShouldThrowExceptionIfNotStarted() throws IOException, InterruptedException { vrt.stop(); } @Test public void shouldSubmitTestRun() throws IOException, InterruptedException { TestRunOptions testRunOptions = TestRunOptions.builder() - .device("Device") - .os("OS") - .browser("Browser") - .viewport("Viewport") - .diffTollerancePercent(0.5f) - .ignoreAreas(Arrays.asList(IgnoreAreas.builder() - .x(100L) - .y(100L) - .height(1L) - .width(1L) - .build())) - .build(); + .device("Device") + .os("OS") + .browser("Browser") + .viewport("Viewport") + .diffTollerancePercent(0.5f) + .ignoreAreas(Arrays.asList(IgnoreAreas.builder() + .x(100L) + .y(100L) + .height(1L) + .width(1L) + .build())) + .build(); TestRunRequest testRunRequest = TestRunRequest.builder() - .projectId(PROJECT_ID) - .branchName(config.getBranchName()) - .buildId(BUILD_ID) - .name(NAME) - .imageBase64(IMAGE_BASE_64) - .os(testRunOptions.getOs()) - .browser(testRunOptions.getBrowser()) - .viewport(testRunOptions.getViewport()) - .device(testRunOptions.getDevice()) - .diffTollerancePercent(testRunOptions.getDiffTollerancePercent()) - .ignoreAreas(testRunOptions.getIgnoreAreas()) - .build(); + .projectId(PROJECT_ID) + .branchName(config.getBranchName()) + .buildId(BUILD_ID) + .name(NAME) + .imageBase64(IMAGE_BASE_64) + .os(testRunOptions.getOs()) + .browser(testRunOptions.getBrowser()) + .viewport(testRunOptions.getViewport()) + .device(testRunOptions.getDevice()) + .diffTollerancePercent(testRunOptions.getDiffTollerancePercent()) + .ignoreAreas(testRunOptions.getIgnoreAreas()) + .build(); TestRunResponse testRunResponse = TestRunResponse.builder() - .status(TestRunStatus.UNRESOLVED) - .build(); + .status(TestRunStatus.UNRESOLVED) + .build(); server.enqueue(new MockResponse().setBody(gson.toJson(testRunResponse))); vrt.buildId = BUILD_ID; vrt.projectId = PROJECT_ID; @@ -182,7 +180,7 @@ public void shouldSubmitTestRun() throws IOException, InterruptedException { @Test(expectedExceptions = TestRunException.class, expectedExceptionsMessageRegExp = "Visual Regression Tracker has not been started") - public void submitTestRunShouldThrowIfNotStarted() throws IOException { + public void submitTestRunShouldThrowIfNotStarted() throws IOException, InterruptedException { when(vrtMocked.isStarted()).thenReturn(false); doCallRealMethod().when(vrtMocked).submitTestRun(anyString(), any(), any()); @@ -191,24 +189,24 @@ public void submitTestRunShouldThrowIfNotStarted() throws IOException { @DataProvider(name = "trackErrorCases") public Object[][] trackErrorCases() { - return new Object[][] { + return new Object[][]{ { TestRunResponse.builder() - .url("https://someurl.com/test/123123") - .imageName("imageName") - .baselineName("baselineName") - .diffName("diffName") - .status(TestRunStatus.UNRESOLVED) + .url("https://someurl.com/test/123123") + .imageName("imageName") + .baselineName("baselineName") + .diffName("diffName") + .status(TestRunStatus.UNRESOLVED) .build(), "Difference found: https://someurl.com/test/123123" }, { TestRunResponse.builder() - .url("https://someurl.com/test/123123") - .imageName("imageName") - .baselineName("baselineName") - .diffName("diffName") - .status(TestRunStatus.NEW) + .url("https://someurl.com/test/123123") + .imageName("imageName") + .baselineName("baselineName") + .diffName("diffName") + .status(TestRunStatus.NEW) .build(), "No baseline: https://someurl.com/test/123123" } @@ -218,15 +216,15 @@ public Object[][] trackErrorCases() { @Test(dataProvider = "trackErrorCases", expectedExceptions = TestRunException.class, expectedExceptionsMessageRegExp = "^(Difference found: https://someurl.com/test/123123|No baseline: https://someurl.com/test/123123)$") - public void trackShouldThrowException(TestRunResponse testRunResponse, String expectedExceptionMessage) throws IOException { + public void trackShouldThrowException(TestRunResponse testRunResponse, String expectedExceptionMessage) throws IOException, InterruptedException { vrtMocked.configuration = VisualRegressionTrackerConfig.builder() - .apiUrl("") - .project("") - .apiKey("") - .branchName("") - .enableSoftAssert(false) - .ciBuildId("") - .build(); + .apiUrl("") + .project("") + .apiKey("") + .branchName("") + .enableSoftAssert(false) + .ciBuildId("") + .build(); when(vrtMocked.submitTestRun(anyString(), anyString(), any())).thenReturn(testRunResponse); @@ -235,7 +233,7 @@ public void trackShouldThrowException(TestRunResponse testRunResponse, String ex } @Test(dataProvider = "trackErrorCases") - public void trackShouldLogSevere(TestRunResponse testRunResponse, String expectedExceptionMessage) throws IOException { + public void trackShouldLogSevere(TestRunResponse testRunResponse, String expectedExceptionMessage) throws IOException, InterruptedException { Logger loggerMock = (Logger) LoggerFactory.getLogger(VisualRegressionTracker.class); // create and start a ListAppender ListAppender listAppender = new ListAppender<>(); @@ -243,13 +241,13 @@ public void trackShouldLogSevere(TestRunResponse testRunResponse, String expecte // add the appender to the logger loggerMock.addAppender(listAppender); vrtMocked.configuration = VisualRegressionTrackerConfig.builder() - .apiUrl("") - .project("") - .apiKey("") - .branchName("") - .enableSoftAssert(true) - .ciBuildId("") - .build(); + .apiUrl("") + .project("") + .apiKey("") + .branchName("") + .enableSoftAssert(true) + .ciBuildId("") + .build(); when(vrtMocked.submitTestRun(anyString(), anyString(), any())).thenReturn(testRunResponse); doCallRealMethod().when(vrtMocked).track(anyString(), anyString(), any()); @@ -261,40 +259,40 @@ public void trackShouldLogSevere(TestRunResponse testRunResponse, String expecte @DataProvider(name = "shouldTrackPassCases") public Object[][] shouldTrackPassCases() { - return new Object[][] { + return new Object[][]{ { TestRunResponse.builder() - .id("someId") - .imageName("imageName") - .baselineName("baselineName") - .diffName("diffName") - .diffPercent(12.32f) - .diffTollerancePercent(0.01f) - .pixelMisMatchCount(1) - .merge(false) - .url("https://someurl.com/test/123123") - .status(TestRunStatus.OK) + .id("someId") + .imageName("imageName") + .baselineName("baselineName") + .diffName("diffName") + .diffPercent(12.32f) + .diffTollerancePercent(0.01f) + .pixelMisMatchCount(1) + .merge(false) + .url("https://someurl.com/test/123123") + .status(TestRunStatus.OK) .build(), } }; } @Test(dataProvider = "shouldTrackPassCases") - public void shouldTrackPass(TestRunResponse testRunResponse) throws IOException { + public void shouldTrackPass(TestRunResponse testRunResponse) throws IOException, InterruptedException { when(vrtMocked.submitTestRun(anyString(), anyString(), any())).thenReturn(testRunResponse); - vrtMocked.paths = new PathProvider("backendUrl"); + vrtMocked.paths = new PathProvider("http://localhost:4200"); doCallRealMethod().when(vrtMocked).track(anyString(), anyString(), any()); TestRunResult testRunResult = vrtMocked.track("name", "image", TestRunOptions.builder().build()); assertThat(testRunResult.getTestRunResponse(), is(testRunResponse)); - assertThat(testRunResult.getImageUrl(), is("backendUrl/".concat(testRunResponse.getImageName()))); - assertThat(testRunResult.getDiffUrl(), is("backendUrl/".concat(testRunResponse.getDiffName()))); - assertThat(testRunResult.getBaselineUrl(), is("backendUrl/".concat(testRunResponse.getBaselineName()))); + assertThat(testRunResult.getImageUrl(), is("http://localhost:4200/".concat(testRunResponse.getImageName()))); + assertThat(testRunResult.getDiffUrl(), is("http://localhost:4200/".concat(testRunResponse.getDiffName()))); + assertThat(testRunResult.getBaselineUrl(), is("http://localhost:4200/".concat(testRunResponse.getBaselineName()))); } @Test() - public void shouldTrackOverload() throws IOException { + public void shouldTrackOverload() throws IOException, InterruptedException { doCallRealMethod().when(vrtMocked).track(anyString(), anyString()); vrtMocked.track("name", "image"); @@ -303,7 +301,7 @@ public void shouldTrackOverload() throws IOException { @DataProvider(name = "shouldReturnIsStartedCases") public Object[][] shouldReturnIsStartedCases() { - return new Object[][] { + return new Object[][]{ {null, null, false}, {null, "some", false}, {"some", null, false}, @@ -324,23 +322,17 @@ public void shouldReturnIsStarted(String buildId, String projectId, boolean expe @Test public void handleRequestShouldThrowIfNotSuccess() throws IOException { String error = "{\n" + - " \"statusCode\": 404,\n" + - " \"message\": \"Project not found\"\n" + - "}"; - Request mockRequest = new Request.Builder() - .url(config.getApiUrl()) - .build(); + " \"statusCode\": 404,\n" + + " \"message\": \"Project not found\"\n" + + "}"; String exceptionMessage = ""; try { - vrt.handleResponse(new Response.Builder() - .request(mockRequest) - .protocol(Protocol.HTTP_2) - .code(404) - .message("Not found") - .body(ResponseBody.create(error, VisualRegressionTracker.JSON)) - .build(), Object.class); - } catch (TestRunException ex) { + //A mock client is needed to create a mock response + HttpClient httpClient = new MockHttpClient(404, error); + HttpResponse httpResponse = httpClient.send(null, null); + vrt.handleResponse(httpResponse, Object.class); + } catch (TestRunException | InterruptedException ex) { exceptionMessage = ex.getMessage(); } @@ -348,15 +340,15 @@ public void handleRequestShouldThrowIfNotSuccess() throws IOException { } @Test - public void httpTimoutWorks() throws IOException, InterruptedException { + public void httpTimeoutWorks() throws IOException, InterruptedException { BuildResponse buildResponse = BuildResponse.builder() .id(BUILD_ID) .projectId(PROJECT_ID) .ciBuildId(CI_BUILD_ID) .build(); String json = gson.toJson(buildResponse); - //body size is 97 bytes, http timeout is 1s, set body read delay to 0.9s, wait that vrt get all values correctly - server.enqueue(new MockResponse().throttleBody(json.length(), HTTP_TIMOUT * 1000 - 100, TimeUnit.MILLISECONDS) + //body size is 97 bytes, http timeout is 1s, set body read delay to 0.5s, wait that vrt get all values correctly + server.enqueue(new MockResponse().throttleBody(json.length(), HTTP_TIMOUT * 1000 - 500, TimeUnit.MILLISECONDS) .setResponseCode(200) .setBody(json)); @@ -368,9 +360,14 @@ public void httpTimoutWorks() throws IOException, InterruptedException { assertThat(vrt.projectId, is(PROJECT_ID)); } - @Test(expectedExceptions = SocketTimeoutException.class, - expectedExceptionsMessageRegExp = "^(timeout|Read timed out)$") - public void httpTimoutElapsed() throws IOException, InterruptedException { + @Test(expectedExceptions = UnsupportedOperationException.class, expectedExceptionsMessageRegExp = "This method is not yet supported.") + public void methodNotSupported() { + vrt.getRequest(METHOD.GET, null, null); + } + + @Test(expectedExceptions = HttpTimeoutException.class, + expectedExceptionsMessageRegExp = "^(request timed out)$") + public void httpTimeoutElapsed() throws IOException, InterruptedException { BuildResponse buildResponse = BuildResponse.builder() .id(BUILD_ID) .projectId(PROJECT_ID)