Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Karate-Tools] Sonar Issues Fix #8

Merged
merged 2 commits into from
Dec 12, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 2 additions & 6 deletions code/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,16 +7,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]

- [#7](https://github.com/InditexTech/karatetools-oss/issues/7) [Karate-Tools] Sonar Issues Fix

## [4.0.0] - 2024-11-26

- First Open Source Release

## [3.1.0] - 2024-10-01

- Last Internal to Inditex Release

[Unreleased]: https://github.com/InditexTech/karatetools-oss/compare/4.0.0...HEAD

[4.0.0]: https://github.com/InditexTech/karatetools-oss/compare/3.1.0...4.0.0

[3.1.0]: https://github.com/InditexTech/karatetools-oss/releases/tag/3.1.0
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
import org.apache.kafka.common.KafkaFuture;
import org.apache.kafka.common.Node;
import org.apache.kafka.common.config.SaslConfigs;
import org.assertj.core.api.ThrowableAssert.ThrowingCallable;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.mockito.MockedStatic;
Expand Down Expand Up @@ -117,7 +118,6 @@ void when_broker_and_registry_security_enabled_config_expect_fields_informed() {
.isEqualTo(config.get(SaslConfigs.SASL_MECHANISM));
assertThat(client.getConfiguration().getProperty(SaslConfigs.SASL_JAAS_CONFIG))
.isEqualTo(config.get(SaslConfigs.SASL_JAAS_CONFIG));

// Registry
assertThat(client.getConfiguration().getProperty(AbstractKafkaSchemaSerDeConfig.SCHEMA_REGISTRY_URL_CONFIG))
.isEqualTo(config.get(AbstractKafkaSchemaSerDeConfig.SCHEMA_REGISTRY_URL_CONFIG));
Expand Down Expand Up @@ -164,14 +164,12 @@ void when_first_call_with_null_admin_expect_exception() {
try (final MockedStatic<Admin> staticAdmin = mockStatic(Admin.class)) {
staticAdmin.when(() -> Admin.create(any(Properties.class))).thenReturn(null);

assertThatThrownBy(() -> {
client.available();
}).isInstanceOf(KafkaException.class).hasMessage("Unable to access Kafka Admin client");
final ThrowingCallable result = client::available;

assertThatThrownBy(result).isInstanceOf(KafkaException.class).hasMessage("Unable to access Kafka Admin client");
assertThat(logWatcher.list).anyMatch(log -> log.getLevel().equals(Level.ERROR)
&& log.getFormattedMessage().contains("KafkaAbstractClient => available() KafkaException")
&& log.getThrowableProxy().getMessage().contains("Unable to access Kafka Admin client"));

}
}

Expand All @@ -185,10 +183,9 @@ void when_first_call_with_null_cluster_expect_exception() {
staticAdmin.when(() -> Admin.create(any(Properties.class))).thenReturn(admin);
when(admin.describeCluster()).thenReturn(null);

assertThatThrownBy(() -> {
client.available();
}).isInstanceOf(KafkaException.class).hasMessage("Unable to access Kafka cluster");
final ThrowingCallable result = client::available;

assertThatThrownBy(result).isInstanceOf(KafkaException.class).hasMessage("Unable to access Kafka cluster");
assertThat(logWatcher.list).anyMatch(log -> log.getLevel().equals(Level.ERROR)
&& log.getFormattedMessage().contains("KafkaAbstractClient => available() KafkaException")
&& log.getThrowableProxy().getMessage().contains("Unable to access Kafka cluster"));
Expand All @@ -207,10 +204,9 @@ void when_first_call_with_null_nodes_future_expect_exception() {
when(admin.describeCluster()).thenReturn(describeClusterResult);
when(describeClusterResult.nodes()).thenReturn(null);

assertThatThrownBy(() -> {
client.available();
}).isInstanceOf(KafkaException.class).hasMessage("Unable to access Kafka cluster nodes [null]");
final ThrowingCallable result = client::available;

assertThatThrownBy(result).isInstanceOf(KafkaException.class).hasMessage("Unable to access Kafka cluster nodes [null]");
assertThat(logWatcher.list).anyMatch(log -> log.getLevel().equals(Level.ERROR)
&& log.getFormattedMessage().contains("KafkaAbstractClient => available() KafkaException")
&& log.getThrowableProxy().getMessage().contains("Unable to access Kafka cluster nodes [null]"));
Expand All @@ -232,10 +228,9 @@ void when_first_call_with_null_nodes_list_expect_exception() throws InterruptedE
when(describeClusterResult.nodes()).thenReturn(nodes);
when(nodes.get()).thenReturn(null);

assertThatThrownBy(() -> {
client.available();
}).isInstanceOf(KafkaException.class).hasMessage("Unable to access Kafka cluster nodes [null list]");
final ThrowingCallable result = client::available;

assertThatThrownBy(result).isInstanceOf(KafkaException.class).hasMessage("Unable to access Kafka cluster nodes [null list]");
assertThat(logWatcher.list).anyMatch(log -> log.getLevel().equals(Level.ERROR)
&& log.getFormattedMessage().contains("KafkaAbstractClient => available() KafkaException")
&& log.getThrowableProxy().getMessage().contains("Unable to access Kafka cluster nodes [null list]"));
Expand All @@ -257,10 +252,9 @@ void when_first_call_with_empty_nodes_expect_exception() throws InterruptedExcep
when(describeClusterResult.nodes()).thenReturn(nodes);
when(nodes.get()).thenReturn(List.of());

assertThatThrownBy(() -> {
client.available();
}).isInstanceOf(KafkaException.class).hasMessage("Unable to access Kafka cluster nodes [empty list]");
final ThrowingCallable result = client::available;

assertThatThrownBy(result).isInstanceOf(KafkaException.class).hasMessage("Unable to access Kafka cluster nodes [empty list]");
assertThat(logWatcher.list).anyMatch(log -> log.getLevel().equals(Level.ERROR)
&& log.getFormattedMessage().contains("KafkaAbstractClient => available() KafkaException")
&& log.getThrowableProxy().getMessage().contains("Unable to access Kafka cluster nodes [empty list]"));
Expand All @@ -283,10 +277,9 @@ void when_first_call_with_interrupted_exception_expect_exception() throws Interr
when(describeClusterResult.nodes()).thenReturn(nodes);
when(nodes.get()).thenThrow(new InterruptedException("Interrupted exception"));

assertThatThrownBy(() -> {
client.available();
}).isInstanceOf(KafkaException.class).hasMessage("Thread interrupted");
final ThrowingCallable result = client::available;

assertThatThrownBy(result).isInstanceOf(KafkaException.class).hasMessage("Thread interrupted");
assertThat(logWatcher.list).anyMatch(log -> log.getLevel().equals(Level.ERROR)
&& log.getFormattedMessage().contains("KafkaAbstractClient => available() InterruptedException")
&& log.getThrowableProxy().getMessage().contains("Interrupted exception"));
Expand All @@ -308,10 +301,9 @@ void when_first_call_with_other_exception_expect_exception() throws InterruptedE
when(describeClusterResult.nodes()).thenReturn(nodes);
when(nodes.get()).thenThrow(new RuntimeException("Unknown exception"));

assertThatThrownBy(() -> {
client.available();
}).isInstanceOf(KafkaException.class).hasMessage("Unable to access Kafka cluster");
final ThrowingCallable result = client::available;

assertThatThrownBy(result).isInstanceOf(KafkaException.class).hasMessage("Unable to access Kafka cluster");
assertThat(logWatcher.list).anyMatch(log -> log.getLevel().equals(Level.ERROR)
&& log.getFormattedMessage().contains("KafkaAbstractClient => available() Exception")
&& log.getThrowableProxy().getMessage().contains("Unknown exception"));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ void setup() {
logWatcher = new ListAppender<>();
logWatcher.start();
final Logger logger = (Logger) LoggerFactory.getLogger(KarateClientLogger.class);
logger.setLevel(Level.ALL);
logger.setLevel(Level.TRACE);
logger.addAppender(logWatcher);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -124,12 +124,12 @@ protected static KarateMockData build(final OperationPath operationPath, final S
}
}
// Set Body Example if Schema defined
final Schema requestSchema = OpenApiGenerators.getRequestSchema(operation);
final Schema requestSchema = OpenApiUtils.getRequestSchema(operation);
if (requestSchema != null) {
mockData.setRequest(OpenApiExampleGenerator.generateExample(openApi, requestSchema));
}
// Set Response if Schema defined
final Schema responseSchema = OpenApiGenerators.getResponseSchema(operation, responseStatus);
final Schema responseSchema = OpenApiUtils.getResponseSchema(operation, responseStatus);
if (responseSchema != null) {
mockData.setResponse(OpenApiExampleGenerator.generateExample(openApi, responseSchema));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -103,12 +103,12 @@ protected static KarateTestData build(final Operation operation, final String st
// Set Headers Example if defined
setHeaders(operation, openApi, testData);
// Set Body Example if Schema defined
final Schema requestSchema = OpenApiGenerators.getRequestSchema(operation);
final Schema requestSchema = OpenApiUtils.getRequestSchema(operation);
if (requestSchema != null) {
testData.setBody(OpenApiExampleGenerator.generateExample(openApi, requestSchema));
}
// Set Response Matches if Schema defined
final Schema responseSchema = OpenApiGenerators.getResponseSchema(operation, statusCode);
final Schema responseSchema = OpenApiUtils.getResponseSchema(operation, statusCode);
if (responseSchema != null) {
testData.setResponseMatches("#(read('classpath:" + responseSchemaClassPath + "'))");
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,18 +4,13 @@
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.TreeMap;

import dev.inditex.karate.openapi.data.KarateFunctionalFeature.FunctionalTestStep;
import dev.inditex.karate.openapi.data.KarateSmokeFeature.SmokeTestResponse;
import dev.inditex.karate.openapi.data.OpenApiParser.OperationPath;

import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.Operation;
import io.swagger.v3.oas.models.media.MediaType;
import io.swagger.v3.oas.models.media.Schema;

/**
* The Class OpenApiGenerators.
Expand All @@ -40,8 +35,8 @@ protected OpenApiGenerators() {
public static List<Path> generateOperations(final Path root, final MavenArtifact artifact, final List<OperationPath> operations) {
final List<Path> outputs = new ArrayList<>();
for (final OperationPath operationPath : operations) {
final Path operationFolder = getOperationFolder(root, artifact, operationPath);
outputs.addAll(KarateOperation.save(root, operationFolder, artifact, operationPath, getResponseSchemas(operationPath)));
final Path operationFolder = OpenApiUtils.getOperationFolder(root, artifact, operationPath);
outputs.addAll(KarateOperation.save(root, operationFolder, artifact, operationPath, OpenApiUtils.getResponseSchemas(operationPath)));
}
return outputs;
}
Expand All @@ -63,9 +58,9 @@ public static List<Path> generateSmokeTests(final Path root, final MavenArtifact
final List<SmokeTestResponse> responses = new ArrayList<>();
final Set<String> responseCodes = op.operation().getResponses().keySet();
responseCodes.forEach(code -> responses.add(
new SmokeTestResponse(code, getResponseSchemaClasspath(root, artifact, op, code))));
new SmokeTestResponse(code, OpenApiUtils.getResponseSchemaClasspath(root, artifact, op, code))));
outputs.addAll(KarateSmokeFeature.save(targetPath, op.operation(),
getOperationClasspath(root, artifact, op), responses, openApi));
OpenApiUtils.getOperationClasspath(root, artifact, op), responses, openApi));
});
return outputs;
}
Expand All @@ -90,8 +85,8 @@ public static List<Path> generateFunctionalTest(final Path root, final MavenArti
final OperationPath operationPath = entry.getKey();
entry.getValue().forEach(response -> steps.add(new FunctionalTestStep(
operationPath.operation(), response,
getOperationClasspath(root, artifact, operationPath),
getResponseSchemaClasspath(root, artifact, operationPath, response))));
OpenApiUtils.getOperationClasspath(root, artifact, operationPath),
OpenApiUtils.getResponseSchemaClasspath(root, artifact, operationPath, response))));
});
outputs.addAll(KarateFunctionalFeature.save(targetPath, testName, inlineMocks, steps, openApi));
return outputs;
Expand All @@ -113,7 +108,7 @@ public static List<Path> generateMockData(final Path root, final MavenArtifact a
final Boolean inlineMocks, final MavenArtifact functionalArtifact, final String testName,
final Map<OperationPath, Set<String>> operationsResponses,
final OpenAPI openApi) {
final Path targetPath = getMockDataTargetPath(root, artifact, inlineMocks, functionalArtifact, testName);
final Path targetPath = OpenApiUtils.getMockDataTargetPath(root, artifact, inlineMocks, functionalArtifact, testName);
final List<Path> outputs = new ArrayList<>();
operationsResponses.entrySet().forEach(entry -> {
final OperationPath operationPath = entry.getKey();
Expand All @@ -122,128 +117,4 @@ public static List<Path> generateMockData(final Path root, final MavenArtifact a
return outputs;
}

/**
* Gets the operation classpath.
*
* @param root the root
* @param artifact the artifact
* @param operationPath the operation path
* @return the operation classpath
*/
public static String getOperationClasspath(final Path root, final MavenArtifact artifact, final OperationPath operationPath) {
final Path operationFolder = getOperationFolder(root, artifact, operationPath);
final Path operationFile = operationFolder.resolve(operationPath.operation().getOperationId() + ".feature");
return root.relativize(operationFile).toString().replace("\\", "/");
}

/**
* Gets the response schema classpath.
*
* @param root the root
* @param artifact the artifact
* @param operationPath the operation path
* @param code the code
* @return the response schema classpath
*/
public static String getResponseSchemaClasspath(final Path root, final MavenArtifact artifact, final OperationPath operationPath,
final String code) {
final Path operationFolder = getOperationFolder(root, artifact, operationPath);
return KarateSchema.getSchemaClasspath(root, operationFolder, operationPath.operation().getOperationId(), code);
}

/**
* Gets the response schema.
*
* @param operation the operation
* @param code the code
* @return the response schema
*/
@SuppressWarnings("rawtypes")
public static Schema getResponseSchema(final Operation operation, final String code) {
if (operation.getResponses() != null
&& operation.getResponses().get(code) != null
&& operation.getResponses().get(code).getContent() != null) {
final Optional<MediaType> mediaType = operation.getResponses().get(code).getContent().values().stream().findFirst();
if (mediaType.isPresent() && mediaType.get().getSchema() != null) {
return mediaType.get().getSchema();
}
}
return null;
}

/**
* Gets the request schema.
*
* @param operation the operation
* @return the request schema
*/
@SuppressWarnings("rawtypes")
public static Schema getRequestSchema(final Operation operation) {
if (operation.getRequestBody() != null && operation.getRequestBody().getContent() != null) {
final Optional<MediaType> mediaType =
operation.getRequestBody().getContent().values().stream().findFirst();
if (mediaType.isPresent() && mediaType.get().getSchema() != null) {
return mediaType.get().getSchema();
}
}
return null;
}

/**
* Gets the mock data target path.
*
* @param root the root
* @param artifact the artifact
* @param inlineMocks the inline mocks
* @param functionalArtifact the functional artifact
* @param testName the test name
* @return the mock data target path
*/
protected static Path getMockDataTargetPath(final Path root, final MavenArtifact artifact, final Boolean inlineMocks,
final MavenArtifact functionalArtifact, final String testName) {
// PATH: mocks/templates/standalone/ARTIFACT_ID/TAG/XXXX_operationId_XXX.yml"
Path targetPath = root.resolve("mocks/templates/standalone").resolve(artifact.artifactIdToPath());
if (Boolean.TRUE.equals(inlineMocks)) {
// PATH: <FUNCTIONAL_TEST_PATH>/mocks/ARTIFACT_ID/TAG/XXXX_operationId_XXX.yml"
targetPath = root.resolve(functionalArtifact.toPath()).resolve("functional").resolve(testName).resolve("mocks")
.resolve(artifact.artifactIdToPath());
}
return targetPath;
}

/**
* Gets the operation folder.
*
* @param root the root
* @param artifact the artifact
* @param operationPath the operation path
* @return the operation folder
*/
protected static Path getOperationFolder(final Path root, final MavenArtifact artifact, final OperationPath operationPath) {
final Path targetPath = root.resolve("apis").resolve(artifact.toPath());
final String tag = operationPath.operation().getTags() != null ? operationPath.operation().getTags().get(0) : "NoTag";
return targetPath.resolve(tag).resolve(operationPath.operation().getOperationId());
}

/**
* Gets the response schemas.
*
* @param operationPath the operation path
* @return the response schemas
*/
@SuppressWarnings("rawtypes")
protected static Map<String, Schema> getResponseSchemas(final OperationPath operationPath) {
final Map<String, Schema> schemas = new TreeMap<>();
operationPath.operation().getResponses().entrySet().forEach(e -> {
final String returnCode = e.getKey();
if (e.getValue().getContent() != null) {
final Optional<MediaType> mediaType = e.getValue().getContent().values().stream().findFirst();
if (mediaType.isPresent() && mediaType.get().getSchema() != null) {
schemas.put(returnCode, mediaType.get().getSchema());
}
}
});
return schemas;
}

}
Loading
Loading