How to use scenarios method of net.serenitybdd.cucumber.suiteslicing.CucumberSuiteSlicer class

Best Serenity Cucumber code snippet using net.serenitybdd.cucumber.suiteslicing.CucumberSuiteSlicer.scenarios

Source:CucumberSerenityRunner.java Github

copy

Full Screen

...241            } else {242                LOGGER.info("Running slice {} of {} using fork {} of {} from feature paths {}", batchNumber, batchCount, forkNumber, forkCount, featurePaths);243                List<String> tagFiltersAsString =  tagFilters.stream().map(Expression::toString).collect(toList());244                WeightedCucumberScenarios weightedCucumberScenarios = new CucumberSuiteSlicer(featurePaths, TestStatistics.from(environmentVariables, featurePaths))245                        .scenarios(batchNumber, batchCount, forkNumber, forkCount, tagFiltersAsString);246                List<ParentRunner<?>> unfilteredChildren = children;247                AtomicInteger filteredInScenarioCount = new AtomicInteger();248                List<ParentRunner<?>> filteredChildren = unfilteredChildren.stream()249                        .filter(forIncludedFeatures(weightedCucumberScenarios))250                        .map(toPossibleFeatureRunner(weightedCucumberScenarios, filteredInScenarioCount))251                        .filter(Optional::isPresent)252                        .map(Optional::get)253                        .collect(toList());254                if (filteredInScenarioCount.get() != weightedCucumberScenarios.totalScenarioCount()) {255                    LOGGER.warn(256                            "There is a mismatch between the number of scenarios included in this test run ({}) and the expected number of scenarios loaded ({}). This suggests that the scenario filtering is not working correctly or feature file(s) of an unexpected structure are being run",257                            filteredInScenarioCount.get(),258                            weightedCucumberScenarios.scenarios.size());259                }260                LOGGER.info("Running {} of {} features", filteredChildren.size(), unfilteredChildren.size());261                return filteredChildren;262            }263        } catch (Exception e) {264            LOGGER.error("Test failed to start", e);265            throw e;266        }267    }268    private Function<ParentRunner<?>, Optional<ParentRunner<?>>> toPossibleFeatureRunner(WeightedCucumberScenarios weightedCucumberScenarios, AtomicInteger filteredInScenarioCount) {269        return featureRunner -> {270            int initialScenarioCount = featureRunner.getDescription().getChildren().size();271            String featureName = FeatureRunnerExtractors.extractFeatureName(featureRunner);272            try {273                ScenarioFilter filter = weightedCucumberScenarios.createFilterContainingScenariosIn(featureName);274                String featurePath = FeatureRunnerExtractors.featurePathFor(featureRunner);275                featureRunner.filter(filter);276                if (!filter.scenariosIncluded().isEmpty()) {277                    LOGGER.info("{} scenario(s) included for '{}' in {}", filter.scenariosIncluded().size(), featureName, featurePath);278                    filter.scenariosIncluded().forEach(scenario -> {279                        LOGGER.info("Included scenario '{}'", scenario);280                        filteredInScenarioCount.getAndIncrement();281                    });282                }283                if (!filter.scenariosExcluded().isEmpty()) {284                    LOGGER.debug("{} scenario(s) excluded for '{}' in {}", filter.scenariosExcluded().size(), featureName, featurePath);285                    filter.scenariosExcluded().forEach(scenario -> LOGGER.debug("Excluded scenario '{}'", scenario));286                }287                return Optional.of(featureRunner);288            } catch (NoTestsRemainException e) {289                LOGGER.info("Filtered out all {} scenarios for feature '{}'", initialScenarioCount, featureName);290                return Optional.empty();291            }292        };293    }294    private Predicate<ParentRunner<?>> forIncludedFeatures(WeightedCucumberScenarios weightedCucumberScenarios) {295        return featureRunner -> {296            String featureName = FeatureRunnerExtractors.extractFeatureName(featureRunner);297            String featurePath =  PathUtils.getAsFile(FeatureRunnerExtractors.featurePathFor(featureRunner)).getName();298            boolean matches = weightedCucumberScenarios.scenarios.stream().anyMatch(scenario -> featurePath.equals(scenario.featurePath));299            LOGGER.debug("{} in filtering '{}' in {}", matches ? "Including" : "Not including", featureName, featurePath);300            return matches;301        };302    }303}...

