How to use getThreadCount method of net.serenitybdd.jbehave.runners.SerenityReportingRunner class

Best Serenity jBehave code snippet using net.serenitybdd.jbehave.runners.SerenityReportingRunner.getThreadCount

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.runners;
2
3import com.github.valfirst.jbehave.junit.monitoring.JUnitDescriptionGenerator;
4import com.github.valfirst.jbehave.junit.monitoring.JUnitReportingRunner;
5import com.github.valfirst.jbehave.junit.monitoring.JUnitScenarioReporter;
6import com.github.valfirst.jbehave.junit.monitoring.StoryPathsExtractor;
7import com.google.common.base.Splitter;
8import com.google.common.collect.Lists;
9import net.serenitybdd.core.exceptions.SerenityManagedException;
10import net.serenitybdd.jbehave.SerenityJBehaveSystemProperties;
11import net.serenitybdd.jbehave.SerenityStories;
12import net.serenitybdd.jbehave.annotations.Metafilter;
13import net.serenitybdd.jbehave.embedders.ExtendedEmbedder;
14import net.serenitybdd.jbehave.embedders.monitors.ReportingEmbedderMonitor;
15import net.thucydides.core.guice.Injectors;
16import net.thucydides.core.steps.StepEventBus;
17import net.thucydides.core.util.EnvironmentVariables;
18import org.codehaus.plexus.util.StringUtils;
19import org.jbehave.core.ConfigurableEmbedder;
20import org.jbehave.core.configuration.Configuration;
21import org.jbehave.core.embedder.Embedder;
22import org.jbehave.core.embedder.PerformableTree;
23import org.jbehave.core.embedder.PerformableTree.RunContext;
24import org.jbehave.core.failures.BatchFailures;
25import org.jbehave.core.model.Story;
26import org.jbehave.core.reporters.StoryReporterBuilder;
27import org.jbehave.core.steps.CandidateSteps;
28import org.jbehave.core.steps.InjectableStepsFactory;
29import org.jbehave.core.steps.NullStepMonitor;
30import org.jbehave.core.steps.StepMonitor;
31import org.junit.runner.Description;
32import org.junit.runner.Runner;
33import org.junit.runner.notification.RunNotifier;
34import org.slf4j.Logger;
35import org.slf4j.LoggerFactory;
36
37import java.lang.reflect.InvocationTargetException;
38import java.lang.reflect.Method;
39import java.util.*;
40import java.util.regex.Pattern;
41import java.util.stream.Collectors;
42import java.util.stream.Stream;
43
44public class SerenityReportingRunner extends Runner {
45
46    private List<Description> storyDescriptions;
47    private ExtendedEmbedder configuredEmbedder;
48    private List<String> storyPaths;
49    private Configuration configuration;
50    private Description description;
51    List<CandidateSteps> candidateSteps;
52
53    private final ConfigurableEmbedder configurableEmbedder;
54    private final Class<? extends ConfigurableEmbedder> testClass;
55    private final EnvironmentVariables environmentVariables;
56
57    private static final Logger LOGGER = LoggerFactory.getLogger(SerenityReportingRunner.class);
58    private boolean runningInMaven;
59
60    @SuppressWarnings("unchecked")
61    public SerenityReportingRunner(Class<? extends ConfigurableEmbedder> testClass) throws Throwable {
62        this(testClass, testClass.newInstance());
63    }
64
65    public SerenityReportingRunner(Class<? extends ConfigurableEmbedder> testClass,
66                                   ConfigurableEmbedder embedder) {
67        this.configurableEmbedder = embedder;
68        ExtendedEmbedder extendedEmbedder = new ExtendedEmbedder(this.configurableEmbedder.configuredEmbedder());
69        extendedEmbedder.getEmbedderMonitor().subscribe(new ReportingEmbedderMonitor(
70                ((SerenityStories) embedder).getSystemConfiguration(), extendedEmbedder));
71        this.configurableEmbedder.useEmbedder(extendedEmbedder);
72        this.testClass = testClass;
73        this.environmentVariables = environmentVariablesFrom(configurableEmbedder);
74    }
75
76    protected List<Description> getDescriptions() {
77        if (storyDescriptions == null) {
78            storyDescriptions = buildDescriptionFromStories();
79        }
80        return storyDescriptions;
81    }
82
83    protected Configuration getConfiguration() {
84        if (configuration == null) {
85            configuration = getConfiguredEmbedder().configuration();
86        }
87        return configuration;
88    }
89
90    public ExtendedEmbedder getConfiguredEmbedder() {
91        if (configuredEmbedder == null) {
92            configuredEmbedder = (ExtendedEmbedder) configurableEmbedder.configuredEmbedder();
93        }
94        return configuredEmbedder;
95    }
96
97    List<String> getStoryPaths() {
98        if ((storyPaths == null) || (storyPaths.isEmpty())) {
99            storyPaths = storyPathsFromRunnerClass();
100        }
101        return storyPaths;
102    }
103
104    private List<String> storyPathsFromRunnerClass() {
105        try {
106            List<String> storyPaths = new StoryPathsExtractor(configurableEmbedder).getStoryPaths();
107
108            String storyFilter = getStoryFilterFrom(configurableEmbedder);
109
110            return storyPaths.stream()
111                             .filter(story -> story.matches(storyFilter))
112                             .collect(Collectors.toList());
113
114        } catch (Throwable e) {
115            LOGGER.error("Could not load story paths", e);
116            return Collections.emptyList();
117        }
118    }
119
120    private String getStoryFilterFrom(ConfigurableEmbedder embedder) {
121
122        String defaultStoryFilter = environmentVariables.getProperty(SerenityJBehaveSystemProperties.STORY_FILTER.getName(), ".*");
123
124        Optional<Method> getStoryFilter = Arrays.stream(embedder.getClass().getMethods())
125                .filter(method -> method.getName().equals("getStoryFilter"))
126                .findFirst();
127
128        if (getStoryFilter.isPresent()) {
129            try {
130                Optional<Object> storyFilterValue = Optional.ofNullable(getStoryFilter.get().invoke(embedder));
131                return storyFilterValue.orElse(defaultStoryFilter).toString();
132            } catch (IllegalAccessException | InvocationTargetException e) {
133                LOGGER.warn("Could not invoke getStoryFilter() method on {}", embedder, e);
134            }
135        }
136        return defaultStoryFilter;
137    }
138
139    private EnvironmentVariables environmentVariablesFrom(ConfigurableEmbedder configurableEmbedder) {
140        if (configurableEmbedder instanceof SerenityStories) {
141            return ((SerenityStories) configurableEmbedder).getEnvironmentVariables();
142        } else {
143            return Injectors.getInjector().getProvider(EnvironmentVariables.class).get();
144        }
145    }
146
147    @Override
148    public Description getDescription() {
149        if (description == null) {
150            description = Description.createSuiteDescription(configurableEmbedder.getClass());
151            for (Description childDescription : getDescriptions()) {
152                description.addChild(childDescription);
153            }
154        }
155        return description;
156    }
157
158    private int testCount = 0;
159
160    @Override
161    public int testCount() {
162        if (testCount == 0) {
163            testCount = countStories();
164        }
165        return testCount;
166    }
167
168    @Override
169    public void run(RunNotifier notifier) {
170
171        beforeStoriesRun(getConfiguredEmbedder());
172
173        getConfiguredEmbedder().embedderControls().doIgnoreFailureInView(getIgnoreFailuresInView());
174        getConfiguredEmbedder().embedderControls().doIgnoreFailureInStories(getIgnoreFailuresInStories());
175        getConfiguredEmbedder().embedderControls().useStoryTimeoutInSecs(getStoryTimeoutInSecs());
176        getConfiguredEmbedder().embedderControls().useStoryTimeouts(getStoryTimeout());
177        getConfiguredEmbedder().embedderControls().useThreads(getThreadCount());
178
179        if (metaFiltersAreDefined()) {
180            getConfiguredEmbedder().useMetaFilters(getMetaFilters());
181        }
182
183//      if (!isRunningInMaven() && !isRunningInGradle()) {
184
185        JUnitScenarioReporter junitReporter = new JUnitScenarioReporter(notifier, testCount(), getDescription(),
186                getConfiguredEmbedder().configuration().keywords());
187        // tell the reporter how to handle pending steps
188        junitReporter.usePendingStepStrategy(getConfiguration().pendingStepStrategy());
189
190        JUnitReportingRunner.recommendedControls(getConfiguredEmbedder());
191
192        addToStoryReporterFormats(junitReporter);
193//      }
194
195        try {
196            getConfiguredEmbedder().runStoriesAsPaths(getStoryPaths());
197        } catch (Throwable e) {
198            throw new SerenityManagedException(e);
199        } finally {
200            getConfiguredEmbedder().generateCrossReference();
201        }
202        shutdownTestSuite();
203    }
204
205    private boolean isRunningInGradle() {
206        return Stream.of(new Exception().getStackTrace()).anyMatch(elt -> elt.getClassName().startsWith("org.gradle"));
207    }
208
209    /**
210     * Override this method to add custom configuration to the JBehave embedder object.
211     *
212     * @param configuredEmbedder
213     */
214    public void beforeStoriesRun(ExtendedEmbedder configuredEmbedder) {
215    }
216
217    private void shutdownTestSuite() {
218        StepEventBus.getEventBus().testSuiteFinished();
219    }
220
221    List<CandidateSteps> getCandidateSteps() {
222        if (candidateSteps == null) {
223            StepMonitor originalStepMonitor = createCandidateStepsWithNoMonitor();
224            createCandidateStepsWith(originalStepMonitor);
225        }
226        return candidateSteps;
227    }
228
229    private void createCandidateStepsWith(StepMonitor stepMonitor) {
230        // reset step monitor and recreate candidate steps
231        getConfiguration().useStepMonitor(stepMonitor);
232        candidateSteps = buildCandidateSteps();
233        candidateSteps.forEach(
234                step -> step.configuration().useStepMonitor(stepMonitor)
235        );
236    }
237
238    private StepMonitor createCandidateStepsWithNoMonitor() {
239        StepMonitor usedStepMonitor = getConfiguration().stepMonitor();
240        createCandidateStepsWith(new NullStepMonitor());
241        return usedStepMonitor;
242    }
243
244    private List<CandidateSteps> buildCandidateSteps() {
245        List<CandidateSteps> candidateSteps;
246
247        InjectableStepsFactory stepsFactory = configurableEmbedder
248                .stepsFactory();
249        if (stepsFactory != null) {
250            candidateSteps = stepsFactory.createCandidateSteps();
251        } else {
252            Embedder embedder = getConfiguredEmbedder();
253            candidateSteps = embedder.candidateSteps();
254            if (candidateSteps == null || candidateSteps.isEmpty()) {
255                candidateSteps = embedder.stepsFactory().createCandidateSteps();
256            }
257        }
258        return candidateSteps;
259    }
260
261    private void addToStoryReporterFormats(JUnitScenarioReporter junitReporter) {
262        StoryReporterBuilder storyReporterBuilder = getConfiguration().storyReporterBuilder();
263        StoryReporterBuilder.ProvidedFormat junitReportFormat
264                = new StoryReporterBuilder.ProvidedFormat(junitReporter);
265        storyReporterBuilder.withFormats(junitReportFormat);
266    }
267
268    private List<Description> buildDescriptionFromStories() {
269        List<CandidateSteps> candidateSteps = getCandidateSteps();
270        JUnitDescriptionGenerator descriptionGenerator = new JUnitDescriptionGenerator(candidateSteps, getConfiguration());
271        List<Description> storyDescriptions = new ArrayList<>();
272
273        addSuite(storyDescriptions, "BeforeStories");
274        PerformableTree performableTree = createPerformableTree(candidateSteps, getStoryPaths());
275        storyDescriptions.addAll(descriptionGenerator.createDescriptionFrom(performableTree));
276        addSuite(storyDescriptions, "AfterStories");
277
278        return storyDescriptions;
279    }
280
281    private int countStories() {
282        JUnitDescriptionGenerator descriptionGenerator = new JUnitDescriptionGenerator(getCandidateSteps(), getConfiguration());
283        return descriptionGenerator.getTestCases() + beforeAndAfterStorySteps();
284    }
285
286    private int beforeAndAfterStorySteps() {
287        return 2;
288    }
289
290    private PerformableTree createPerformableTree(List<CandidateSteps> candidateSteps, List<String> storyPaths) {
291        ExtendedEmbedder configuredEmbedder = this.getConfiguredEmbedder();
292        configuredEmbedder.useMetaFilters(getMetaFilters());
293        BatchFailures failures = new BatchFailures(configuredEmbedder.embedderControls().verboseFailures());
294        PerformableTree performableTree = configuredEmbedder.performableTree();
295        RunContext context = performableTree.newRunContext(getConfiguration(), candidateSteps,
296                configuredEmbedder.embedderMonitor(), configuredEmbedder.metaFilter(), failures);
297        performableTree.addStories(context, configuredEmbedder.storyManager().storiesOfPaths(storyPaths));
298        return performableTree;
299    }
300
301    private void addSuite(List<Description> storyDescriptions, String name) {
302        storyDescriptions.add(Description.createTestDescription(Object.class,
303                name));
304    }
305
306    private boolean metaFiltersAreDefined() {
307        String metaFilters = getMetafilterSetting();
308        return !StringUtils.isEmpty(metaFilters);
309    }
310
311    private String getMetafilterSetting() {
312        Optional<String> environmentMetafilters = getEnvironmentMetafilters();
313        Optional<String> annotatedMetafilters = getAnnotatedMetafilters(testClass);
314        Optional<String> thucAnnotatedMetafilters = getThucAnnotatedMetafilters(testClass);
315        return environmentMetafilters.orElse(annotatedMetafilters.orElse(thucAnnotatedMetafilters.orElse("")));
316    }
317
318    private Optional<String> getEnvironmentMetafilters() {
319        return Optional.ofNullable(environmentVariables.getProperty(SerenityJBehaveSystemProperties.METAFILTER.getName()));
320    }
321
322    /**
323     * When Metafilter in thucydides package is removed, this method and callers will be removed
324     *
325     * @param testClass
326     * @return
327     */
328    @Deprecated
329    private Optional<String> getThucAnnotatedMetafilters(Class<? extends ConfigurableEmbedder> testClass) {
330        return (testClass.getAnnotation(net.thucydides.jbehave.annotations.Metafilter.class) != null) ?
331                Optional.of(testClass.getAnnotation(net.thucydides.jbehave.annotations.Metafilter.class).value()) : Optional.empty();
332    }
333
334    private Optional<String> getAnnotatedMetafilters(Class<? extends ConfigurableEmbedder> testClass) {
335        return (testClass.getAnnotation(Metafilter.class) != null) ?
336                Optional.of(testClass.getAnnotation(Metafilter.class).value()) : Optional.empty();
337    }
338
339    protected boolean getIgnoreFailuresInStories() {
340        return environmentVariables.getPropertyAsBoolean(SerenityJBehaveSystemProperties.IGNORE_FAILURES_IN_STORIES.getName(), false);
341    }
342
343    protected int getStoryTimeoutInSecs() {
344        return environmentVariables.getPropertyAsInteger(SerenityJBehaveSystemProperties.STORY_TIMEOUT_IN_SECS.getName(),
345                (int) getConfiguredEmbedder().embedderControls().storyTimeoutInSecs());
346    }
347
348    protected int getThreadCount() {
349        return environmentVariables.getPropertyAsInteger(SerenityJBehaveSystemProperties.JBEHAVE_THREADS.getName(), 1);
350    }
351
352    protected String getStoryTimeout() {
353        return environmentVariables.getProperty(
354                SerenityJBehaveSystemProperties.STORY_TIMEOUT.getName(),
355                getConfiguredEmbedder().embedderControls().storyTimeouts());
356    }
357
358    protected List<String> getMetaFilters() {
359        String metaFilters = getMetafilterSetting();
360        return Lists.newArrayList(Splitter.on(Pattern.compile(",")).trimResults().omitEmptyStrings().split(metaFilters));
361    }
362
363    protected boolean getIgnoreFailuresInView() {
364        return environmentVariables.getPropertyAsBoolean(SerenityJBehaveSystemProperties.IGNORE_FAILURES_IN_VIEW.getName(), true);
365    }
366
367    public boolean isRunningInMaven() {
368        return Stream.of(new Exception().getStackTrace()).anyMatch(elt -> elt.getClassName().contains("maven"));
369    }
370}
371
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 getThreadCount code on LambdaTest Cloud Grid

Execute automation tests with getThreadCount 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)