Skip to content

Commit

Permalink
extract scenarioIdFrom functionality
Browse files Browse the repository at this point in the history
refactor some code doubling related to scenarioIdFrom and featureFrom
  • Loading branch information
jacob-wieland-gematik committed Dec 5, 2024
1 parent 7ed77cc commit 11fb4bb
Show file tree
Hide file tree
Showing 4 changed files with 251 additions and 288 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ public class FeatureFileLoader {

private static final Logger LOGGER = LoggerFactory.getLogger(FeatureFileLoader.class);

private Optional<Feature> featureFrom(URI featureFileUri) {
public Optional<Feature> featureFrom(URI featureFileUri) {

String defaultFeatureId = new File(featureFileUri).getName().replace(".feature", "");
String defaultFeatureName = Inflector.getInstance().humanize(defaultFeatureId);
Expand Down Expand Up @@ -47,12 +47,12 @@ private void parseGherkinIn(URI featureFileUri) {

public Feature featureWithDefaultName(Feature feature, String defaultName) {
return new Feature(feature.getLocation(),
feature.getTags(),
feature.getLanguage(),
feature.getKeyword(),
defaultName,
feature.getDescription(),
feature.getChildren());
feature.getTags(),
feature.getLanguage(),
feature.getKeyword(),
defaultName,
feature.getDescription(),
feature.getChildren());
}

public void addTestSourceReadEvent(TestSourceRead event) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,9 @@ public class ScenarioContextParallel {
// key - scenarioId
private final Map<String, List<Tag>> scenarioTags = Collections.synchronizedMap(new HashMap<>());

public URI getScenarioContextURI() {
return scenarioContextURI;
}

public ScenarioContextParallel(URI scenarioContextURI) {
this.baseStepListeners = Collections.synchronizedList(new ArrayList<>());
Expand Down Expand Up @@ -180,7 +183,7 @@ public synchronized void setCurrentScenarioDefinitionFrom(String scenarioId, Tes

public synchronized boolean isAScenarioOutline(String scenarioId) {
return currentScenarioDefinitionMap.get(scenarioId) != null &&
currentScenarioDefinitionMap.get(scenarioId).getExamples().size() > 0;
currentScenarioDefinitionMap.get(scenarioId).getExamples().size() > 0;
}

public synchronized void startNewExample(String scenarioId) {
Expand Down Expand Up @@ -262,7 +265,7 @@ public synchronized void addTableRows(String scenarioId, List<String> headers,

AtomicInteger rowNumber = new AtomicInteger();
rows.forEach(
row -> table.appendRow(newRow(headers, lineNumbersOfEachRow, rowNumber.getAndIncrement(), row))
row -> table.appendRow(newRow(headers, lineNumbersOfEachRow, rowNumber.getAndIncrement(), row))
);
table.updateLineNumbers(lineNumbersOfEachRow);
exampleCountMap.put(scenarioId, new AtomicInteger(table.getSize()));
Expand All @@ -274,8 +277,8 @@ private DataTableRow newRow(List<String> headers,
int rowNumber,
Map<String, String> row) {
return new DataTableRow(
rowValuesFrom(headers, row),
lineNumbersOfEachRow.getOrDefault(rowNumber, 0L));
rowValuesFrom(headers, row),
lineNumbersOfEachRow.getOrDefault(rowNumber, 0L));
}

private List<String> rowValuesFrom(List<String> headers, Map<String, String> row) {
Expand Down Expand Up @@ -369,7 +372,7 @@ public synchronized void playAllTestEvents() {
LOGGER.error("An unrecoverable error occurred during test execution: " + exception.getMessage(), exception);
exception.printStackTrace();
recordUnexpectedFailure(new SerenityManagedException("An unrecoverable error occurred during test execution: " + exception.getMessage(),
exception));
exception));
}
}
clearEventBus();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -158,15 +158,15 @@ protected void handleTestSourceRead(TestSourceRead event) {
URI featurePath = event.getUri();

featureFrom(featurePath).ifPresent(
feature -> {
getContext().setFeatureTags(feature.getTags());

resetEventBusFor(featurePath);
initialiseListenersFor(featurePath);
configureDriver(feature, featurePath);
Story userStory = userStoryFrom(feature, relativeUriFrom(event.getUri()));
getStepEventBus(event.getUri()).testSuiteStarted(userStory);
}
feature -> {
getContext().setFeatureTags(feature.getTags());

resetEventBusFor(featurePath);
initialiseListenersFor(featurePath);
configureDriver(feature, featurePath);
Story userStory = userStoryFrom(feature, relativeUriFrom(event.getUri()));
getStepEventBus(event.getUri()).testSuiteStarted(userStory);
}
);
}

Expand Down Expand Up @@ -196,28 +196,8 @@ protected Optional<Feature> featureFrom(URI featureFileUri) {
if (!featureFileUri.toString().contains(FEATURES_ROOT_PATH) && !featureFileUri.toString().contains(FEATURES_CLASSPATH_ROOT_PATH)) {
LOGGER.warn("Feature from " + featureFileUri + " is not under the 'features' directory. Requirements report will not be correctly generated!");
}
String defaultFeatureId = PathUtils.getAsFile(featureFileUri).getName().replace(".feature", "");
String defaultFeatureName = Inflector.getInstance().humanize(defaultFeatureId);

parseGherkinIn(featureFileUri);

if (isEmpty(featureLoader.getFeatureName(featureFileUri))) {
return Optional.empty();
}

Feature feature = featureLoader.getFeature(featureFileUri);
if (feature.getName().isEmpty()) {
feature = featureLoader.featureWithDefaultName(feature, defaultFeatureName);
}
return Optional.of(feature);
}

private void parseGherkinIn(URI featureFileUri) {
try {
featureLoader.getFeature(featureFileUri);
} catch (Throwable ignoreParsingErrors) {
LOGGER.warn("Could not parse the Gherkin in feature file " + featureFileUri + ": file ignored");
}
return featureLoader.featureFrom(featureFileUri);
}

private Story userStoryFrom(Feature feature, String featureFileUri) {
Expand Down Expand Up @@ -263,9 +243,9 @@ protected void handleTestCaseStarted(TestCaseStarted event) {
if (getContext().isAScenarioOutline()) {
getContext().startNewExample();
handleExamples(currentFeature.get(),
getContext().currentScenarioOutline().getTags(),
getContext().currentScenarioOutline().getName(),
getContext().currentScenarioOutline().getExamples());
getContext().currentScenarioOutline().getTags(),
getContext().currentScenarioOutline().getName(),
getContext().currentScenarioOutline().getExamples());
}
startOfScenarioLifeCycle(currentFeature.get(), scenarioName, getContext().currentScenarioDefinition, event.getTestCase().getLocation().getLine());
getContext().currentScenario = scenarioIdFrom(currentFeature.get().getName(), TestSourcesModel.convertToId(getContext().currentScenarioDefinition.getName()));
Expand Down Expand Up @@ -296,9 +276,9 @@ private io.cucumber.messages.types.Rule getRuleForTestCase(TestSourcesModel.AstN

private boolean scenarioIsIncludedInARule(Scenario existingScenario, FeatureChild featureChild) {
return featureChild.getRule() != null && featureChild.getRule().isPresent()
&& featureChild.getRule().get().getChildren().stream().
filter(rc -> rc.getScenario().isPresent()).
map(rc -> rc.getScenario().get()).collect(Collectors.toList()).contains(existingScenario);
&& featureChild.getRule().get().getChildren().stream().
filter(rc -> rc.getScenario().isPresent()).
map(rc -> rc.getScenario().get()).collect(Collectors.toList()).contains(existingScenario);
}

private Feature getFeatureForTestCase(TestSourcesModel.AstNode astNode) {
Expand Down Expand Up @@ -332,11 +312,11 @@ private TestOutcome latestOf(List<TestOutcome> testOutcomes) {

protected void handleTestStepStarted(TestStepStarted event) {
StepDefinitionAnnotations.setScreenshotPreferencesTo(
StepDefinitionAnnotationReader
.withScreenshotLevel((TakeScreenshots) systemConfiguration.getScreenshotLevel()
.orElse(TakeScreenshots.UNDEFINED))
.forStepDefinition(event.getTestStep().getCodeLocation())
.getScreenshotPreferences());
StepDefinitionAnnotationReader
.withScreenshotLevel((TakeScreenshots) systemConfiguration.getScreenshotLevel()
.orElse(TakeScreenshots.UNDEFINED))
.forStepDefinition(event.getTestStep().getCodeLocation())
.getScreenshotPreferences());

if (!(event.getTestStep() instanceof HookTestStep)) {
if (event.getTestStep() instanceof PickleStepTestStep) {
Expand Down Expand Up @@ -430,12 +410,12 @@ private void handleExamples(Feature currentFeature, List<Tag> scenarioOutlineTag
initializeExamples();
for (Examples examples : examplesList) {
if (examplesAreNotExcludedByTags(examples, scenarioOutlineTags, currentFeatureTags)
&& lineFilters.examplesAreNotExcluded(examples, getContext().currentFeaturePath())) {
&& lineFilters.examplesAreNotExcluded(examples, getContext().currentFeaturePath())) {
List<TableRow> examplesTableRows = examples
.getTableBody()
.stream()
.filter(tableRow -> lineFilters.tableRowIsNotExcludedBy(tableRow, getContext().currentFeaturePath()))
.collect(Collectors.toList());
.getTableBody()
.stream()
.filter(tableRow -> lineFilters.tableRowIsNotExcludedBy(tableRow, getContext().currentFeaturePath()))
.collect(Collectors.toList());
List<String> headers = getHeadersFrom(examples.getTableHeader().get());
List<Map<String, String>> rows = getValuesFrom(examplesTableRows, headers);

Expand All @@ -456,18 +436,18 @@ private void handleExamples(Feature currentFeature, List<Tag> scenarioOutlineTag
String exampleTableDescription = trim(examples.getDescription());
if (newScenario) {
getContext().setTable(
dataTableFrom(SCENARIO_OUTLINE_NOT_KNOWN_YET,
headers,
rows,
exampleTableName,
exampleTableDescription,
lineNumbersOfEachRow));
} else {
getContext().addTableRows(headers,
dataTableFrom(SCENARIO_OUTLINE_NOT_KNOWN_YET,
headers,
rows,
exampleTableName,
exampleTableDescription,
lineNumbersOfEachRow);
lineNumbersOfEachRow));
} else {
getContext().addTableRows(headers,
rows,
exampleTableName,
exampleTableDescription,
lineNumbersOfEachRow);
}
getContext().addTableTags(tagsIn(examples));

Expand Down Expand Up @@ -582,11 +562,11 @@ private DataTable dataTableFrom(String scenarioOutline,
String description,
Map<Integer, Long> lineNumbersOfEachRow) {
return DataTable.withHeaders(headers)
.andScenarioOutline(scenarioOutline)
.andMappedRows(rows, lineNumbersOfEachRow)
.andTitle(name)
.andDescription(description)
.build();
.andScenarioOutline(scenarioOutline)
.andMappedRows(rows, lineNumbersOfEachRow)
.andTitle(name)
.andDescription(description)
.build();
}

private DataTable addTableRowsTo(DataTable table, List<String> headers,
Expand All @@ -602,8 +582,8 @@ private DataTable addTableRowsTo(DataTable table, List<String> headers,

private List<String> rowValuesFrom(List<String> headers, Map<String, String> row) {
return headers.stream()
.map(header -> row.get(header))
.collect(toList());
.map(header -> row.get(header))
.collect(toList());
}

private void startOfScenarioLifeCycle(Feature feature, String scenarioName, Scenario scenario, Integer currentLine) {
Expand All @@ -628,9 +608,9 @@ private void startScenario(Feature currentFeature, Scenario scenarioDefinition,
getContext().stepEventBus().setTestSource(TestSourceType.TEST_SOURCE_CUCUMBER.getValue());

getContext().stepEventBus()
.testStarted(scenarioName,
scenarioIdFrom(TestSourcesModel.convertToId(currentFeature.getName()),
TestSourcesModel.convertToId(scenarioName)));
.testStarted(scenarioName,
scenarioIdFrom(TestSourcesModel.convertToId(currentFeature.getName()),
TestSourcesModel.convertToId(scenarioName)));

getContext().stepEventBus().addDescriptionToCurrentTest(scenarioDefinition.getDescription());
getContext().stepEventBus().addTagsToCurrentTest(convertCucumberTags(currentFeature.getTags()));
Expand All @@ -651,15 +631,15 @@ private void startScenario(Feature currentFeature, Scenario scenarioDefinition,

private List<TestTag> tagsInEnclosingRule(Feature feature, Scenario scenario) {
List<io.cucumber.messages.types.Rule> nestedRules = feature.getChildren().stream()
.filter(fc -> fc.getRule().isPresent())
.map(fc -> fc.getRule().get())
.filter(Objects::nonNull)
.collect(toList());
.filter(fc -> fc.getRule().isPresent())
.map(fc -> fc.getRule().get())
.filter(Objects::nonNull)
.collect(toList());

return nestedRules.stream()
.filter(rule -> containsScenario(rule, scenario))
.flatMap(rule -> convertCucumberTags(rule.getTags()).stream())
.collect(toList());
.filter(rule -> containsScenario(rule, scenario))
.flatMap(rule -> convertCucumberTags(rule.getTags()).stream())
.collect(toList());
}

private boolean containsScenario(io.cucumber.messages.types.Rule rule, Scenario scenario) {
Expand Down Expand Up @@ -710,17 +690,17 @@ private List<TestTag> convertCucumberTags(List<Tag> cucumberTags) {
cucumberTags = completeManualTagsIn(cucumberTags);

return cucumberTags.stream()
.map(tag -> TestTag.withValue(tag.getName().substring(1)))
.collect(toList());
.map(tag -> TestTag.withValue(tag.getName().substring(1)))
.collect(toList());
}

private List<Tag> completeManualTagsIn(List<Tag> cucumberTags) {
if (unqualifiedManualTag(cucumberTags).isPresent() && doesNotContainResultTag(cucumberTags)) {
List<Tag> updatedTags = Lists.newArrayList(cucumberTags);

Tag newManualTag = new Tag(unqualifiedManualTag(cucumberTags).get().getLocation(),
"@manual:pending",
UUID.randomUUID().toString());
"@manual:pending",
UUID.randomUUID().toString());
updatedTags.add(newManualTag);
return updatedTags;
} else {
Expand Down Expand Up @@ -870,10 +850,10 @@ private void updateManualResultsFrom(List<Tag> scenarioTags) {
getContext().stepEventBus().testIsManual();

manualResultDefinedIn(scenarioTags).ifPresent(
testResult ->
UpdateManualScenario.forScenario(getContext().currentScenarioDefinition.getDescription())
.inContext(getContext().stepEventBus().getBaseStepListener(), systemConfiguration.getEnvironmentVariables())
.updateManualScenario(testResult, scenarioTags)
testResult ->
UpdateManualScenario.forScenario(getContext().currentScenarioDefinition.getDescription())
.inContext(getContext().stepEventBus().getBaseStepListener(), systemConfiguration.getEnvironmentVariables())
.updateManualScenario(testResult, scenarioTags)
);
}

Expand Down Expand Up @@ -915,7 +895,7 @@ private void skipped(String stepTitle, Throwable cause) {

private String currentStepTitle() {
return getContext().stepEventBus().getCurrentStep().isPresent()
? getContext().stepEventBus().getCurrentStep().get().getDescription() : "";
? getContext().stepEventBus().getCurrentStep().get().getDescription() : "";
}

private boolean errorOrFailureRecordedForStep(String stepTitle, Throwable cause) {
Expand All @@ -941,7 +921,7 @@ private Optional<TestOutcome> latestTestOutcome() {

List<TestOutcome> recordedOutcomes = getContext().stepEventBus().getBaseStepListener().getTestOutcomes();
return (recordedOutcomes.isEmpty()) ? Optional.empty()
: Optional.of(recordedOutcomes.get(recordedOutcomes.size() - 1));
: Optional.of(recordedOutcomes.get(recordedOutcomes.size() - 1));
}

private boolean isAssumptionFailure(Throwable rootCause) {
Expand All @@ -956,8 +936,8 @@ private boolean isAssumptionFailure(Throwable rootCause) {
private String stepTitleFrom(io.cucumber.messages.types.Step currentStep, TestStep testStep) {
if (currentStep != null && testStep instanceof PickleStepTestStep)
return currentStep.getKeyword()
+ ((PickleStepTestStep) testStep).getStep().getText()
+ embeddedTableDataIn((PickleStepTestStep) testStep);
+ ((PickleStepTestStep) testStep).getStep().getText()
+ embeddedTableDataIn((PickleStepTestStep) testStep);
return "";
}

Expand Down Expand Up @@ -1001,7 +981,7 @@ private void generateReports() {

public List<TestOutcome> getAllTestOutcomes() {
return baseStepListeners.stream().map(BaseStepListener::getTestOutcomes).flatMap(List::stream)
.collect(Collectors.toList());
.collect(Collectors.toList());
}

private String normalized(String value) {
Expand Down
Loading

0 comments on commit 11fb4bb

Please sign in to comment.