Full Screen

Full Screen

Source:CucumberWithSerenity.java Github

copy

Full Screen

...87                return super.getChildren();88            } else {89                LOGGER.info("Running slice {} of {} using fork {} of {} from feature paths {}", batchNumber, batchCount, forkNumber, forkCount, featurePaths);90                WeightedCucumberScenarios weightedCucumberScenarios = new CucumberSuiteSlicer(featurePaths, TestStatistics.from(environmentVariables, featurePaths))91                        .scenarios(batchNumber, batchCount, forkNumber, forkCount, tagFilters);92                List<FeatureRunner> unfilteredChildren = super.getChildren();93                AtomicInteger filteredInScenarioCount = new AtomicInteger();94                List<FeatureRunner> filteredChildren = unfilteredChildren.stream()95                        .filter(forIncludedFeatures(weightedCucumberScenarios))96                        .map(toPossibleFeatureRunner(weightedCucumberScenarios, filteredInScenarioCount))97                        .filter(Optional::isPresent)98                        .map(Optional::get)99                        .collect(toList());100                if (filteredInScenarioCount.get() != weightedCucumberScenarios.totalScenarioCount()) {101                    LOGGER.warn(102                            "There is a mismatch between the number of scenarios included in this test run ({}) and the expected number of scenarios loaded ({}). This suggests that the scenario filtering is not working correctly or feature file(s) of an unexpected structure are being run",103                            filteredInScenarioCount.get(),104                            weightedCucumberScenarios.scenarios.size());105                }106                LOGGER.info("Running {} of {} features", filteredChildren.size(), unfilteredChildren.size());107                return filteredChildren;108            }109        } catch (Exception e) {110            LOGGER.error("Test failed to start", e);111            throw e;112        }113    }114    private Function<FeatureRunner, Optional<FeatureRunner>> toPossibleFeatureRunner(WeightedCucumberScenarios weightedCucumberScenarios, AtomicInteger filteredInScenarioCount) {115        return featureRunner -> {116            int initialScenarioCount = featureRunner.getDescription().getChildren().size();117            String featureName = FeatureRunnerExtractors.extractFeatureName(featureRunner);118            try {119                ScenarioFilter filter = weightedCucumberScenarios.createFilterContainingScenariosIn(featureName);120                String featurePath = FeatureRunnerExtractors.featurePathFor(featureRunner);121                featureRunner.filter(filter);122                if (!filter.scenariosIncluded().isEmpty()) {123                    LOGGER.info("{} scenario(s) included for '{}' in {}", filter.scenariosIncluded().size(), featureName, featurePath);124                    filter.scenariosIncluded().forEach(scenario -> {125                        LOGGER.info("Included scenario '{}'", scenario);126                        filteredInScenarioCount.getAndIncrement();127                    });128                }129                if (!filter.scenariosExcluded().isEmpty()) {130                    LOGGER.debug("{} scenario(s) excluded for '{}' in {}", filter.scenariosExcluded().size(), featureName, featurePath);131                    filter.scenariosExcluded().forEach(scenario -> LOGGER.debug("Excluded scenario '{}'", scenario));132                }133                return Optional.of(featureRunner);134            } catch (NoTestsRemainException e) {135                LOGGER.info("Filtered out all {} scenarios for feature '{}'", initialScenarioCount, featureName);136                return Optional.empty();137            }138        };139    }140    private Predicate<FeatureRunner> forIncludedFeatures(WeightedCucumberScenarios weightedCucumberScenarios) {141        return featureRunner -> {142            String featureName = FeatureRunnerExtractors.extractFeatureName(featureRunner);143            String featurePath = Paths.get(FeatureRunnerExtractors.featurePathFor(featureRunner)).getFileName().toString();144            boolean matches = weightedCucumberScenarios.scenarios.stream().anyMatch(scenario -> featurePath.equals(scenario.featurePath));145            LOGGER.debug("{} in filtering '{}' in {}", matches ? "Including" : "Not including", featureName, featurePath);146            return matches;147        };148    }149}...

