Skip to content

Commit

Permalink
Run tests in random port
Browse files Browse the repository at this point in the history
  • Loading branch information
campos20 committed Sep 29, 2024
1 parent 08dd8dd commit 2d5d72b
Show file tree
Hide file tree
Showing 7 changed files with 52 additions and 44 deletions.
Original file line number Diff line number Diff line change
@@ -1,61 +1,66 @@
package org.worldcubeassociation.statistics.integration;

import static org.junit.platform.commons.function.Try.success;

import com.google.common.base.CaseFormat;
import io.restassured.builder.RequestSpecBuilder;
import io.restassured.filter.log.RequestLoggingFilter;
import io.restassured.filter.log.ResponseLoggingFilter;
import io.restassured.http.ContentType;
import io.restassured.response.Response;
import io.restassured.specification.RequestSpecification;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.UncheckedIOException;
import java.nio.file.Files;
import org.json.JSONException;
import org.skyscreamer.jsonassert.Customization;
import org.skyscreamer.jsonassert.JSONAssert;
import org.skyscreamer.jsonassert.JSONCompareMode;
import org.skyscreamer.jsonassert.comparator.CustomComparator;
import org.skyscreamer.jsonassert.comparator.DefaultComparator;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.TestPropertySource;
import org.worldcubeassociation.statistics.util.LoadResourceUtil;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.UncheckedIOException;
import java.nio.file.Files;

import static org.junit.platform.commons.function.Try.success;

@ActiveProfiles("test")
@TestPropertySource(locations = "classpath:application-test.yaml")
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class AbstractTest {

private static final String PROTOCOL_HTTP = "http://";
private static final String TEST_HOST = "localhost";
private static final int API_PORT = 8081;

protected final RequestSpecification SPEC = createRequestSpecification();
@LocalServerPort
private int API_PORT;

private static RequestSpecification createRequestSpecification() {
protected RequestSpecification createRequestSpecification() {
return new RequestSpecBuilder()
.setContentType(ContentType.JSON)
.setBaseUri(String.format("%s%s:%s", PROTOCOL_HTTP, TEST_HOST, API_PORT))
.addFilter(new ResponseLoggingFilter())
.addFilter(new RequestLoggingFilter())
.build();
.setContentType(ContentType.JSON)
.setBaseUri(String.format("%s%s:%s", PROTOCOL_HTTP, TEST_HOST, API_PORT))
.addFilter(new ResponseLoggingFilter())
.addFilter(new RequestLoggingFilter())
.build();
}

public void validateResponse(Object index, Response response, DefaultComparator comparator) {
StackWalker walker = StackWalker.getInstance();
StackWalker.StackFrame stackFrameOptional = walker.walk(stream -> stream
.filter(f -> f.getClassName().contains("org.worldcubeassociation.statistics.integration.controller"))
.findFirst()).orElseThrow(() -> new RuntimeException("I couldn't recover test's stackframe"));
.filter(f -> f.getClassName()
.contains("org.worldcubeassociation.statistics.integration.controller"))
.findFirst())
.orElseThrow(() -> new RuntimeException("I couldn't recover test's stackframe"));

final String methodName = stackFrameOptional.getMethodName();
final String fullClassName = stackFrameOptional.getClassName();
final String className = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_HYPHEN,
fullClassName.substring(fullClassName.lastIndexOf(".") + 1));
fullClassName.substring(fullClassName.lastIndexOf(".") + 1));

String resource = String.format("jsons/%s/%s_%s.json", className, methodName, index.toString());
String resource = String.format("jsons/%s/%s_%s.json", className, methodName,
index.toString());

final String actualPayload = response.getBody().prettyPrint();

Expand All @@ -64,7 +69,7 @@ public void validateResponse(Object index, Response response, DefaultComparator
final String expectedPayload = LoadResourceUtil.getResource(resource);

JSONAssert.assertEquals(
expectedPayload, actualPayload, comparator);
expectedPayload, actualPayload, comparator);

} catch (UncheckedIOException | JSONException ex) {
if (ex.getCause() instanceof FileNotFoundException) {
Expand All @@ -75,7 +80,8 @@ public void validateResponse(Object index, Response response, DefaultComparator
success("Test file did not exist. File created and test succeeded");

} catch (Exception e) {
throw new AbstractTest.TestCasePayloadGeneratedException(actualPayload, resource);
throw new AbstractTest.TestCasePayloadGeneratedException(actualPayload,
resource);
}
}
}
Expand All @@ -86,21 +92,23 @@ public void validateResponse(Object index, Response response) {
}

private static class TestCasePayloadGeneratedException extends RuntimeException {

private static final int MAX_PAYLOAD_LEN = 50;

public TestCasePayloadGeneratedException(String payload, String resource) {
super(String.format("Resource \"%s\" not found for this execution." +
" So resources was generated based on this \"%s %s\" payload." +
" Run tests again!", resource
, payload.substring(0, Math.min(payload.length(), MAX_PAYLOAD_LEN))
, payload.length() > MAX_PAYLOAD_LEN ? "..." : ""
)
" So resources was generated based on this \"%s %s\" payload." +
" Run tests again!", resource
, payload.substring(0, Math.min(payload.length(), MAX_PAYLOAD_LEN))
, payload.length() > MAX_PAYLOAD_LEN ? "..." : ""
)
);
}
}

