Skip to content

Commit

Permalink
"Change AsyncApiSamplerTest"
Browse files Browse the repository at this point in the history
  • Loading branch information
GracielaMéndezOlmos committed Dec 1, 2023
1 parent 82baa76 commit e12d7a5
Show file tree
Hide file tree
Showing 4 changed files with 161 additions and 59 deletions.
44 changes: 24 additions & 20 deletions src/main/java/com/sngular/kloadgen/sampler/AsyncApiSampler.java
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ public final SampleResult sample(final Entry entry) {
final var sampleResult = new SampleResult();
sampleResult.setThreadName("AsyncApi Sampler");
sampleResult.sampleStart();
try (final KafkaProducer<Object, Object> producer = new KafkaProducer<>(extractProps())) {
try (final KafkaProducer<Object, Object> producer = getKafkaProducer()) {
generator.setUpGenerator(getSchemaFieldConfiguration());
final var messageVal = generator.nextMessage();
if (Objects.nonNull(messageVal)) {
Expand All @@ -94,13 +94,8 @@ public final SampleResult sample(final Entry entry) {
return sampleResult;
}

private Map<String, Object> extractProps() {
final var properties = new HashMap<String, Object>();
getBrokerConfiguration().forEach(property -> properties.put(property.getPropertyName(), property.getPropertyValue()));
properties.put(PropsKeysHelper.SCHEMA_KEYED_MESSAGE_KEY, Boolean.FALSE);
properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, GenericJsonRecordSerializer.class.getCanonicalName());
properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, GenericJsonRecordSerializer.class.getCanonicalName());
return properties;
public KafkaProducer getKafkaProducer() {
return new KafkaProducer<>(extractProps());
}

public final List<FieldValueMapping> getSchemaFieldConfiguration() {
Expand Down Expand Up @@ -147,6 +142,27 @@ private String prettyPrint(final RecordMetadata recordMetadata) {
return String.format(TEMPLATE, recordMetadata.topic(), recordMetadata.partition(), recordMetadata.offset());
}

private Map<String, Object> extractProps() {
final var properties = new HashMap<String, Object>();
getBrokerConfiguration().forEach(property -> properties.put(property.getPropertyName(), property.getPropertyValue()));
properties.put(PropsKeysHelper.SCHEMA_KEYED_MESSAGE_KEY, Boolean.FALSE);
properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, GenericJsonRecordSerializer.class.getCanonicalName());
properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, GenericJsonRecordSerializer.class.getCanonicalName());
return properties;
}

public final String getAsyncApiSchemaName() {
return this.getPropertyAsString("asyncapischemaname");
}

public final void setAsyncApiSchemaName(final String asyncApiSchemaName) {
this.setProperty("asyncapischemaname", asyncApiSchemaName);
}

private Object getObject(final EnrichedRecord messageVal, final boolean isKloadSerializer) {
return isKloadSerializer ? messageVal : messageVal.getGenericRecord();
}

public final List<PropertyMapping> getBrokerConfiguration() {
final List<PropertyMapping> propertyList = new ArrayList<>();
for (TestElementProperty elementProperty : (List<TestElementProperty>) this.getProperty("brokerConfiguration").getObjectValue()) {
Expand All @@ -163,18 +179,6 @@ public final void setBrokerConfiguration(final List<PropertyMapping> asyncApiSer
this.setProperty(new CollectionProperty("brokerConfiguration", asyncApiServerName));
}

public final String getAsyncApiSchemaName() {
return this.getPropertyAsString("asyncapischemaname");
}

public final void setAsyncApiSchemaName(final String asyncApiSchemaName) {
this.setProperty("asyncapischemaname", asyncApiSchemaName);
}

private Object getObject(final EnrichedRecord messageVal, final boolean isKloadSerializer) {
return isKloadSerializer ? messageVal : messageVal.getGenericRecord();
}

public final AsyncApiFile getAsyncApiFileNode() {
AsyncApiFile asyncApiFile = null;
if (Objects.isNull(asyncApiFileNode)) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,10 +40,11 @@ void testExtractFile() {
final File testFile = fileHelper.getFile("/asyncapi/event-api.yml");
final AsyncApiFile asapfle = new AsyncApiExtractorImpl().processFile(testFile);

org.junit.jupiter.api.Assertions.assertNotNull(asapfle);
org.junit.jupiter.api.Assertions.assertEquals("{user_signedup=user_signedup}", asapfle.getApiSchemaList().toString());
org.junit.jupiter.api.Assertions.assertEquals("{production=AsyncApiServer(name=production, url=mqtt://test.mosquitto.org, protocol=mqtt, description=Test MQTT broker)}",
asapfle.getApiServerMap().toString());
Assertions.assertThat(asapfle).isNotNull();
Assertions.assertThat(asapfle.getApiSchemaList().toString()).isEqualTo("{user_signedup=user_signedup}");
Assertions.assertThat(asapfle.getApiServerMap().toString()).isEqualTo("{production=AsyncApiServer(name=production," +
" url=mqtt://test.mosquitto.org, protocol=mqtt," +
" description=Test MQTT broker)}");
}

@Test
Expand Down
150 changes: 115 additions & 35 deletions src/test/java/com/sngular/kloadgen/sampler/AsyncApiSamplerTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -8,35 +8,54 @@

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.stream.Stream;

import com.sngular.kloadgen.extractor.ApiExtractor;
import com.sngular.kloadgen.parsedschema.JsonParsedSchema;
import com.sngular.kloadgen.processor.fixture.JsonSchemaFixturesConstants;
import java.util.Properties;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
import com.sngular.kloadgen.extractor.asyncapi.AsyncApiExtractorImpl;
import com.sngular.kloadgen.extractor.model.AsyncApiFile;
import com.sngular.kloadgen.model.FieldValueMapping;
import com.sngular.kloadgen.model.PropertyMapping;
import com.sngular.kloadgen.testutil.FileHelper;
import com.sngular.kloadgen.util.ProducerKeysHelper;
import com.sngular.kloadgen.util.PropsKeysHelper;
import org.apache.jmeter.samplers.Entry;
import org.apache.jmeter.threads.JMeterContext;
import org.apache.jmeter.threads.JMeterContextService;
import org.apache.jmeter.threads.JMeterVariables;
import org.apache.jmeter.util.JMeterUtils;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.mockito.Answers;
import org.mockito.MockedStatic;
import org.mockito.Mockito;

class AsyncApiSamplerTest {

private static AsyncApiFile asyncApiFileNode;

private final FileHelper fileHelper = new FileHelper();

private final Properties properties = new Properties();

private final KafkaProducer kafkaProducer = Mockito.mock(KafkaProducer.class);

private final Entry entry = new Entry();

private final ObjectMapper om = new ObjectMapper(new YAMLFactory());

private JMeterContext jmcx;

private AsyncApiSampler sampler = new AsyncApiSampler();

private ApiExtractor apiExtractor;
//@Captor
//private ArgumentCaptor<Schema> argumentCaptor = ArgumentCaptor.forClass(Schema.class);

private static Stream<Object> parametersForConfigureValueGeneratorTest() {
return Stream.of("localhost:8081", "");
}
private MockedStatic<JMeterContextService> jmeterContextServiceMockedStatic;

@BeforeEach
public final void setUp() throws IOException {
Expand All @@ -46,37 +65,98 @@ public final void setUp() throws IOException {
jmcx = JMeterContextService.getContext();
jmcx.setVariables(new JMeterVariables());
JMeterUtils.setLocale(Locale.ENGLISH);
sampler = new AsyncApiSampler();
apiExtractor = Mockito.mock(ApiExtractor.class);
sampler = new AsyncapiSamplerWrapper(kafkaProducer);
final var testFile = fileHelper.getContent("/asyncapi/event-api.yml");
final JsonNode openApi = om.readTree(testFile);
asyncApiFileNode = new AsyncApiExtractorImpl().processNode(openApi);
jmeterContextServiceMockedStatic = Mockito.mockStatic(JMeterContextService.class, Answers.RETURNS_DEEP_STUBS);

}

/*@Test
void testAsyncApiSampleBasic() throws IOException {
JsonNode asyncApiFileNode = mock(JsonNode.class);
sampler.setAsyncApiFileNode(asyncApiFileNode);
JMeterVariables jmvar = new JMeterVariables();
jmvar.putAll(getVariablesJsonSchema());
@AfterEach
public void tearDown() {
properties.clear();
kafkaProducer.close();
jmeterContextServiceMockedStatic.close();
}

/*@Test
void testAsyncApiSampleBasic() {
sampler.setAsyncApiSchemaName(asyncApiFileNode.getAsyncApiFileNode().path("channels").toString().split("\"")[1]);
sampler.setBrokerConfiguration(getMappings());
sampler.setSchemaFieldConfiguration(getListFieldValueMapping());
sampler.setAsyncApiFileNode(asyncApiFileNode.getAsyncApiFileNode());
Mockito.when(kafkaProducer.send(new ProducerRecord<>("user_signup", Mockito.any()))).thenCallRealMethod();
jmeterContextServiceMockedStatic.when(() -> JMeterContextService.getContext().getProperties()).thenReturn(properties);
//Aquí no sé como relacionar lo que hace el when con el método sample
SampleResult samp = sampler.sample(entry);
Assertions.assertThat(samp).isNotNull()
.isEqualTo(" ");
}*/

public JMeterVariables getVariablesJsonSchema() throws IOException {
public static List<PropertyMapping> getMappings() {

List<PropertyMapping> mappings = new ArrayList<>();
JsonNode serversNode = asyncApiFileNode.getAsyncApiFileNode().path("servers");
if (serversNode != null) {
Iterator<JsonNode> serverNodes = serversNode.elements();
while (serverNodes.hasNext()) {
JsonNode serverNode = serverNodes.next();
String serverUrl = serverNode.get("url").asText();
String serverProtocol = serverNode.get("protocol").asText();
String serverDescription = serverNode.get("description").asText();

mappings.add(new PropertyMapping("url", serverUrl));
mappings.add(new PropertyMapping("protocol", serverProtocol));
mappings.add(new PropertyMapping("description", serverDescription));
}
}
return mappings;
}

final var testFile = fileHelper.getContent("/asyncapi/event-api.yml");
final var parsedSchema = new JsonParsedSchema("test", testFile);

final var variables = new JMeterVariables();
variables.put(PropsKeysHelper.KEY_SCHEMA_TYPE, "JSON");
variables.put(PropsKeysHelper.VALUE_SUBJECT_NAME, "jsonSubject");
variables.put(PropsKeysHelper.KEY_SUBJECT_NAME, "jsonSubject");
variables.put(PropsKeysHelper.VALUE_SCHEMA, String.valueOf(parsedSchema));
variables.put(PropsKeysHelper.KEY_SCHEMA, String.valueOf(parsedSchema));
variables.putObject(PropsKeysHelper.VALUE_SCHEMA_PROPERTIES, JsonSchemaFixturesConstants.SIMPLE_SCHEMA_NONREQUIRED);
variables.put(ProducerKeysHelper.KEY_NAME_STRATEGY, "theStrategy");
return variables;
public static List<FieldValueMapping> getListFieldValueMapping() {

int i = 0;
String field = null;
List<FieldValueMapping> fieldValueMappings = new ArrayList<>();
JsonNode valueFields = asyncApiFileNode.getAsyncApiFileNode().path("components")
.path("schemas")
.path("userSignedUpPayload")
.path("properties");
if (valueFields != null) {
Iterator<JsonNode> fieldValuesNodes = valueFields.elements();
while (fieldValuesNodes.hasNext()) {
JsonNode fieldValuesNode = fieldValuesNodes.next();
String type = fieldValuesNode.get("type").toString().replaceAll("\"", "");
type = type.replaceAll("'", "");
String value = fieldValuesNode.get("description").toString().replaceAll("\"", "");
value = "[" + value.replaceAll("'", "") + "]";

switch (i) {
case 0:
field = "firstName";
break;
case 1:
field = "lastName";
break;
case 2:
field = "email";
break;
case 3:
field = "date";
break;
default:
break;
}

fieldValueMappings.add(new FieldValueMapping(field, type, 0, value, null, null, null));

i++;
}
}
return fieldValueMappings;
}


Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package com.sngular.kloadgen.sampler;

import org.apache.kafka.clients.producer.KafkaProducer;

public class AsyncapiSamplerWrapper extends AsyncApiSampler {

protected AsyncapiSamplerWrapper(final KafkaProducer kafkaProducer) {
this.kafkaProducer = kafkaProducer;
}

private KafkaProducer kafkaProducer;

@Override
public KafkaProducer getKafkaProducer() {
return kafkaProducer;
}
}

0 comments on commit e12d7a5

Please sign in to comment.