Full Screen

Full Screen

Source:ScenarioLineCountStatistics.java Github

copy

Full Screen

...40                    .filter(child -> asList(ScenarioOutline.class, Scenario.class).contains(child.getClass()))41                    .map(scenarioToResult(cucumberFeature))42                    .collect(toList());43            } catch (Exception e) {44                throw new IllegalStateException(String.format("Could not extract scenarios from %s", cucumberFeature.getUri()), e);45            }46        };47    }48    private Function<ScenarioDefinition, TestScenarioResult> scenarioToResult(CucumberFeature feature) {49        return scenarioDefinition -> {50            try {51                return new TestScenarioResult(52                    feature.getGherkinFeature().getFeature().getName(),53                    scenarioDefinition.getName(),54                    scenarioStepCountFor(backgroundStepCountFor(feature), scenarioDefinition));55            } catch (Exception e) {56                throw new IllegalStateException(String.format("Could not determine step count for scenario '%s'", scenarioDefinition.getDescription()), e);57            }58        };...

Full Screen

Full Screen

Source:CucumberScenarioLoader.java Github

copy

Full Screen

...20import static java.util.Arrays.asList;21import static java.util.stream.Collectors.toList;22import static java.util.stream.Collectors.toSet;23/**24 * Reads cucumber feature files and breaks them down into a collection of scenarios (WeightedCucumberScenarios).25 */26public class CucumberScenarioLoader {27    private static final Logger LOGGER = LoggerFactory.getLogger(CucumberScenarioLoader.class);28    private final List<URI> featurePaths;29    private final TestStatistics statistics;30    public CucumberScenarioLoader(List<URI> featurePaths, TestStatistics statistics) {31        this.featurePaths = featurePaths;32        this.statistics = statistics;33    }34    public WeightedCucumberScenarios load() {35        LOGGER.debug("Feature paths are {}", featurePaths);36        ResourceLoader resourceLoader = new MultiLoader(CucumberSuiteSlicer.class.getClassLoader());37        List<WeightedCucumberScenario> weightedCucumberScenarios = new FeatureLoader(resourceLoader).load(featurePaths).stream()38            .map(getScenarios())39            .flatMap(List::stream)40            .collect(toList());41        return new WeightedCucumberScenarios(weightedCucumberScenarios);42    }43    private Function<CucumberFeature, List<WeightedCucumberScenario>> getScenarios() {44        return cucumberFeature -> {45            try {46                return (cucumberFeature.getGherkinFeature().getFeature() == null) ? Collections.emptyList() : cucumberFeature.getGherkinFeature().getFeature().getChildren()47                    .stream()48                    .filter(child -> asList(ScenarioOutline.class, Scenario.class).contains(child.getClass()))49                    .map(scenarioDefinition -> new WeightedCucumberScenario(50                        PathUtils.getAsFile(cucumberFeature.getUri()).getName(),51                        cucumberFeature.getGherkinFeature().getFeature().getName(),52                        scenarioDefinition.getName(),53                        scenarioWeightFor(cucumberFeature, scenarioDefinition),54                        tagsFor(cucumberFeature, scenarioDefinition),55                        scenarioCountFor(scenarioDefinition)))56                    .collect(toList());57            } catch (Exception e) {58                throw new IllegalStateException(String.format("Could not extract scenarios from %s", cucumberFeature.getUri()), e);59            }60        };61    }62    private int scenarioCountFor(ScenarioDefinition scenarioDefinition) {63        if (scenarioDefinition instanceof ScenarioOutline) {64            return ((ScenarioOutline) scenarioDefinition).getExamples().stream().map(examples -> examples.getTableBody().size()).mapToInt(Integer::intValue).sum();65        } else {66            return 1;67        }68    }69    private Set<String> tagsFor(CucumberFeature feature, ScenarioDefinition scenarioDefinition) {70        return FluentIterable.concat(feature.getGherkinFeature().getFeature().getTags(), scenarioTags(scenarioDefinition)).stream().map(Tag::getName).collect(toSet());71    }72    private List<Tag> scenarioTags(ScenarioDefinition scenario) {...

Full Screen

Full Screen

Source:CucumberSuiteSlicerTest.java Github

copy

Full Screen

...25            .scenario("Buying more widgets");26    }27    @Test28    public void shouldReturnOnlyScenariosWithSpecifiedTags() {29        assertThat(cucumberSuiteSlicer.scenarios(1, 1, 1, 1, asList("@shouldPass")).scenarios, contains(expectedScenario1));30    }31    @Test32    public void noSuppliedTagsMeansReturnAllScenarios() {33        assertThat(cucumberSuiteSlicer.scenarios(1, 1, 1, 1, asList()).scenarios, contains(expectedScenario1, expectedScenario2));34    }35    @Test36    public void shouldSupportNotInTheTagExpression() {37        assertThat(cucumberSuiteSlicer.scenarios(1, 1, 1, 1, asList("not @shouldPass")).scenarios, contains(expectedScenario2));38    }39    @Test40    public void shouldSupportOldExclusionSyntaxInTheTagExpression() {41        assertThat(cucumberSuiteSlicer.scenarios(1, 1, 1, 1, asList("~@shouldPass")).scenarios, contains(expectedScenario2));42    }43}

Full Screen

Full Screen

Source:CucumberSuiteSlicer.java Github

copy

Full Screen

...10    public CucumberSuiteSlicer(List<URI> featurePaths, TestStatistics statistics) {11        this.featurePaths = featurePaths;12        this.statistics = statistics;13    }14    public WeightedCucumberScenarios scenarios(int batchNumber, int batchCount, int forkNumber, int forkCount, List<String> tagFilters) {15        return new CucumberScenarioLoader(featurePaths, statistics).load()16            .filter(forSuppliedTags(tagFilters))17            .slice(batchNumber).of(batchCount).slice(forkNumber).of(forkCount);18    }19    private Predicate<WeightedCucumberScenario> forSuppliedTags(List<String> tagFilters) {20        return cucumberScenario -> TagParser.parseFromTagFilters(tagFilters).evaluate(newArrayList(cucumberScenario.tags));21    }22}...

