How to use scenarioNotAllowed method of net.serenitybdd.jbehave.SerenityReporter class

Best Serenity jBehave code snippet using net.serenitybdd.jbehave.SerenityReporter.scenarioNotAllowed

Run Serenity jBehave automation tests on LambdaTest cloud grid

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

copy
1package net.serenitybdd.jbehave.embedders.monitors;
2
3import net.serenitybdd.core.di.WebDriverInjectors;
4import net.serenitybdd.jbehave.SerenityReporter;
5import net.serenitybdd.jbehave.embedders.ExtendedEmbedder;
6import net.thucydides.core.guice.Injectors;
7import net.thucydides.core.util.EnvironmentVariables;
8import net.thucydides.core.webdriver.DriverConfiguration;
9import org.jbehave.core.embedder.EmbedderControls;
10import org.jbehave.core.embedder.EmbedderMonitor;
11import org.jbehave.core.embedder.MetaFilter;
12import org.jbehave.core.failures.BatchFailures;
13import org.jbehave.core.model.*;
14import org.jbehave.core.reporters.ReportsCount;
15import org.slf4j.Logger;
16import org.slf4j.LoggerFactory;
17
18import java.io.File;
19import java.util.Collections;
20import java.util.List;
21import java.util.Properties;
22import java.util.Set;
23import java.util.concurrent.ConcurrentHashMap;
24import java.util.concurrent.ExecutorService;
25
26/**
27 * User: YamStranger
28 * Date: 3/25/16
29 * Time: 6:35 PM
30 */
31public class ReportingEmbedderMonitor implements EmbedderMonitor {
32    private static final Logger logger = LoggerFactory.getLogger(ReportingEmbedderMonitor.class);
33    private SerenityReporter reporter;
34    private ExtendedEmbedder embedder;
35    private final DriverConfiguration configuration;
36    private final Set<String> processedStories=Collections.newSetFromMap(new ConcurrentHashMap<String, Boolean>());
37
38
39    public ReportingEmbedderMonitor(final ExtendedEmbedder embedder) {
40        this(configuration(), embedder);
41    }
42
43    public ReportingEmbedderMonitor(final DriverConfiguration configuration,
44                                    final ExtendedEmbedder embedder) {
45        this.configuration = configuration;
46        this.embedder = embedder;
47    }
48
49
50    @Override
51    public void runningEmbeddable(String name) {
52    }
53
54    @Override
55    public void embeddableFailed(String name, Throwable cause) {
56    }
57
58    @Override
59    public void embeddableNotConfigurable(String name) {
60    }
61
62    @Override
63    public void embeddablesSkipped(List<String> classNames) {
64    }
65
66    @Override
67    public void metaNotAllowed(Meta meta, MetaFilter filter) {
68    }
69
70    @Override
71    public void storyFailed(String path, Throwable cause) {
72    }
73
74    @Override
75    public void storiesSkipped(List<String> storyPaths) {
76    }
77
78    @Override
79    public void scenarioNotAllowed(Scenario scenario, MetaFilter filter) {
80    }
81
82    @Override
83    public void batchFailed(BatchFailures failures) {
84    }
85
86    @Override
87    public void beforeOrAfterStoriesFailed() {
88    }
89
90    @Override
91    public void generatingReportsView(File outputDirectory, List<String> formats, Properties viewProperties) {
92    }
93
94    @Override
95    public void reportsViewGenerationFailed(File outputDirectory, List<String> formats, Properties viewProperties, Throwable cause) {
96    }
97
98    @Override
99    public void reportsViewGenerated(ReportsCount count) {
100    }
101
102    @Override
103    public void reportsViewFailures(ReportsCount count) {
104    }
105
106    @Override
107    public void reportsViewNotGenerated() {
108    }
109
110    @Override
111    public void runningWithAnnotatedEmbedderRunner(String className) {
112    }
113
114    @Override
115    public void annotatedInstanceNotOfType(Object annotatedInstance, Class<?> type) {
116    }
117
118    @Override
119    public void mappingStory(String storyPath, List<String> metaFilters) {
120    }
121
122    @Override
123    public void generatingMapsView(File outputDirectory, StoryMaps storyMaps, Properties viewProperties) {
124    }
125
126    @Override
127    public void mapsViewGenerationFailed(File outputDirectory, StoryMaps storyMaps, Properties viewProperties, Throwable cause) {
128    }
129
130    @Override
131    public void generatingNavigatorView(File outputDirectory, Properties viewResources) {
132    }
133
134    @Override
135    public void navigatorViewGenerationFailed(File outputDirectory, Properties viewResources, Throwable cause) {
136    }
137
138    @Override
139    public void navigatorViewNotGenerated() {
140    }
141
142    @Override
143    public void processingSystemProperties(Properties properties) {
144    }
145
146    @Override
147    public void systemPropertySet(String name, String value) {
148    }
149
150    @Override
151    public void storyTimeout(Story story, StoryDuration storyDuration) {
152    }
153
154    @Override
155    public void usingThreads(int threads) {
156    }
157
158    @Override
159    public void usingExecutorService(ExecutorService executorService) {
160    }
161
162    @Override
163    public void usingControls(EmbedderControls embedderControls) {
164    }
165
166    @Override
167    public void invalidTimeoutFormat(String path) {
168    }
169
170    @Override
171    public void usingTimeout(String path, long timeout) {
172    }
173
174    @Override
175    public void runningStory(String path) {
176        logger.info("{}story running with path {}", this.hashCode(), path);
177        final Story story = embedder.findStory(path);
178        if (story == null) {
179            logger.error("can not find any story by path {}", path);
180        } else {
181            includeInReportSkippedAndIgnoredAndWip(story);
182        }
183    }
184
185
186    @Override
187    public void storiesNotAllowed(List<Story> notAllowed, MetaFilter filter) {
188        logger.debug("processing stories Not Allowed {}", notAllowed);
189        for (final Story story : notAllowed) {
190            includeInReportSkippedAndIgnoredAndWip(story);
191        }
192    }
193
194    @Override
195    public void storiesNotAllowed(List<Story> notAllowed, MetaFilter filter, boolean verbose) {
196        logger.debug("processing stories Not Allowed {}", notAllowed);
197        for (final Story story : notAllowed) {
198            includeInReportSkippedAndIgnoredAndWip(story);
199        }
200    }
201
202    private void includeInReportSkippedAndIgnoredAndWip(final Story story) {
203        final SerenityReporter reporter = reporter();
204        this.processedStories.addAll(
205                reporter.processExcludedByFilter(story, this.processedStories)
206        );
207    }
208
209    public synchronized SerenityReporter reporter() {
210        if (this.reporter == null) {
211            this.reporter = new SerenityReporter(this.configuration);
212        }
213        return reporter;
214    }
215
216
217    private static DriverConfiguration configuration() {
218        DriverConfiguration<DriverConfiguration> configuration =
219                WebDriverInjectors.getInjector().getInstance(DriverConfiguration.class);
220        EnvironmentVariables variables =
221                Injectors.getInjector().getProvider(EnvironmentVariables.class).get().copy();
222        if (variables != null) {
223            configuration = configuration.withEnvironmentVariables(variables);
224        }
225        return configuration;
226    }
227}
228
Full Screen
copy
1package net.serenitybdd.jbehave;
2
3import com.google.common.base.Joiner;
4import com.google.common.base.Splitter;
5import com.google.common.collect.Lists;
6import net.serenitybdd.core.Serenity;
7import net.serenitybdd.core.SerenityListeners;
8import net.serenitybdd.core.SerenityReports;
9import net.thucydides.core.guice.Injectors;
10import net.thucydides.core.model.*;
11import net.thucydides.core.model.stacktrace.RootCauseAnalyzer;
12import net.thucydides.core.reports.ReportService;
13import net.thucydides.core.steps.BaseStepListener;
14import net.thucydides.core.steps.ExecutedStepDescription;
15import net.thucydides.core.steps.StepEventBus;
16import net.thucydides.core.steps.StepFailure;
17import net.thucydides.core.util.EnvironmentVariables;
18import net.thucydides.core.util.Inflector;
19import net.thucydides.core.util.NameConverter;
20import net.thucydides.core.webdriver.DriverConfiguration;
21import net.thucydides.core.webdriver.ThucydidesWebDriverSupport;
22import org.codehaus.plexus.util.StringUtils;
23import org.jbehave.core.configuration.Keywords;
24import org.jbehave.core.model.*;
25import org.jbehave.core.model.Story;
26import org.jbehave.core.reporters.NullStoryReporter;
27import org.junit.internal.AssumptionViolatedException;
28import org.slf4j.Logger;
29import org.slf4j.LoggerFactory;
30
31import java.io.File;
32import java.util.*;
33import java.util.stream.Collectors;
34
35import static net.serenitybdd.jbehave.SerenityJBehaveSystemProperties.STORY_DIRECTORY;
36import static net.thucydides.core.ThucydidesSystemProperty.WEBDRIVER_DRIVER;
37import static net.thucydides.core.steps.TestSourceType.TEST_SOURCE_JBEHAVE;
38import static org.apache.commons.lang3.StringUtils.isNotEmpty;
39
40public class SerenityReporter extends NullStoryReporter {
41
42    private static final Logger logger = LoggerFactory.getLogger(SerenityReporter.class);
43
44    private ThreadLocal<SerenityListeners> serenityListenersThreadLocal;
45    private ThreadLocal<ReportService> reportServiceThreadLocal;
46    private final List<BaseStepListener> baseStepListeners;
47
48    private final DriverConfiguration systemConfiguration;
49    private static final String OPEN_PARAM_CHAR = "\uff5f";
50    private static final String CLOSE_PARAM_CHAR = "\uff60";
51
52    private static final String PENDING = "pending";
53    private static final String MANUAL = "manual";
54    private static final String SKIP = "skip";
55    private static final String WIP = "wip";
56    private static final String IGNORE = "ignore";
57    private static final String BEFORE_STORIES = "BeforeStories";
58    private static final String AFTER_STORIES = "AfterStories";
59
60    private GivenStoryMonitor givenStoryMonitor;
61
62    private final EnvironmentVariables environmentVariables;
63
64    public SerenityReporter(DriverConfiguration systemConfiguration) {
65        this.systemConfiguration = systemConfiguration;
66        serenityListenersThreadLocal = new ThreadLocal<>();
67        reportServiceThreadLocal = new ThreadLocal<>();
68        baseStepListeners = new ArrayList<>();
69        givenStoryMonitor = new GivenStoryMonitor();
70        this.environmentVariables = Injectors.getInjector().getInstance(EnvironmentVariables.class);
71    }
72
73
74    protected void clearListeners() {
75        serenityListenersThreadLocal.remove();
76        reportServiceThreadLocal.remove();
77        givenStoryMonitor.clear();
78    }
79
80    protected SerenityListeners getSerenityListeners() {
81        if (serenityListenersThreadLocal.get() == null) {
82            SerenityListeners listeners = SerenityReports.setupListeners(systemConfiguration);
83            serenityListenersThreadLocal.set(listeners);
84            synchronized (baseStepListeners) {
85                baseStepListeners.add(listeners.getBaseStepListener());
86            }
87        }
88        return serenityListenersThreadLocal.get();
89    }
90
91    protected ReportService getReportService() {
92        return SerenityReports.getReportService(systemConfiguration);
93    }
94
95    @Override
96    public void storyNotAllowed(Story story, String filter) {
97        logger.debug("not allowed story {}", story.getName());
98    }
99
100    @Override
101    public void storyCancelled(Story story, StoryDuration storyDuration) {
102        logger.debug("cancelled story {}", story.getName());
103    }
104
105    private Stack<Story> storyStack = new Stack<>();
106
107    private Stack<Scenario> activeScenarios = new Stack<>();
108    private List<String> givenStories = new ArrayList<>();
109
110    private Story currentStory() {
111        return storyStack.peek();
112    }
113
114    private void currentStoryIs(Story story) {
115        storyStack.push(story);
116    }
117
118    private Map<String, String> storyMetadata;
119
120    private void clearActiveScenariosData() {
121        activeScenarios.clear();
122    }
123
124    @Override
125    public void beforeStory(Story story, boolean givenStory) {
126        logger.debug("before story {}", story.getName());
127        prepareSerenityListeners();
128
129        currentStoryIs(story);
130        noteAnyGivenStoriesFor(story);
131        storyMetadata = getMetadataFrom(story.getMeta());
132        if (!isFixture(story) && !givenStory) {
133
134            clearActiveScenariosData();
135
136            configureDriver(story);
137
138            SerenityStepFactory.resetContext();
139
140            if (!isAStoryLevelGiven(story)) {
141                startTestSuiteForStory(story);
142                if (givenStoriesPresentFor(story)) {
143                    startTestForFirstScenarioIn(story);
144                }
145            }
146
147        } else if (givenStory) {
148            shouldNestScenarios(true);
149        }
150        registerStoryMeta(story.getMeta());
151    }
152
153    private void prepareSerenityListeners() {
154        getSerenityListeners().withDriver(ThucydidesWebDriverSupport.getDriver());
155    }
156
157    private boolean nestScenarios = false;
158
159    private boolean shouldNestScenarios() {
160        return nestScenarios;
161    }
162
163    private void shouldNestScenarios(boolean nestScenarios) {
164        this.nestScenarios = nestScenarios;
165    }
166
167    private void startTestForFirstScenarioIn(Story story) {
168        startScenarioCalled(story.getScenarios().get(0), story);
169        StepEventBus.getEventBus().stepStarted(ExecutedStepDescription.withTitle("Preconditions"));
170        shouldNestScenarios(true);
171    }
172
173    @Override
174    public void beforeScenario(Scenario scenario) {
175        String scenarioTitle = scenario.getTitle();
176        logger.debug("before scenario started {}", scenarioTitle);
177
178        if (shouldResetStepsBeforeEachScenario()) {
179            SerenityStepFactory.resetContext();
180        }
181
182        resetDriverIfNecessary();
183
184        if (isCurrentScenario(scenarioTitle)) {
185            return;
186        }
187
188        if (shouldNestScenarios()) {
189            startNewStep(scenarioTitle);
190        } else {
191            startScenarioCalled(scenario, currentStory());
192        }
193
194        Meta meta = scenario.getMeta();
195
196        logger.debug("scenario:\"{}\" registering metadata for {}",
197                StringUtils.isEmpty(scenarioTitle) ? " don't know name " : scenarioTitle, meta);
198        registerIssues(meta);
199        registerFeaturesAndEpics(meta);
200        registerTags(meta);
201        registerMetadata(meta);
202        registerScenarioMeta(meta);
203
204        markAsSkippedOrPendingIfAnnotatedAsSuchIn(scenarioTags(scenario));
205    }
206
207    private List<String> scenarioTags(Scenario scenario) {
208        List<String> scenarioTags = new ArrayList<>(scenario.getMeta().getPropertyNames());
209        scenarioTags.addAll(currentStory().getMeta().getPropertyNames());
210        return scenarioTags;
211    }
212
213    private void resetDriverIfNecessary() {
214        if (Serenity.currentDriverIsDisabled()) {
215            Serenity.getWebdriverManager().resetDriver();
216        }
217    }
218
219    private boolean isCurrentScenario(String scenarioTitle) {
220        return !activeScenarios.empty() && scenarioTitle.equals(activeScenarios.peek().getTitle());
221    }
222
223    private Scenario currentScenario() {
224        return activeScenarios.peek();
225    }
226
227    private void startNewStep(String scenarioTitle) {
228        if (givenStoryMonitor.isInGivenStory() && StepEventBus.getEventBus().areStepsRunning()) {
229            StepEventBus.getEventBus().updateCurrentStepTitleAsPrecondition(scenarioTitle);
230        } else {
231            StepEventBus.getEventBus().stepStarted(ExecutedStepDescription.withTitle(scenarioTitle),
232                    givenStoryMonitor.isInGivenStory());
233        }
234    }
235
236    private boolean givenStoriesPresentFor(Story story) {
237        return !story.getGivenStories().getStories().isEmpty();
238    }
239
240    private void startTestSuiteForStory(Story story) {
241        String storyName = removeSuffixFrom(story.getName());
242        String storyTitle = (isNotEmpty(story.getDescription().asString())) ? story.getDescription().asString() : NameConverter.humanize(storyName);
243
244        net.thucydides.core.model.Story userStory
245                = net.thucydides.core.model.Story.withIdAndPath(storyName, storyTitle, stripStoriesFolderFrom(story.getPath()))
246                .withNarrative(getNarrativeFrom(story));
247        StepEventBus.getEventBus().testSuiteStarted(userStory);
248        registerTags(story);
249    }
250
251    private String stripStoriesFolderFrom(String path) {
252        String storyDirectory = environmentVariables.getProperty(STORY_DIRECTORY,"stories");
253
254        return (path.toLowerCase().startsWith(storyDirectory + "/")) ? path.substring(storyDirectory.length() + 1) : path;
255    }
256
257    private String getNarrativeFrom(Story story) {
258        return (!story.getNarrative().isEmpty()) ?
259                story.getNarrative().asString(new Keywords()).trim() : "";
260    }
261
262    private void noteAnyGivenStoriesFor(Story story) {
263        for (GivenStory given : story.getGivenStories().getStories()) {
264            String givenStoryName = new File(given.getPath()).getName();
265            givenStories.add(givenStoryName);
266        }
267    }
268
269    private boolean isAStoryLevelGiven(Story story) {
270        for (String givenStoryName : givenStories) {
271            if (hasSameName(story, givenStoryName)) {
272                return true;
273            }
274        }
275        return false;
276    }
277
278    private void givenStoryDone(Story story) {
279        givenStories.remove(story.getName());
280    }
281
282    private boolean hasSameName(Story story, String givenStoryName) {
283        return story.getName().equalsIgnoreCase(givenStoryName);
284    }
285
286    private void configureDriver(Story story) {
287        StepEventBus.getEventBus().setUniqueSession(systemConfiguration.shouldUseAUniqueBrowser());
288        String requestedDriver = getRequestedDriver(story.getMeta());
289        // An annotated driver that ends with "!" overrides the command-line configured driver
290        if (isEmphatic(requestedDriver)) {
291            ThucydidesWebDriverSupport.useDefaultDriver(unemphasised(requestedDriver));
292        } else if (StringUtils.isNotEmpty(requestedDriver) && (!driverIsProvidedInTheEnvironmentVariables())){
293            ThucydidesWebDriverSupport.useDefaultDriver(requestedDriver);
294        }
295    }
296
297    private String unemphasised(String requestedDriver) {
298        return requestedDriver.replace("!","");
299    }
300
301    private boolean isEmphatic(String requestedDriver) {
302        return requestedDriver != null && requestedDriver.endsWith("!");
303    }
304
305    private boolean driverIsProvidedInTheEnvironmentVariables() {
306        return (isNotEmpty(systemConfiguration.getEnvironmentVariables().getProperty(WEBDRIVER_DRIVER)));
307    }
308
309    private void registerTags(Story story) {
310        registerStoryIssues(story.getMeta());
311        registerStoryFeaturesAndEpics(story.getMeta());
312        registerStoryTags(story.getMeta());
313        registerStoryMeta(story.getMeta());
314    }
315
316    private boolean isFixture(Story story) {
317        return (story.getName().equals(BEFORE_STORIES) || story.getName().equals(AFTER_STORIES));
318    }
319
320    private String getRequestedDriver(Meta metaData) {
321
322        if (metaData == null) {
323            return null;
324        }
325
326        if (StringUtils.isNotEmpty(metaData.getProperty("driver"))) {
327            return metaData.getProperty("driver");
328        }
329        if (systemConfiguration.getDriverType() != null) {
330            return systemConfiguration.getDriverType().toString();
331        }
332        return null;
333    }
334
335    private List<String> getIssueOrIssuesPropertyValues(Meta metaData) {
336        return getTagPropertyValues(metaData, "issue");
337    }
338
339    private List<TestTag> getFeatureOrFeaturesPropertyValues(Meta metaData) {
340        List<String> features = getTagPropertyValues(metaData, "feature");
341
342        return features.stream().map(
343                featureName -> TestTag.withName(featureName).andType("feature")
344        ).collect(Collectors.toList());
345    }
346
347    private List<TestTag> getEpicOrEpicsPropertyValues(Meta metaData) {
348        List<String> epics = getTagPropertyValues(metaData, "epic");
349        return epics.stream().map(
350                epicName -> TestTag.withName(epicName).andType("epic")
351        ).collect(Collectors.toList());
352    }
353
354    private List<TestTag> getTagOrTagsPropertyValues(Meta metaData) {
355        List<String> tags = getTagPropertyValues(metaData, "tag");
356        return tags.stream()
357                .map(  this::toTag )
358                .collect(Collectors.toList());
359    }
360
361    public TestTag toTag(String tag) {
362        List<String> tagParts = Lists.newArrayList(Splitter.on(":").trimResults().split(tag));
363        if (tagParts.size() == 2) {
364            return TestTag.withName(tagParts.get(1)).andType(tagParts.get(0));
365        } else {
366            return TestTag.withName("true").andType(tagParts.get(0));
367        }
368    }
369
370
371    private List<String> getTagPropertyValues(Meta metaData, String tagType) {
372        if (metaData == null) {
373            return new ArrayList<>();
374        }
375
376        String singularTag = metaData.getProperty(tagType);
377        String pluralTagType = Inflector.getInstance().pluralize(tagType);
378
379        String multipleTags = metaData.getProperty(pluralTagType);
380        String allTags = Joiner.on(',').skipNulls().join(singularTag, multipleTags);
381
382        return Lists.newArrayList(Splitter.on(',').omitEmptyStrings().trimResults().split(allTags));
383    }
384
385    private void registerIssues(Meta metaData) {
386        List<String> issues = getIssueOrIssuesPropertyValues(metaData);
387
388        if (!issues.isEmpty()) {
389            StepEventBus.getEventBus().addIssuesToCurrentTest(issues);
390        }
391    }
392
393    private void registerStoryIssues(Meta metaData) {
394        List<String> issues = getIssueOrIssuesPropertyValues(metaData);
395
396        if (!issues.isEmpty()) {
397            StepEventBus.getEventBus().addIssuesToCurrentStory(issues);
398        }
399    }
400
401    private void registerFeaturesAndEpics(Meta metaData) {
402        List<TestTag> featuresAndEpics = featureAndEpicTags(metaData);
403
404        if (!featuresAndEpics.isEmpty()) {
405            StepEventBus.getEventBus().addTagsToCurrentTest(featuresAndEpics);
406        }
407    }
408
409    private List<TestTag> featureAndEpicTags(Meta metaData) {
410        List<TestTag> featuresAndEpics = new ArrayList<>();
411        featuresAndEpics.addAll(getFeatureOrFeaturesPropertyValues(metaData));
412        featuresAndEpics.addAll(getEpicOrEpicsPropertyValues(metaData));
413        return featuresAndEpics;
414    }
415
416    private void registerStoryFeaturesAndEpics(Meta metaData) {
417        List<TestTag> featuresAndEpics = featureAndEpicTags(metaData);
418
419        if (!featuresAndEpics.isEmpty()) {
420            StepEventBus.getEventBus().addTagsToCurrentStory(featuresAndEpics);
421        }
422    }
423
424    private void registerTags(Meta metaData) {
425        List<TestTag> tags = getTagOrTagsPropertyValues(metaData);
426
427        if (!tags.isEmpty()) {
428            StepEventBus.getEventBus().addTagsToCurrentTest(tags);
429        }
430    }
431
432    private Map<String, String> getMetadataFrom(Meta metaData) {
433        Map<String, String> metadataValues = new HashMap<>();
434        if (metaData == null) {
435            return metadataValues;
436        }
437
438        for (String propertyName : metaData.getPropertyNames()) {
439            metadataValues.put(propertyName, metaData.getProperty(propertyName));
440        }
441        return metadataValues;
442    }
443
444    private void registerMetadata(Meta metaData) {
445        Serenity.getCurrentSession().clearMetaData();
446
447        Map<String, String> scenarioMetadata = getMetadataFrom(metaData);
448        scenarioMetadata.putAll(storyMetadata);
449        for (String key : scenarioMetadata.keySet()) {
450            Serenity.getCurrentSession().addMetaData(key, scenarioMetadata.get(key));
451        }
452    }
453
454    private void registerStoryTags(Meta metaData) {
455        List<TestTag> tags = getTagOrTagsPropertyValues(metaData);
456
457        if (!tags.isEmpty()) {
458            StepEventBus.getEventBus().addTagsToCurrentStory(tags);
459        }
460    }
461
462    private void registerStoryMeta(Meta metaData) {
463        if (isPending(metaData)) {
464            StepEventBus.getEventBus().suspendTest();
465        } else if (isSkipped(metaData)) {
466            StepEventBus.getEventBus().suspendTest();
467        } else if (isIgnored(metaData)) {
468            StepEventBus.getEventBus().suspendTest();
469        } else if (isManual(metaData)) {
470            StepEventBus.getEventBus().suspendTest();
471        }
472    }
473
474    private boolean isStoryManual() {
475        return isManual(currentStory().getMeta());
476    }
477
478    private void registerScenarioMeta(Meta metaData) {
479
480        // Manual can be combined with the other tags to override the default result category
481        if (isManual(metaData) || isStoryManual()) {
482            StepEventBus.getEventBus().testIsManual();
483        }
484    }
485
486    private String removeSuffixFrom(String name) {
487        return (name.contains(".")) ? name.substring(0, name.indexOf(".")) : name;
488    }
489
490    @Override
491    public void afterStory(boolean given) {
492        logger.debug("afterStory {}", given);
493        shouldNestScenarios(false);
494        if (given) {
495            givenStoryMonitor.exitingGivenStory();
496            givenStoryDone(currentStory());
497        } else {
498            if (isAfterStory(currentStory())) {
499                generateReports();
500            } else if (!isFixture(currentStory()) && (!isAStoryLevelGiven(currentStory()))) {
501                StepEventBus.getEventBus().testSuiteFinished();
502                clearListeners();
503            }
504        }
505
506        storyStack.pop();
507    }
508
509    private boolean isAfterStory(Story currentStory) {
510        return (currentStory.getName().equals(AFTER_STORIES));
511    }
512
513    private synchronized void generateReports() {
514        getReportService().generateReportsFor(getAllTestOutcomes());
515    }
516
517    public List<TestOutcome> getAllTestOutcomes() {
518
519        return baseStepListeners.stream()
520                .map(BaseStepListener::getTestOutcomes)
521                .flatMap(Collection::stream)
522                .collect(Collectors.toList());
523    }
524
525    @Override
526    public void narrative(Narrative narrative) {
527        logger.debug("narrative {}", narrative);
528    }
529
530    @Override
531    public void lifecyle(Lifecycle lifecycle) {
532        logger.debug("lifecyle {}", lifecycle);
533    }
534
535    @Override
536    public void scenarioNotAllowed(Scenario scenario, String s) {
537        logger.debug("scenarioNotAllowed {}", scenario.getTitle());
538        StepEventBus.getEventBus().testIgnored();
539    }
540
541    private void startScenarioCalled(Scenario scenario, Story story) {
542        StepEventBus.getEventBus().setTestSource(TEST_SOURCE_JBEHAVE.getValue());
543        StepEventBus.getEventBus().testStarted(scenario.getTitle(), story.getPath() + ";" + scenario.getTitle());
544        activeScenarios.add(scenario);
545    }
546
547    private boolean shouldResetStepsBeforeEachScenario() {
548        return systemConfiguration.getEnvironmentVariables().getPropertyAsBoolean(
549                SerenityJBehaveSystemProperties.RESET_STEPS_EACH_SCENARIO.getName(), true);
550    }
551
552    private void markAsSkippedOrPendingIfAnnotatedAsSuchIn(List<String> tags) {
553        if (isManual(tags)) {
554            StepEventBus.getEventBus().testIsManual();
555        }
556        if (isSkipped(tags)) {
557            StepEventBus.getEventBus().testSkipped();
558            StepEventBus.getEventBus().getBaseStepListener().overrideResultTo(TestResult.SKIPPED);
559        }
560        if (isPending(tags)) {
561            StepEventBus.getEventBus().testPending();
562            StepEventBus.getEventBus().getBaseStepListener().overrideResultTo(TestResult.PENDING);
563        }
564        if (isIgnored(tags)) {
565            StepEventBus.getEventBus().testIgnored();
566            StepEventBus.getEventBus().getBaseStepListener().overrideResultTo(TestResult.IGNORED);
567        }
568    }
569
570    private boolean isSkipped(List<String> tags) {
571        return tags.contains("skip") || tags.contains("wip");
572    }
573
574    private boolean isPending(List<String> tags) {
575        return tags.contains("pending");
576    }
577
578    private boolean isIgnored(List<String> tags) {
579        return tags.contains("ignore");
580    }
581
582    private boolean isManual(List<String> tags) {
583        return tags.contains("manual");
584    }
585
586    private boolean isPending(Meta metaData) {
587        return metaData != null && (metaData.hasProperty(PENDING));
588    }
589
590    private boolean isManual(Meta metaData) {
591        return metaData != null && (metaData.hasProperty(MANUAL));
592    }
593
594    private boolean isSkipped(Meta metaData) {
595        return metaData != null && (metaData.hasProperty(WIP) || metaData.hasProperty(SKIP));
596    }
597
598    private boolean isCandidateToBeExecuted(Meta metaData) {
599        return !isIgnored(metaData) && !isPending(metaData) && !isSkipped(metaData);
600    }
601
602    private boolean isIgnored(Meta metaData) {
603        return metaData != null && (metaData.hasProperty(IGNORE));
604    }
605
606    @Override
607    public void afterScenario() {
608        Scenario scenario = currentScenario();
609        logger.debug("afterScenario : {}", scenario.getTitle());
610        List<String> scenarioTags = scenarioTags(scenario);
611        markAsSkippedOrPendingIfAnnotatedAsSuchIn(scenarioTags);
612
613        if (givenStoryMonitor.isInGivenStory() || shouldNestScenarios()) {
614            StepEventBus.getEventBus().stepFinished();
615        } else {
616            if (!(isPending(scenarioTags) || isSkipped(scenarioTags) || isIgnored(scenarioTags))) {
617                StepEventBus.getEventBus().testFinished(executingExamples());
618            }
619            activeScenarios.pop();
620        }
621
622        ThucydidesWebDriverSupport.clearStepLibraries();
623    }
624
625    @Override
626    public void givenStories(GivenStories givenStories) {
627        logger.debug("givenStories {}", givenStories);
628        givenStoryMonitor.enteringGivenStory();
629    }
630
631    @Override
632    public void givenStories(List<String> strings) {
633        logger.debug("givenStories {}", strings);
634    }
635
636    int exampleCount = 0;
637
638    @Override
639    public void beforeExamples(List<String> steps, ExamplesTable table) {
640        logger.debug("beforeExamples {} {}", steps, table);
641        if (givenStoryMonitor.isInGivenStory()) {
642            return;
643        }
644
645        exampleCount = 0;
646        StepEventBus.getEventBus().useExamplesFrom(serenityTableFrom(table));
647    }
648
649    private DataTable serenityTableFrom(ExamplesTable table) {
650        String scenarioOutline = scenarioOutlineFrom(currentScenario());
651        return DataTable.withHeaders(table.getHeaders())
652                .andScenarioOutline(scenarioOutline)
653                .andMappedRows(table.getRows())
654                .build();
655
656    }
657
658    private String scenarioOutlineFrom(Scenario scenario) {
659        StringBuilder outline = new StringBuilder();
660        for (String step : scenario.getSteps()) {
661            outline.append(step.trim()).append(System.lineSeparator());
662        }
663        return outline.toString();
664    }
665
666    @Override
667    public void example(Map<String, String> tableRow, int exampleIndex) {
668        StepEventBus.getEventBus().clearStepFailures();
669
670        if (givenStoryMonitor.isInGivenStory()) {
671            return;
672        }
673
674        if (executingExamples()) {
675            finishExample();
676        }
677        exampleCount++;
678        startExample(tableRow);
679    }
680
681    private void startExample(Map<String, String> data) {
682        StepEventBus.getEventBus().exampleStarted(data);
683    }
684
685    private void finishExample() {
686        StepEventBus.getEventBus().exampleFinished();
687    }
688
689    private boolean executingExamples() {
690        return (exampleCount > 0);
691    }
692
693    @Override
694    public void afterExamples() {
695        if (givenStoryMonitor.isInGivenStory()) {
696            return;
697        }
698
699        finishExample();
700    }
701
702    @Override
703    public void beforeStep(String stepTitle) {
704        StepEventBus.getEventBus().stepStarted(ExecutedStepDescription.withTitle(stepTitle));
705    }
706
707    @Override
708    public void successful(String title) {
709        if (annotatedResultTakesPriority()) {
710            processAnnotatedResult();
711        } else {
712            StepEventBus.getEventBus().updateCurrentStepTitle(normalized(title));
713            StepEventBus.getEventBus().stepFinished();
714        }
715    }
716
717    private void processAnnotatedResult() {
718        TestResult forcedResult = StepEventBus.getEventBus().getForcedResult().get();
719        switch (forcedResult) {
720            case PENDING:
721                StepEventBus.getEventBus().stepPending();
722                break;
723            case IGNORED:
724                StepEventBus.getEventBus().stepIgnored();
725                break;
726            case SKIPPED:
727                StepEventBus.getEventBus().stepIgnored();
728                break;
729            default:
730                StepEventBus.getEventBus().stepIgnored();
731        }
732
733    }
734
735    private boolean annotatedResultTakesPriority() {
736        return StepEventBus.getEventBus().getForcedResult().isPresent();
737    }
738
739    @Override
740    public void ignorable(String title) {
741        StepEventBus.getEventBus().updateCurrentStepTitle(normalized(title));
742        StepEventBus.getEventBus().stepIgnored();
743    }
744
745    @Override
746    public void comment(String step) {
747        StepEventBus.getEventBus().stepStarted(ExecutedStepDescription.withTitle(step));
748        StepEventBus.getEventBus().stepIgnored();
749    }
750
751    @Override
752    public void pending(String stepTitle) {
753        StepEventBus.getEventBus().stepStarted(ExecutedStepDescription.withTitle(normalized(stepTitle)));
754        StepEventBus.getEventBus().stepPending();
755
756    }
757
758    @Override
759    public void notPerformed(String stepTitle) {
760        StepEventBus.getEventBus().stepStarted(ExecutedStepDescription.withTitle(normalized(stepTitle)));
761        StepEventBus.getEventBus().stepIgnored();
762    }
763
764    @Override
765    public void failed(String stepTitle, Throwable cause) {
766        if (!StepEventBus.getEventBus().testSuiteHasStarted()) {
767            declareOutOfSuiteFailure();
768        }
769
770        if (!errorOrFailureRecordedForStep(cause.getCause())) {
771            StepEventBus.getEventBus().updateCurrentStepTitle(stepTitle);
772            Throwable rootCause = new RootCauseAnalyzer(cause.getCause()).getRootCause().toException();
773
774            if (isAssumptionFailure(rootCause)) {
775                StepEventBus.getEventBus().assumptionViolated(rootCause.getMessage());
776            } else {
777                StepEventBus.getEventBus().stepFailed(new StepFailure(ExecutedStepDescription.withTitle(normalized(stepTitle)), rootCause));
778            }
779        }
780
781    }
782
783    private void declareOutOfSuiteFailure() {
784        String storyName = !storyStack.isEmpty() ? storyStack.peek().getName() : "Before or After Story";
785        String storyId = !storyStack.isEmpty() ? storyStack.peek().getPath() : null;
786        StepEventBus.getEventBus().testStarted(storyName, storyId);
787    }
788
789    private boolean isAssumptionFailure(Throwable rootCause) {
790        return (AssumptionViolatedException.class.isAssignableFrom(rootCause.getClass()));
791    }
792
793    public List<String> processExcludedByFilter(final Story story, final Set<String> exclude) {
794        final Meta storyMeta = story.getMeta();
795        final List<Scenario> processing = new LinkedList<>();
796        final List<String> processed = new LinkedList<>();
797
798        if (isSkipped(storyMeta) || isIgnored(storyMeta)) { //this story should be excluded by filter
799            processing.addAll(story.getScenarios());
800        } else {
801            for (Scenario scenario : story.getScenarios()) {
802                final Meta scenarioMeta = scenario.getMeta();
803                if (isSkipped(scenarioMeta) || isIgnored(scenarioMeta)) { //this scenario should be excluded by filter
804                    processing.add(scenario);
805                }
806            }
807        }
808        if (processing.size() > 0) {
809            final Story beforeStory = new Story();
810            beforeStory.namedAs(BEFORE_STORIES);
811            final Story afterStory = new Story();
812            afterStory.namedAs(AFTER_STORIES);
813
814            final Narrative narrative = story.getNarrative();
815            beforeStory(beforeStory, false);
816            afterStory(false);
817            beforeStory(story, false);
818            narrative(narrative);
819            for (final Scenario filtered : processing) {
820                final String scenarioKey = scenarioKey(story, filtered);
821                if (!exclude.contains(scenarioKey)) {
822
823                    beforeScenario(filtered);
824
825                    final List<String> steps = filtered.getSteps();
826                    if (ExamplesTable.EMPTY == filtered.getExamplesTable() || filtered.getExamplesTable().getRows().size() == 0) {
827                        for (final String step : steps) {
828                            beforeStep(step);
829                            successful(step);
830                        }
831                    } else {
832                        final ExamplesTable examples = filtered.getExamplesTable();
833                        beforeExamples(steps, examples);
834                        for (final Map<String, String> row : examples.getRows()) {
835                            example(row);
836                            for (final String step : steps) {
837                                beforeStep(step);
838                                successful(step);
839                            }
840                        }
841                        afterExamples();
842                    }
843                    afterScenario();
844                    processed.add(scenarioKey(story, filtered));
845                }
846            }
847            afterStory(false);
848            beforeStory(afterStory, false);
849            afterStory(false);
850        }
851        return processed;
852    }
853
854    private String scenarioKey(final Story story, final Scenario scenario) {
855        return story.getPath().concat(scenario.getTitle());
856    }
857
858    @Override
859    public void failedOutcomes(String s, OutcomesTable outcomesTable) {
860        logger.debug("failedOutcomes");
861    }
862
863    @Override
864    public void restarted(String s, Throwable throwable) {
865        logger.debug("restarted");
866    }
867
868    @Override
869    public void restartedStory(Story story, Throwable cause) {
870        logger.debug("restartedStory");
871    }
872
873    @Override
874    public void dryRun() {
875        logger.debug("dryRun");
876    }
877
878    @Override
879    public void pendingMethods(List<String> strings) {
880        logger.debug("pendingMethods");
881    }
882
883    private String normalized(String value) {
884        return value.replaceAll(OPEN_PARAM_CHAR, "{").replaceAll(CLOSE_PARAM_CHAR, "}");
885
886    }
887
888    private boolean errorOrFailureRecordedForStep(Throwable cause) {
889        if (!latestTestOutcome().isPresent()) {
890            return false;
891        }
892
893        for (TestStep step : latestTestOutcome().get().getFlattenedTestSteps()) {
894            if ((step.getException() != null) && (step.getException().getOriginalCause() == cause)) {
895                return true;
896            }
897        }
898        return false;
899    }
900
901    private Optional<TestOutcome> latestTestOutcome() {
902        List<TestOutcome> recordedOutcomes = StepEventBus.getEventBus().getBaseStepListener().getTestOutcomes();
903        return recordedOutcomes.isEmpty() ? Optional.empty()
904                : Optional.of(recordedOutcomes.get(recordedOutcomes.size() - 1));
905    }
906
907}
908
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

Trigger scenarioNotAllowed code on LambdaTest Cloud Grid

Execute automation tests with scenarioNotAllowed on a cloud-based Grid of 3000+ real browsers and operating systems for both web and mobile applications.

Test now for Free
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)