Skip to content

Commit 3de466c

Browse files
authored
Merge pull request #28 from alexromanov/feature/refactor-feature-code
Refactor tracker: add logging and path handling
2 parents 159be52 + 9afd2d5 commit 3de466c

File tree

3 files changed

+106
-69
lines changed

3 files changed

+106
-69
lines changed
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
package io.visual_regression_tracker.sdk_java;
2+
3+
import lombok.AllArgsConstructor;
4+
5+
@AllArgsConstructor
6+
public class PathProvider {
7+
8+
private static final String BUILD_PATH = "/builds";
9+
private static final String TEST_RUNS_PATH = "/test-runs";
10+
11+
private final String baseApiUrl;
12+
13+
public String getBuildPath() {
14+
return baseApiUrl.concat(BUILD_PATH);
15+
}
16+
17+
public String getBuildPathForBuild(String buildId) {
18+
return getBuildPath().concat("/").concat(buildId);
19+
}
20+
21+
public String getTestRunPath() {
22+
return baseApiUrl.concat(TEST_RUNS_PATH);
23+
}
24+
}

src/main/java/io/visual_regression_tracker/sdk_java/VisualRegressionTracker.java

Lines changed: 77 additions & 64 deletions
Original file line numberDiff line numberDiff line change
@@ -1,80 +1,93 @@
11
package io.visual_regression_tracker.sdk_java;
22

3+
import java.io.IOException;
4+
import java.util.Optional;
5+
36
import com.google.gson.Gson;
47
import io.visual_regression_tracker.sdk_java.request.BuildRequest;
58
import io.visual_regression_tracker.sdk_java.request.TestRunRequest;
69
import io.visual_regression_tracker.sdk_java.response.BuildResponse;
710
import io.visual_regression_tracker.sdk_java.response.TestRunResponse;
11+
import lombok.extern.slf4j.Slf4j;
812
import okhttp3.MediaType;
913
import okhttp3.OkHttpClient;
1014
import okhttp3.Request;
1115
import okhttp3.RequestBody;
1216
import okhttp3.Response;
13-
import org.slf4j.Logger;
14-
import org.slf4j.LoggerFactory;
15-
16-
import java.io.IOException;
17-
import java.util.Optional;
18-
1917