Full Screen

Full Screen

scenarios

Using AI Code Generation

copy

Full Screen

1import net.serenitybdd.cucumber.suiteslicing.CucumberSuiteSlicer;2import net.serenitybdd.cucumber.suiteslicing.CucumberScenario;3import java.util.List;4public class TestRunner extends CucumberSuiteSlicer {5    public List<CucumberScenario> scenarios() {6        return super.scenarios();7    }8}9import net.serenitybdd.cucumber.suiteslicing.CucumberSuiteSlicer;10import net.serenitybdd.cucumber.suiteslicing.CucumberScenario;11import java.util.List;12public class TestRunner extends CucumberSuiteSlicer {13    public List<CucumberScenario> scenarios() {14        return super.scenarios();15    }16}17import net.serenitybdd.cucumber.suiteslicing.CucumberSuiteSlicer;18import net.serenitybdd.cucumber.suiteslicing.CucumberScenario;19import java.util.List;20public class TestRunner extends CucumberSuiteSlicer {21    public List<CucumberScenario> scenarios() {22        return super.scenarios();23    }24}25import net.serenitybdd.cucumber.suiteslicing.CucumberSuiteSlicer;26import net.serenitybdd.cucumber.suiteslicing.CucumberScenario;27import java.util.List;28public class TestRunner extends CucumberSuiteSlicer {29    public List<CucumberScenario> scenarios() {30        return super.scenarios();31    }32}33import net.serenitybdd.cucumber.suiteslicing.CucumberSuiteSlicer;34import net.serenitybdd.cucumber.suiteslicing.CucumberScenario;35import java.util.List;36public class TestRunner extends CucumberSuiteSlicer {37    public List<CucumberScenario> scenarios() {38        return super.scenarios();39    }40}41import net.serenitybdd.cucumber