public void validateResponseIgnoreAttribute(int index, Response response, String ignoreAttribute) {
public void validateResponseIgnoreAttribute(int index, Response response,
String ignoreAttribute) {
validateResponse(index, response, new CustomComparator(JSONCompareMode.STRICT,
new Customization(ignoreAttribute, (o1, o2) -> true)));
new Customization(ignoreAttribute, (o1, o2) -> true)));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ public class BestEverRanksControllerIT extends AbstractTest {
@ParameterizedTest(name = "{displayName} {0}: status {1} wcaId {2} reason {3}")
public void list(int index, HttpStatus status, String wcaId, String reason) {
Response response = given()
.spec(super.SPEC)
.spec(super.createRequestSpecification())
.when()
.get(BASE_PATH + "{wca_id}", wcaId)
.then()
Expand All @@ -54,7 +54,7 @@ static Stream<Arguments> listArguments() {
@ParameterizedTest(name = "{displayName} {0}: status {1} body {2} reason {3}")
public void generateByEvents(int index, HttpStatus status, Map<String, Object> body, String reason) {
Response response = given()
.spec(super.SPEC)
.spec(super.createRequestSpecification())
.body(body)
.when()
.post(BASE_PATH + "generate")
Expand All @@ -79,7 +79,7 @@ static Stream<Arguments> generateByEventsArguments() {
@ParameterizedTest(name = "{displayName} {0}: status {1} reason {2}")
public void generateAll(int index, HttpStatus status, String reason) {
Response response = given()
.spec(super.SPEC)
.spec(super.createRequestSpecification())
.when()
.post(BASE_PATH + "generate/all")
.then()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ public class DatabaseQueryControllerIT extends AbstractTest {
@ParameterizedTest(name = "{displayName} {0}: status {1} token {2} body {3} reason {4}")
public void query(int index, HttpStatus status, String token, Map<String, Object> body, String reason) {
Response response = given()
.spec(super.SPEC)
.spec(super.createRequestSpecification())
.header("Authorization", token)
.body(body)
.when()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ public class RecordEvolutionControllerIT extends AbstractTest {
@Test
public void getAvailableEvents() {
Response response = given()
.spec(super.SPEC)
.spec(super.createRequestSpecification())
.when()
.get(BASE_PATH + "event")
.then()
Expand All @@ -38,7 +38,7 @@ public void getAvailableEvents() {
@ParameterizedTest(name = "{displayName} {0}: status {1} reason {2}")
public void getByEvent(int index, HttpStatus status, String event) {
Response response = given()
.spec(super.SPEC)
.spec(super.createRequestSpecification())
.when()
.get(BASE_PATH + event)
.then()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ public class StatisticsControllerIT extends AbstractTest {
@DisplayName("Test statistics generated from yaml files")
public void generateAll() {
given()
.spec(super.SPEC)
.spec(super.createRequestSpecification())
.when()
.post(BASE_PATH + "generate-from-sql")
.then()
Expand All @@ -41,7 +41,7 @@ public void generateAll() {
@DisplayName("Test statistics generated from specific yaml file")
public void generateFromFile(int index, HttpStatus status, String fileName) {
Response response = given()
.spec(super.SPEC)
.spec(super.createRequestSpecification())
.when()
.post(BASE_PATH + "generate-from-sql/" + fileName)
.then()
Expand All @@ -64,7 +64,7 @@ private static Stream<Arguments> generateFromFileArguments() {
@DisplayName("Test statistics generated from yaml files")
public void deleteAll() {
given()
.spec(super.SPEC)
.spec(super.createRequestSpecification())
.when()
.delete(BASE_PATH)
.then()
Expand All @@ -80,7 +80,7 @@ public void listByTerm(int index, HttpStatus status, String term, String reason)
generateAll();

Response response = given()
.spec(super.SPEC)
.spec(super.createRequestSpecification())
.param("term", term)
.when()
.get(BASE_PATH + "list")
Expand Down Expand Up @@ -108,7 +108,7 @@ public void byPath(int index, HttpStatus status, String path, String reason) {
generateAll();

Response response = given()
.spec(super.SPEC)
.spec(super.createRequestSpecification())
.when()
.get(BASE_PATH + "list/{pathId}", path)
.then()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ public class SumOfRanksControllerIT extends AbstractTest {

private Response generateSor() {
return given()
.spec(super.SPEC)
.spec(super.createRequestSpecification())
.when()
.post(BASE_PATH)
.then()
Expand Down Expand Up @@ -59,7 +59,7 @@ public void list(int index, HttpStatus status, String resultType, String regionT
generateSor();

Response response = given()
.spec(super.SPEC)
.spec(super.createRequestSpecification())
.params(params)
.when()
.get(BASE_PATH + "{resultType}/{regionType}/{region}", resultType, regionType, region)
Expand Down Expand Up @@ -101,7 +101,7 @@ public void meta() {
generateSor();

Response response = given()
.spec(super.SPEC)
.spec(super.createRequestSpecification())
.when()
.get(BASE_PATH + "meta")
.then()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ public class WcaControllerIT extends AbstractTest {
@ParameterizedTest(name = "index {0} status {1} token {2} reason {3}")
public void userInfo(int index, HttpStatus status, String token, String reason) {
Response response = given()
.spec(super.SPEC)
.spec(super.createRequestSpecification())
.header("Authorization", token)
.when()
.get(BASE_PATH + "user")
Expand Down

0 comments on commit 2d5d72b

Please sign in to comment.