18+
@Slf4j
2019
public class VisualRegressionTracker {
21-
protected static final String apiKeyHeaderName = "apiKey";
20+
21+
private static final String TRACKER_NOT_STARTED = "Visual Regression Tracker has not been started";
22+
protected static final String API_KEY_HEADER = "apiKey";
2223
protected static final MediaType JSON = MediaType.get("application/json; charset=utf-8");
23-
private static final Logger LOGGER = LoggerFactory.getLogger(VisualRegressionTracker.class);
2424
protected Gson gson;
25-
protected VisualRegressionTrackerConfig visualRegressionTrackerConfig;
25+
protected VisualRegressionTrackerConfig configuration;
26+
protected PathProvider paths;
2627
protected String buildId;
2728
protected String projectId;
2829
protected OkHttpClient client;
2930

30-
public VisualRegressionTracker(VisualRegressionTrackerConfig visualRegressionTrackerConfig) {
31-
this.visualRegressionTrackerConfig = visualRegressionTrackerConfig;
32-
33-
this.client = new OkHttpClient();
34-
this.gson = new Gson();
31+
public VisualRegressionTracker(VisualRegressionTrackerConfig trackerConfig) {
32+
configuration = trackerConfig;
33+
paths = new PathProvider(trackerConfig.getApiUrl());
34+
client = new OkHttpClient();
35+
gson = new Gson();
3536
}
3637

3738
public void start() throws IOException {
39+
String projectName = configuration.getProject();
40+
String branch = configuration.getBranchName();
41+
3842
BuildRequest newBuild = BuildRequest.builder()
39-
.branchName(this.visualRegressionTrackerConfig.getBranchName())
40-
.project(this.visualRegressionTrackerConfig.getProject())
41-
.build();
43+
.branchName(branch)
44+
.project(projectName)
45+
.build();
4246

4347
RequestBody body = RequestBody.create(JSON, gson.toJson(newBuild));
4448

4549
Request request = new Request.Builder()
46-
.url(this.visualRegressionTrackerConfig.getApiUrl().concat("/builds"))
47-
.addHeader(apiKeyHeaderName, this.visualRegressionTrackerConfig.getApiKey())
48-
.post(body)
49-
.build();
50+
.url(paths.getBuildPath())
51+
.addHeader(API_KEY_HEADER, configuration.getApiKey())
52+
.post(body)
53+
.build();
5054

51-
try (Response response = client.newCall(request).execute()) {
55+
log.info("Starting Visual Regression Tracker for project <{}> and branch <{}>", projectName, branch);
5256

53-
BuildResponse buildDTO = handleResponse(response, BuildResponse.class);
57+
Response response = client.newCall(request).execute();
5458

55-
this.buildId = buildDTO.getId();
56-
this.projectId = buildDTO.getProjectId();
57-
}
59+
BuildResponse buildResponse = handleResponse(response, BuildResponse.class);
60+
61+
buildId = buildResponse.getId();
62+
projectId = buildResponse.getProjectId();
63+
64+
log.info("Visual Regression Tracker is started for project <{}>: buildId <{}>, projectId <{}>",
65+
projectName, projectId, buildId);
5866
}
5967

6068
public void stop() throws IOException {
61-
if (!this.isStarted()) {
62-
throw new TestRunException("Visual Regression Tracker has not been started");
69+
if (!isStarted()) {
70+
throw new TestRunException(TRACKER_NOT_STARTED);
6371
}
6472

6573
Request request = new Request.Builder()
66-
.url(this.visualRegressionTrackerConfig.getApiUrl().concat("/builds/").concat(this.buildId))
67-
.addHeader(apiKeyHeaderName, this.visualRegressionTrackerConfig.getApiKey())
68-
.patch(RequestBody.create(JSON, ""))
69-
.build();
74+
.url(paths.getBuildPathForBuild(buildId))
75+
.addHeader(API_KEY_HEADER, configuration.getApiKey())
76+
.patch(RequestBody.create(JSON, ""))
77+
.build();
7078

71-
try (Response response = client.newCall(request).execute()) {
72-
handleResponse(response, Object.class);
73-
}
79+
log.info("Stopping Visual Regression Tracker for buildId <{}>", buildId);
80+
81+
Response response = client.newCall(request).execute();
82+
handleResponse(response, Object.class);
83+
84+
log.info("Visual Regression Tracker is stopped for buildId <{}>", buildId);
7485
}
7586

76-
public void track(String name, String imageBase64, TestRunOptions testRunOptions) throws IOException {
77-
TestRunResponse testResultDTO = this.submitTestRun(name, imageBase64, testRunOptions);
87+
public void track(String name, String imageBase64, TestRunOptions testRunOptions)
88+
throws IOException {
89+
log.info("Tracking test run <{}> with options <{}> for buildId <{}>", name, testRunOptions, buildId);
90+
TestRunResponse testResultDTO = submitTestRun(name, imageBase64, testRunOptions);
7891

7992
String errorMessage;
8093
switch (testResultDTO.getStatus()) {
@@ -90,57 +103,57 @@ public void track(String name, String imageBase64, TestRunOptions testRunOptions
90103
}
91104

92105
if (!errorMessage.isEmpty()) {
93-
if (this.visualRegressionTrackerConfig.getEnableSoftAssert()) {
94-
LOGGER.error(errorMessage);
106+
if (configuration.getEnableSoftAssert()) {
107+
log.error(errorMessage);
95108
} else {
96109
throw new TestRunException(errorMessage);
97110
}
98111
}
99112
}
100113

101114
public void track(String name, String imageBase64) throws IOException {
102-
this.track(name, imageBase64, TestRunOptions.builder().build());
115+
track(name, imageBase64, TestRunOptions.builder().build());
103116
}
104117

105118
protected boolean isStarted() {
106-
return this.buildId != null && this.projectId != null;
119+
return buildId != null && projectId != null;
107120
}
108121

109-
protected TestRunResponse submitTestRun(String name, String imageBase64, TestRunOptions testRunOptions) throws IOException {
110-
if (!this.isStarted()) {
111-
throw new TestRunException("Visual Regression Tracker has not been started");
122+
protected TestRunResponse submitTestRun(String name, String imageBase64,
123+
TestRunOptions testRunOptions) throws IOException {
124+
if (!isStarted()) {
125+
throw new TestRunException(TRACKER_NOT_STARTED);
112126
}
113127

114128
TestRunRequest newTestRun = TestRunRequest.builder()
115-
.projectId(this.projectId)
116-
.buildId(this.buildId)
117-
.branchName(this.visualRegressionTrackerConfig.getBranchName())
118-
.name(name)
119-
.imageBase64(imageBase64)
120-
.os(testRunOptions.getOs())
121-
.browser(testRunOptions.getBrowser())
122-
.viewport(testRunOptions.getViewport())
123-
.device(testRunOptions.getDevice())
124-
.diffTollerancePercent(testRunOptions.getDiffTollerancePercent())
125-
.build();
129+
.projectId(projectId)
130+
.buildId(buildId)
131+
.branchName(configuration.getBranchName())
132+
.name(name)
133+
.imageBase64(imageBase64)
134+
.os(testRunOptions.getOs())
135+
.browser(testRunOptions.getBrowser())
136+
.viewport(testRunOptions.getViewport())
137+
.device(testRunOptions.getDevice())
138+
.diffTollerancePercent(testRunOptions.getDiffTollerancePercent())
139+
.build();
126140

127141
RequestBody body = RequestBody.create(JSON, gson.toJson(newTestRun));
128142

129143
Request request = new Request.Builder()
130-
.url(this.visualRegressionTrackerConfig.getApiUrl().concat("/test-runs"))
131-
.addHeader(apiKeyHeaderName, this.visualRegressionTrackerConfig.getApiKey())
132-
.post(body)
133-
.build();
144+
.url(paths.getTestRunPath())
145+
.addHeader(API_KEY_HEADER, configuration.getApiKey())
146+
.post(body)
147+
.build();
134148

135-
try (Response response = client.newCall(request).execute()) {
136-
return handleResponse(response, TestRunResponse.class);
137-
}
149+
Response response = client.newCall(request).execute();
150+
return handleResponse(response, TestRunResponse.class);
138151
}
139152

140153
protected <T> T handleResponse(Response response, Class<T> classOfT) throws IOException {
141154
String responseBody = Optional.ofNullable(response.body())
142-
.orElseThrow(() -> new TestRunException("Cannot get response body"))
143-
.string();
155+
.orElseThrow(() -> new TestRunException("Cannot get response body"))
156+
.string();
144157

145158
if (!response.isSuccessful()) {
146159
throw new TestRunException(responseBody);

src/test/java/io/visual_regression_tracker/sdk_java/VisualRegressionTrackerTest.java

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -93,7 +93,7 @@ public void shouldStartBuild() throws IOException, InterruptedException {
9393
vrt.start();
9494

9595
RecordedRequest recordedRequest = server.takeRequest();
96-
assertThat(recordedRequest.getHeader(VisualRegressionTracker.apiKeyHeaderName), is(config.getApiKey()));
96+
assertThat(recordedRequest.getHeader(VisualRegressionTracker.API_KEY_HEADER), is(config.getApiKey()));
9797
assertThat(recordedRequest.getBody().readUtf8(), is(gson.toJson(buildRequest)));
9898
assertThat(vrt.buildId, is(BUILD_ID));
9999
assertThat(vrt.projectId, is(PROJECT_ID));
@@ -114,7 +114,7 @@ public void shouldStopBuild() throws IOException, InterruptedException {
114114

115115
RecordedRequest recordedRequest = server.takeRequest();
116116
assertThat(recordedRequest.getMethod(), is("PATCH"));
117-
assertThat(recordedRequest.getHeader(VisualRegressionTracker.apiKeyHeaderName), is(config.getApiKey()));
117+
assertThat(recordedRequest.getHeader(VisualRegressionTracker.API_KEY_HEADER), is(config.getApiKey()));
118118
assertThat(Objects.requireNonNull(recordedRequest.getRequestUrl()).encodedPath(), containsString(BUILD_ID));
119119
}
120120

@@ -155,7 +155,7 @@ public void shouldSubmitTestRun() throws IOException, InterruptedException {
155155
TestRunResponse result = vrt.submitTestRun(NAME, IMAGE_BASE_64, testRunOptions);
156156

157157
RecordedRequest request = server.takeRequest();
158-
assertThat(request.getHeader(VisualRegressionTracker.apiKeyHeaderName), is(config.getApiKey()));
158+
assertThat(request.getHeader(VisualRegressionTracker.API_KEY_HEADER), is(config.getApiKey()));
159159
assertThat(request.getBody().readUtf8(), is(gson.toJson(testRunRequest)));
160160
assertThat(gson.toJson(result), is(gson.toJson(testRunResponse)));
161161
}
@@ -193,7 +193,7 @@ public Object[][] trackErrorCases() {
193193
expectedExceptions = TestRunException.class,
194194
expectedExceptionsMessageRegExp = "^(Difference found: https://someurl.com/test/123123|No baseline: https://someurl.com/test/123123)$")
195195
public void trackShouldThrowException(TestRunResponse testRunResponse, String expectedExceptionMessage) throws IOException {
196-
vrtMocked.visualRegressionTrackerConfig = new VisualRegressionTrackerConfig("", "", "", "", false);
196+
vrtMocked.configuration = new VisualRegressionTrackerConfig("", "", "", "", false);
197197
when(vrtMocked.submitTestRun(anyString(), anyString(), any())).thenReturn(testRunResponse);
198198

199199
doCallRealMethod().when(vrtMocked).track(anyString(), anyString(), any());
@@ -203,7 +203,7 @@ public void trackShouldThrowException(TestRunResponse testRunResponse, String ex
203203
@Test(dataProvider = "trackErrorCases")
204204
public void trackShouldLogSevere(TestRunResponse testRunResponse, String expectedExceptionMessage) throws IOException {
205205
Logger loggerMock = LoggerMock.getLoggerMock(VisualRegressionTracker.class);
206-
vrtMocked.visualRegressionTrackerConfig = new VisualRegressionTrackerConfig("", "", "", "", true);
206+
vrtMocked.configuration = new VisualRegressionTrackerConfig("", "", "", "", true);
207207
when(vrtMocked.submitTestRun(anyString(), anyString(), any())).thenReturn(testRunResponse);
208208

209209
doCallRealMethod().when(vrtMocked).track(anyString(), anyString(), any());

0 commit comments

Comments
 (0)