Full Screen

Full Screen

scenarios

Using AI Code Generation

copy

Full Screen

1import net.serenitybdd.cucumber.suiteslicing.CucumberSuiteSlicer2CucumberSuiteSlicer slicer = new CucumberSuiteSlicer()3def scenarios = slicer.scenarios('src/test/resources/features/')4scenarios.each {5    println it.getUri()6    println it.getLine()7    println it.getName()8}

Full Screen

Full Screen

scenarios

Using AI Code Generation

copy

Full Screen

1import net.serenitybdd.cucumber.suiteslicing.CucumberSuiteSlicer2import net.serenitybdd.cucumber.suiteslicing.CucumberScenario3import java.util.stream.Collectors4CucumberSuiteSlicer cucumberSuiteSlicer = new CucumberSuiteSlicer()5List<CucumberScenario> cucumberScenarios = cucumberSuiteSlicer.scenariosIn(features)6List<CucumberScenario> cucumberScenariosWithSmokeTag = cucumberScenarios.stream()7    .filter(cucumberScenario -> cucumberScenario.getTags().contains("@smoke"))8    .collect(Collectors.toList())9List<CucumberScenario> cucumberScenariosWithoutSmokeTag = cucumberScenarios.stream()10    .filter(cucumberScenario -> !cucumberScenario.getTags().contains("@smoke"))11    .collect(Collectors.toList())12List<CucumberScenario> cucumberScenariosWithSmokeAndRegressionTag = cucumberScenarios.stream()13    .filter(cucumberScenario -> cucumberScenario.getTags().contains("@smoke"))14    .filter(cucumberScenario -> cucumberScenario.getTags().contains("@regression"))15    .collect(Collectors.toList())16List<CucumberScenario> cucumberScenariosWithSmokeOrRegressionTag = cucumberScenarios.stream()17    .filter(cucumberScenario -> cucumberScenario.getTags().contains("@smoke")18        || cucumberScenario.getTags().contains("@regression"))19    .collect(Collectors.toList())20List<CucumberScenario> cucumberScenariosWithSmokeOrRegressionTagButNotRegression = cucumberScenarios.stream()21    .filter(cucumberScenario -> cucumberScenario.getTags().contains("@smoke")22        || cucumberScenario.getTags().contains("@regression"))23    .filter(cucumberScenario -> !cucumberScenario.getTags().contains("@regression"))24    .collect(Collectors.toList())25List<CucumberScenario> cucumberScenariosWithSmokeOrRegressionTagAndNotRegression = cucumberScenarios.stream()26    .filter(cucumberScenario -> cucumberScenario.getTags().contains("@smoke")27        || cucumberScenario.getTags().contains("@regression"))28    .filter(cucumberScenario ->

Full Screen

Full Screen

scenarios

Using AI Code Generation

copy

Full Screen

1@CucumberOptions(2        plugin = {"pretty", "html:target/site/serenity", "json:target/cucumber.json"},3        tags = {"@smoke"}4public class CucumberTestSuite {5    public void setup() {6    }7    public void teardown() {8    }9}

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Serenity Cucumber automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Most used method in CucumberSuiteSlicer

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful