Skip to content

Commit

Permalink
chore: Add unit test for additional branches
Browse files Browse the repository at this point in the history
  • Loading branch information
en-milie committed Sep 9, 2024
1 parent 3889bf7 commit b9b19af
Show file tree
Hide file tree
Showing 8 changed files with 115 additions and 11 deletions.
2 changes: 2 additions & 0 deletions src/main/java/com/endava/cats/args/FilesArguments.java
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,7 @@ public class FilesArguments {

@CommandLine.Option(names = {"--pathsRunOrder"},
description = "Specifies the order in which the paths will be executed. The paths are on each line. The order is the one in which they will be executed")
@Setter
private File pathsOrderFile;

@CommandLine.Option(names = {"-Q"},
Expand Down Expand Up @@ -123,6 +124,7 @@ public class FilesArguments {
@CommandLine.Option(names = {"--mutators", "-m"},
description = "A folder containing custom mutators. This argument is taken in consideration only when using the `cats random` command")
@Getter
@Setter
private File mutatorsFolder;


Expand Down
4 changes: 2 additions & 2 deletions src/main/java/com/endava/cats/factory/FuzzingDataFactory.java
Original file line number Diff line number Diff line change
Expand Up @@ -184,7 +184,7 @@ private Schema<?> createSyntheticSchemaForGet(List<Parameter> operationParameter
return syntheticSchema;
}

private @NotNull List<Parameter> getResolvedParameters(List<Parameter> operationParameters) {
List<Parameter> getResolvedParameters(List<Parameter> operationParameters) {
return Optional.ofNullable(operationParameters)
.orElseGet(Collections::emptyList)
.stream()
Expand Down Expand Up @@ -384,7 +384,7 @@ private KeyValuePair<String, Schema<?>> createSyntheticSchemaForGet(Operation op
return new KeyValuePair<>(SYNTH_SCHEMA_NAME + operation.getOperationId(), syntheticSchema);
}

private Set<String> extractExamples(MediaType mediaType) {
Set<String> extractExamples(MediaType mediaType) {
Set<String> examples = new HashSet<>();
examples.add(Optional.ofNullable(mediaType.getExample()).orElse("").toString());
if (mediaType.getExamples() != null) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,11 +39,6 @@ public class StringGenerator {
*/
public static final String ALPHANUMERIC_PLUS = "[a-zA-Z0-9]+";

/**
* Default alphanumeric pattern.
*/
public static final String ALPHANUMERIC = "[a-zA-Z0-9]";

private static final int MAX_ATTEMPTS_GENERATE = 5;

private static final String ALPHANUMERIC_VALUE = "CatsIsCool";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -172,7 +172,7 @@ private boolean syntheticSchema(String currentProperty) {
return currentProperty.startsWith(SYNTH_SCHEMA_NAME);
}

private <T> Object formatExampleIfNeeded(Schema<T> property) {
<T> Object formatExampleIfNeeded(Schema<T> property) {
if (CatsModelUtils.isDateSchema(property)) {
return DATE_FORMATTER.format(LocalDate.ofInstant(((Date) property.getExample()).toInstant(), ZoneId.systemDefault()));
}
Expand Down
18 changes: 17 additions & 1 deletion src/test/java/com/endava/cats/args/FilesArgumentsTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,7 @@ void shouldReturnEmptyUrlParams() {

@Test
void shouldProperlyParseYamlFile() throws Exception {
Map<String, Map<String, Object>> yaml = new FilesArguments().parseYaml("src/test/resources/test.yml");
Map<String, Map<String, Object>> yaml = FilesArguments.parseYaml("src/test/resources/test.yml");

org.assertj.core.api.Assertions.assertThat(yaml.get("all")).isNotNull();
org.assertj.core.api.Assertions.assertThat(yaml.get("all").get("Authorization")).isNotNull();
Expand Down Expand Up @@ -202,4 +202,20 @@ void shouldReturnUrlParamValue() {
String urlParamValue = filesArguments.getUrlParam("param3");
org.assertj.core.api.Assertions.assertThat(urlParamValue).isEqualTo("value3");
}

@Test
void shouldLoadPathsOrder() throws Exception {
FilesArguments filesArguments = new FilesArguments();
filesArguments.setPathsOrderFile(new File("src/test/resources/paths.order"));
filesArguments.loadPathsOrder();
org.assertj.core.api.Assertions.assertThat(filesArguments.getPathsOrder()).hasSize(2).containsExactly("/path1", "/path2");
}

@Test
void shouldLoadMutators() throws Exception {
FilesArguments filesArguments = new FilesArguments();
filesArguments.setMutatorsFolder(new File("src/test/resources/mutators"));

org.assertj.core.api.Assertions.assertThat(filesArguments.getMutatorsFolder()).isDirectory();
}
}
32 changes: 32 additions & 0 deletions src/test/java/com/endava/cats/factory/FuzzingDataFactoryTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,16 @@
import com.endava.cats.model.FuzzingData;
import com.endava.cats.openapi.OpenApiUtils;
import com.endava.cats.util.JsonUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.google.gson.JsonParser;
import io.quarkus.test.junit.QuarkusTest;
import io.swagger.parser.OpenAPIParser;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.PathItem;
import io.swagger.v3.oas.models.examples.Example;
import io.swagger.v3.oas.models.headers.Header;
import io.swagger.v3.oas.models.media.MediaType;
import io.swagger.v3.oas.models.media.Schema;
import io.swagger.v3.oas.models.parameters.Parameter;
import io.swagger.v3.parser.core.models.ParseOptions;
Expand Down Expand Up @@ -726,4 +730,32 @@ void shouldGenerateOpenApi31Specs() throws Exception {
"category#id",
"residency");
}

@Test
void shouldRecordErrorWhenParamRefDoesNotExist() throws Exception {
List<FuzzingData> dataList = setupFuzzingData("/pet-types", "src/test/resources/petstore.yml");
Assertions.assertThat(dataList).hasSize(2);

Parameter param1 = new Parameter();
param1.set$ref("#/components/parameters/param1");
Assertions.assertThat(catsGlobalContext.getRecordedErrors()).isEmpty();

List<Parameter> resolvedParameters = fuzzingDataFactory.getResolvedParameters(List.of(param1));
Assertions.assertThat(resolvedParameters).isEmpty();
Assertions.assertThat(catsGlobalContext.getRecordedErrors()).hasSize(1);
}

@Test
void shouldExtractMultiLevelExamples() throws Exception {
ObjectMapper objectMapper = new ObjectMapper();
ObjectNode exampleMapObject = objectMapper.createObjectNode();
exampleMapObject.set("WORKER_COMPENSATION_PAYRATE_POST_PATCH", objectMapper.createObjectNode().put("value", "catsIsCool"));
catsGlobalContext.getExampleMap().put("JSON_WORKER_EXAMPLES", new Example().value(exampleMapObject));
MediaType mediaType = new MediaType();
mediaType.setExamples(Map.of("example1", new Example().$ref("#/components/examples/JSON_WORKER_EXAMPLES/value/WORKER_COMPENSATION_PAYRATE_POST_PATCH"), "example2", new Example().value("example2")));

Set<String> examples = fuzzingDataFactory.extractExamples(mediaType);

Assertions.assertThat(examples).hasSize(2).containsExactly("example2", "\"catsIsCool\"");
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,7 @@ void shouldGenerateEmptyWhenLengthZero() {

@ParameterizedTest
@CsvSource(value = {"(^$)|^(((\\+|00)(9[976]\\d|8[987530]\\d|6[987]\\d|5[90]\\d|42\\d|3[875]\\d|2[98654321]\\d|9[8543210]|8[6421]|6[6543210]|5[87654321]|4[987654310]|3[9643210]|2[70]|7|1)([[:space:]]?))?([\\d]{4}\\d{1,9})$);^(((\\+|00)(9[976]\\d|8[987530]\\d|6[987]\\d|5[90]\\d|42\\d|3[875]\\d|2[98654321]\\d|9[8543210]|8[6421]|6[6543210]|5[87654321]|4[987654310]|3[9643210]|2[70]|7|1)([[:space:]]?))?([\\d]{4}\\d{1,9})$)",
"/^[^<>]*$/;^[^<>]*", "^[A-Z-a-z0-9]{4}[A-Z-a-z]{2}[A-Z-a-z0-9]{2}([A-Z-a-z0-9]{3})?$;^[A-Z-a-z0-9]{4}[A-Z-a-z]{2}[A-Z-a-z0-9]{2}([A-Z-a-z0-9]{3})?", "/^.*[a-z]+.*$/i;^.*[a-z]+.*"}, delimiter = ';')
"/^[^<>]*$/;^[^<>]*", "^[A-Z-a-z0-9]{4}[A-Z-a-z]{2}[A-Z-a-z0-9]{2}([A-Z-a-z0-9]{3})?$;^[A-Z-a-z0-9]{4}[A-Z-a-z]{2}[A-Z-a-z0-9]{2}([A-Z-a-z0-9]{3})?", "/^.*[a-z]+.*$/i;^.*[a-z]+.*", ";[a-zA-Z0-9]+", "/^[a-z];^[a-z]"}, delimiter = ';')
void shouldCleanPattern(String pattern, String expected) {
String cleaned = StringGenerator.cleanPattern(pattern);
Assertions.assertThat(cleaned).isEqualTo(expected);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@

import com.endava.cats.context.CatsGlobalContext;
import com.endava.cats.generator.format.api.ValidDataFormat;
import com.endava.cats.util.JsonUtils;
import com.endava.cats.openapi.OpenApiUtils;
import com.endava.cats.util.JsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import io.swagger.parser.OpenAPIParser;
import io.swagger.v3.oas.models.OpenAPI;
Expand All @@ -16,8 +16,13 @@
import org.junit.jupiter.params.provider.CsvSource;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.time.Instant;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;
import java.util.Map;

Expand Down Expand Up @@ -104,6 +109,60 @@ void shouldComputeProperArrayLength(Integer min, Integer max, int expected) {
Assertions.assertThat(result).isEqualTo(expected);
}

@Test
void shouldFormatDateExample() throws Exception {
Schema<Date> schema = new Schema<>();
OpenAPIModelGenerator generator = setupPayloadGenerator();
schema.setExample(Date.from(Instant.parse("2020-01-02T00:00:00Z")));
schema.setType("string");
schema.setFormat("date");

Object formatted = generator.formatExampleIfNeeded(schema);

Assertions.assertThat(formatted).hasToString("2020-01-02");
}

@Test
void shouldRemoveNewLine() throws Exception {
Schema<String> schema = new Schema<>();
OpenAPIModelGenerator generator = setupPayloadGenerator();
schema.setType("string");
schema.setExample("This is a string\nwith a new line");

Object formatted = generator.formatExampleIfNeeded(schema);

Assertions.assertThat(formatted).hasToString("This is a stringwith a new line");
}

@Test
void shouldFormatDateTimeExample() throws Exception {
Schema<Date> schema = new Schema<>();
OpenAPIModelGenerator generator = setupPayloadGenerator();
schema.setExample(OffsetDateTime.of(2020, 1, 2, 0, 0, 0, 0, OffsetDateTime.now(ZoneId.of("UTC")).getOffset()));
schema.setType("string");
schema.setFormat("date-time");

Object formatted = generator.formatExampleIfNeeded(schema);

Assertions.assertThat(formatted).hasToString("2020-01-02T00:00:00Z");
}

@ParameterizedTest
@CsvSource({"binary,Y2F0c0lzQ29vbA==", "byte,Y2F0c0lzQ29vbA=="})
void shouldFormatBinaryExample(String format, String value) throws Exception {
Schema<byte[]> schema = new Schema<>();
OpenAPIModelGenerator generator = setupPayloadGenerator();
schema.setFormat(format);
schema.setType("string");
schema.setExample(value.getBytes(StandardCharsets.UTF_8));

Object formatted = generator.formatExampleIfNeeded(schema);

Assertions.assertThat(formatted).isInstanceOf(byte[].class);
String decoded = new String((byte[]) formatted, StandardCharsets.UTF_8);
Assertions.assertThat(decoded).isEqualTo("catsIsCool");
}

private OpenAPIModelGenerator setupPayloadGenerator() throws IOException {
OpenAPIParser openAPIV3Parser = new OpenAPIParser();
ParseOptions options = new ParseOptions();
Expand Down

0 comments on commit b9b19af

Please sign in to comment.