io.cucumber.core.plugin.SerenityReporter Maven / Gradle / Ivy
The newest version!
package io.cucumber.core.plugin;
import com.google.common.collect.Lists;
import io.cucumber.messages.types.*;
import io.cucumber.plugin.ConcurrentEventListener;
import io.cucumber.plugin.Plugin;
import io.cucumber.plugin.event.TestCaseFinished;
import io.cucumber.plugin.event.TestCaseStarted;
import io.cucumber.plugin.event.TestRunFinished;
import io.cucumber.plugin.event.TestRunStarted;
import io.cucumber.plugin.event.TestStep;
import io.cucumber.plugin.event.TestStepFinished;
import io.cucumber.plugin.event.TestStepStarted;
import io.cucumber.plugin.event.*;
import io.cucumber.tagexpressions.Expression;
import net.serenitybdd.core.Serenity;
import net.serenitybdd.core.SerenityListeners;
import net.serenitybdd.core.SerenityReports;
import net.serenitybdd.core.di.SerenityInfrastructure;
import net.serenitybdd.core.webdriver.configuration.RestartBrowserForEach;
import net.serenitybdd.cucumber.CucumberWithSerenity;
import net.serenitybdd.cucumber.formatting.ScenarioOutlineDescription;
import net.serenitybdd.cucumber.util.PathUtils;
import net.serenitybdd.cucumber.util.StepDefinitionAnnotationReader;
import net.thucydides.core.model.screenshots.StepDefinitionAnnotations;
import net.thucydides.model.domain.DataTable;
import net.thucydides.model.domain.Rule;
import net.thucydides.model.domain.*;
import net.thucydides.model.domain.stacktrace.RootCauseAnalyzer;
import net.thucydides.model.reports.ReportService;
import net.thucydides.model.requirements.FeatureFilePath;
import net.thucydides.core.steps.*;
import net.thucydides.model.steps.ExecutedStepDescription;
import net.thucydides.model.steps.StepFailure;
import net.thucydides.model.steps.TestSourceType;
import net.thucydides.model.util.Inflector;
import net.thucydides.model.webdriver.Configuration;
import net.thucydides.core.webdriver.ThucydidesWebDriverSupport;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.URI;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.stream.Collectors;
import static io.cucumber.core.plugin.TaggedScenario.*;
import static java.util.stream.Collectors.toList;
import static net.serenitybdd.core.webdriver.configuration.RestartBrowserForEach.FEATURE;
import static org.apache.commons.lang3.StringUtils.isEmpty;
import static org.apache.commons.lang3.StringUtils.isNotEmpty;
/**
* Cucumber Formatter for Serenity.
* @deprecated - use the SerenityParallelReporter now
*
* @author L.Carausu ([email protected])
*/
@Deprecated(since="4.0.50")
public class SerenityReporter implements Plugin, ConcurrentEventListener {
private static final String OPEN_PARAM_CHAR = "\uff5f";
private static final String CLOSE_PARAM_CHAR = "\uff60";
private static final String SCENARIO_OUTLINE_NOT_KNOWN_YET = "";
private final Configuration systemConfiguration;
private final List baseStepListeners;
private final static String FEATURES_ROOT_PATH = "/features/";
private final static String FEATURES_CLASSPATH_ROOT_PATH = ":features/";
private final FeatureFileLoader featureLoader = new FeatureFileLoader();
private LineFilters lineFilters;
private List scenarioTags;
private static final Logger LOGGER = LoggerFactory.getLogger(SerenityReporter.class);
private final ManualScenarioChecker manualScenarioDateChecker;
private final ThreadLocal localContext = ThreadLocal.withInitial(ScenarioContext::new);
private final Set contextURISet = new CopyOnWriteArraySet<>();
protected ScenarioContext getContext() {
return localContext.get();
}
/**
* Constructor automatically called by cucumber when class is specified as plugin
* in @CucumberOptions.
*/
public SerenityReporter() {
this.systemConfiguration = SerenityInfrastructure.getConfiguration();
this.manualScenarioDateChecker = new ManualScenarioChecker(systemConfiguration.getEnvironmentVariables());
baseStepListeners = Collections.synchronizedList(new ArrayList<>());
}
public SerenityReporter(Configuration systemConfiguration) {
this.systemConfiguration = systemConfiguration;
this.manualScenarioDateChecker = new ManualScenarioChecker(systemConfiguration.getEnvironmentVariables());
baseStepListeners = Collections.synchronizedList(new ArrayList<>());
}
private final FeaturePathFormatter featurePathFormatter = new FeaturePathFormatter();
private StepEventBus getStepEventBus(URI featurePath) {
URI prefixedPath = featurePathFormatter.featurePathWithPrefixIfNecessary(featurePath);
return StepEventBus.eventBusFor(prefixedPath);
}
private void setStepEventBus(URI featurePath) {
URI prefixedPath = featurePathFormatter.featurePathWithPrefixIfNecessary(featurePath);
StepEventBus.setCurrentBusToEventBusFor(prefixedPath);
}
private void initialiseListenersFor(URI featurePath) {
if (getStepEventBus(featurePath).isBaseStepListenerRegistered()) {
return;
}
SerenityListeners listeners = new SerenityListeners(getStepEventBus(featurePath), systemConfiguration);
baseStepListeners.add(listeners.getBaseStepListener());
}
private final EventHandler testSourceReadHandler = this::handleTestSourceRead;
private final EventHandler caseStartedHandler = this::handleTestCaseStarted;
private final EventHandler caseFinishedHandler = this::handleTestCaseFinished;
private final EventHandler stepStartedHandler = this::handleTestStepStarted;
private final EventHandler stepFinishedHandler = this::handleTestStepFinished;
private final EventHandler runStartedHandler = this::handleTestRunStarted;
private final EventHandler runFinishedHandler = this::handleTestRunFinished;
private final EventHandler writeEventHandler = this::handleWrite;
protected void handleTestRunStarted(TestRunStarted event) {
}
@Override
public void setEventPublisher(EventPublisher publisher) {
publisher.registerHandlerFor(TestRunStarted.class, runStartedHandler);
publisher.registerHandlerFor(TestSourceRead.class, testSourceReadHandler);
publisher.registerHandlerFor(TestCaseStarted.class, caseStartedHandler);
publisher.registerHandlerFor(TestStepStarted.class, stepStartedHandler);
publisher.registerHandlerFor(TestStepFinished.class, stepFinishedHandler);
publisher.registerHandlerFor(TestCaseFinished.class, caseFinishedHandler);
publisher.registerHandlerFor(TestRunFinished.class, runFinishedHandler);
publisher.registerHandlerFor(WriteEvent.class, writeEventHandler);
}
protected void handleTestSourceRead(TestSourceRead event) {
featureLoader.addTestSourceReadEvent(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);
}
);
}
private void resetEventBusFor(URI featurePath) {
StepEventBus.clearEventBusFor(featurePath);
}
private String relativeUriFrom(URI fullPathUri) {
boolean useDecodedURI = systemConfiguration.getEnvironmentVariables().getPropertyAsBoolean("use.decoded.url", false);
String pathURIAsString;
if (useDecodedURI) {
pathURIAsString = URLDecoder.decode(fullPathUri.toString(), StandardCharsets.UTF_8);
} else {
pathURIAsString = fullPathUri.toString();
}
if (pathURIAsString.contains(FEATURES_ROOT_PATH)) {
return StringUtils.substringAfterLast(pathURIAsString, FEATURES_ROOT_PATH);
} else {
return pathURIAsString;
}
}
protected Optional featureFrom(URI featureFileUri) {
LOGGER.debug("Running feature from " + featureFileUri.toString());
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");
}
}
private Story userStoryFrom(Feature feature, String featureFileUri) {
String relativePath = new FeatureFilePath(systemConfiguration.getEnvironmentVariables()).relativePathFor(featureFileUri);
// obtain an id by removing the ".feature" extension and replacing illegal characters with underscores
String id = relativePath.replace(".feature", "");
Story userStory = Story.withIdAndPath(id, feature.getName(), relativePath).asFeature();
if (!isEmpty(feature.getDescription())) {
userStory = userStory.withNarrative(feature.getDescription());
}
return userStory;
}
protected void handleTestCaseStarted(TestCaseStarted event) {
URI featurePath = event.getTestCase().getUri();
getContext().currentFeaturePathIs(featurePath);
contextURISet.add(featurePath);
setStepEventBus(featurePath);
if (FeatureTracker.isNewFeature(event)) {
// Shut down any drivers remaining open from a previous feature, if @singlebrowser is used.
// Cucumber has no event to mark the start and end of a feature, so we need to do this here.
if (RestartBrowserForEach.configuredIn(systemConfiguration.getEnvironmentVariables()).restartBrowserForANew(FEATURE)) {
ThucydidesWebDriverSupport.closeCurrentDrivers();
}
FeatureTracker.startNewFeature(event);
}
String scenarioName = event.getTestCase().getName();
TestSourcesModel.AstNode astNode = featureLoader.getAstNode(getContext().currentFeaturePath(), event.getTestCase().getLocation().getLine());
Optional currentFeature = featureFrom(featurePath);
if ((astNode != null) && currentFeature.isPresent()) {
getContext().setCurrentScenarioDefinitionFrom(astNode);
//the sources are read in parallel, global current feature cannot be used
String scenarioId = scenarioIdFrom(currentFeature.get().getName(), TestSourcesModel.convertToId(getContext().currentScenarioDefinition.getName()));
boolean newScenario = !scenarioId.equals(getContext().getCurrentScenario());
if (newScenario) {
configureDriver(currentFeature.get(), getContext().currentFeaturePath());
if (getContext().isAScenarioOutline()) {
getContext().startNewExample();
handleExamples(currentFeature.get(),
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()));
} else {
if (getContext().isAScenarioOutline()) {
startExample(Long.valueOf(event.getTestCase().getLocation().getLine()), scenarioName);
}
}
TestSourcesModel.getBackgroundForTestCase(astNode).ifPresent(this::handleBackground);
}
io.cucumber.messages.types.Rule rule = getRuleForTestCase(astNode);
if (rule != null) {
getContext().stepEventBus().setRule(Rule.from(rule));
}
}
private io.cucumber.messages.types.Rule getRuleForTestCase(TestSourcesModel.AstNode astNode) {
Feature feature = getFeatureForTestCase(astNode);
Scenario existingScenario = TestSourcesModel.getScenarioDefinition(astNode);
List childrenList = feature.getChildren();
for (FeatureChild featureChild : childrenList) {
if (scenarioIsIncludedInARule(existingScenario, featureChild)) {
return featureChild.getRule().get();
}
}
return null;
}
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);
}
private Feature getFeatureForTestCase(TestSourcesModel.AstNode astNode) {
while (astNode.parent != null) {
astNode = astNode.parent;
}
return (Feature) astNode.node;
}
protected void handleTestCaseFinished(TestCaseFinished event) {
if (getContext().examplesAreRunning()) {
handleResult(event.getResult());
finishExample();
}
if (Status.FAILED.equals(event.getResult().getStatus()) && noAnnotatedResultIdDefinedFor(event)) {
getStepEventBus(event.getTestCase().getUri()).testFailed(event.getResult().getError());
} else {
getStepEventBus(event.getTestCase().getUri()).testFinished(getContext().examplesAreRunning());
}
getContext().clearStepQueue();
}
private boolean noAnnotatedResultIdDefinedFor(TestCaseFinished event) {
BaseStepListener baseStepListener = getStepEventBus(event.getTestCase().getUri()).getBaseStepListener();
return (baseStepListener.getTestOutcomes().isEmpty() || (latestOf(baseStepListener.getTestOutcomes()).getAnnotatedResult() == null));
}
private TestOutcome latestOf(List testOutcomes) {
return testOutcomes.get(testOutcomes.size() - 1);
}
protected void handleTestStepStarted(TestStepStarted event) {
StepDefinitionAnnotations.setScreenshotPreferencesTo(
StepDefinitionAnnotationReader
.withScreenshotLevel((TakeScreenshots) systemConfiguration.getScreenshotLevel()
.orElse(TakeScreenshots.UNDEFINED))
.forStepDefinition(event.getTestStep().getCodeLocation())
.getScreenshotPreferences());
if (!(event.getTestStep() instanceof HookTestStep)) {
if (event.getTestStep() instanceof PickleStepTestStep) {
PickleStepTestStep pickleTestStep = (PickleStepTestStep) event.getTestStep();
TestSourcesModel.AstNode astNode = featureLoader.getAstNode(getContext().currentFeaturePath(), pickleTestStep.getStepLine());
if (astNode != null) {
//io.cucumber.core.internal.gherkin.ast.Step step = (io.cucumber.core.internal.gherkin.ast.Step) astNode.node;
io.cucumber.messages.types.Step step = (io.cucumber.messages.types.Step) astNode.node;
if (!getContext().isAddingScenarioOutlineSteps()) {
getContext().queueStep(step);
getContext().queueTestStep(event.getTestStep());
}
if (getContext().isAScenarioOutline()) {
int lineNumber = event.getTestCase().getLocation().getLine();
getContext().stepEventBus().updateExampleLineNumber(lineNumber);
}
io.cucumber.messages.types.Step currentStep = getContext().getCurrentStep();
String stepTitle = stepTitleFrom(currentStep, pickleTestStep);
getContext().stepEventBus().stepStarted(ExecutedStepDescription.withTitle(stepTitle));
getContext().stepEventBus().updateCurrentStepTitle(normalized(stepTitle));
}
}
}
}
protected void handleWrite(WriteEvent event) {
getContext().stepEventBus().stepStarted(ExecutedStepDescription.withTitle(event.getText()));
getContext().stepEventBus().stepFinished();
}
protected void handleTestStepFinished(TestStepFinished event) {
if (!(event.getTestStep() instanceof HookTestStep)) {
handleResult(event.getResult());
StepDefinitionAnnotations.clear();
}
}
protected void handleTestRunFinished(TestRunFinished event) {
generateReports();
assureTestSuiteFinished();
}
private ReportService getReportService() {
return SerenityReports.getReportService(systemConfiguration);
}
private void configureDriver(Feature feature, URI featurePath) {
getStepEventBus(featurePath).setUniqueSession(systemConfiguration.shouldUseAUniqueBrowser());
List tags = getTagNamesFrom(feature.getTags());
String requestedDriver = getDriverFrom(tags);
String requestedDriverOptions = getDriverOptionsFrom(tags);
if (isNotEmpty(requestedDriver)) {
ThucydidesWebDriverSupport.useDefaultDriver(requestedDriver);
ThucydidesWebDriverSupport.useDriverOptions(requestedDriverOptions);
}
}
private List getTagNamesFrom(List tags) {
List tagNames = new ArrayList<>();
for (Tag tag : tags) {
tagNames.add(tag.getName());
}
return tagNames;
}
private String getDriverFrom(List tags) {
String requestedDriver = null;
for (String tag : tags) {
if (tag.startsWith("@driver:")) {
requestedDriver = tag.substring(8);
}
}
return requestedDriver;
}
private String getDriverOptionsFrom(List tags) {
String requestedDriver = null;
for (String tag : tags) {
if (tag.startsWith("@driver-options:")) {
requestedDriver = tag.substring(16);
}
}
return requestedDriver;
}
private void handleExamples(Feature currentFeature, List scenarioOutlineTags, String id, List examplesList) {
lineFilters = LineFilters.forCurrentContext();
String featureName = currentFeature.getName();
List currentFeatureTags = currentFeature.getTags();
getContext().doneAddingScenarioOutlineSteps();
initializeExamples();
for (Examples examples : examplesList) {
if (examplesAreNotExcludedByTags(examples, scenarioOutlineTags, currentFeatureTags)
&& lineFilters.examplesAreNotExcluded(examples, getContext().currentFeaturePath())) {
List examplesTableRows = examples
.getTableBody()
.stream()
.filter(tableRow -> lineFilters.tableRowIsNotExcludedBy(tableRow, getContext().currentFeaturePath()))
.collect(Collectors.toList());
List headers = getHeadersFrom(examples.getTableHeader().get());
List
© 2015 - 2025 Weber Informatics LLC | Privacy Policy