How to use performableTree method of net.serenitybdd.jbehave.embedders.ExtendedEmbedder class

Best Serenity jBehave code snippet using net.serenitybdd.jbehave.embedders.ExtendedEmbedder.performableTree

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;
2
3import net.serenitybdd.jbehave.embedders.monitors.CompositeEmbedderMonitor;
4import org.jbehave.core.configuration.Configuration;
5import org.jbehave.core.embedder.*;
6import org.jbehave.core.model.Story;
7import org.jbehave.core.steps.CandidateSteps;
8import org.jbehave.core.steps.InjectableStepsFactory;
9
10import java.io.File;
11import java.util.List;
12import java.util.Map;
13import java.util.Properties;
14import java.util.concurrent.ConcurrentHashMap;
15import java.util.concurrent.ExecutorService;
16
17/**
18 * User: YamStranger
19 * Date: 3/25/16
20 * Time: 12:02 AM
21 */
22public class ExtendedEmbedder extends Embedder {
23    final Embedder embedder;
24    final Map<String, Story> stories = new ConcurrentHashMap<>();
25
26    public ExtendedEmbedder(Embedder embedder) {
27        this.embedder = embedder;
28        this.embedder.useEmbedderMonitor(new CompositeEmbedderMonitor(
29            embedder.embedderMonitor()!=null?embedder.embedderMonitor():embedderMonitor));
30    }
31
32    public CompositeEmbedderMonitor getEmbedderMonitor() {
33        return (CompositeEmbedderMonitor) this.embedder.embedderMonitor();
34    }
35
36    public void registerStory(final String path, final Story story) {
37        this.stories.put(path, story);
38    }
39
40    public Story findStory(final String path){
41        return this.stories.get(path);
42    }
43
44    @Override
45    public void mapStoriesAsPaths(List<String> storyPaths) {
46        embedder.mapStoriesAsPaths(storyPaths);
47    }
48
49    @Override
50    public void runAsEmbeddables(List<String> classNames) {
51        embedder.runAsEmbeddables(classNames);
52    }
53
54    @Override
55    public void runStoriesWithAnnotatedEmbedderRunner(List<String> classNames) {
56        embedder.runStoriesWithAnnotatedEmbedderRunner(classNames);
57    }
58
59    @Override
60    public void runStoriesAsPaths(List<String> storyPaths) {
61        embedder.runStoriesAsPaths(storyPaths);
62    }
63
64    @Override
65    public void generateReportsView() {
66        embedder.generateReportsView();
67    }
68
69    @Override
70    public void generateReportsView(File outputDirectory, List<String> formats, Properties viewResources) {
71        embedder.generateReportsView(outputDirectory, formats, viewResources);
72    }
73
74    @Override
75    public void generateCrossReference() {
76        embedder.generateCrossReference();
77    }
78
79    @Override
80    public void reportStepdocs() {
81        embedder.reportStepdocs();
82    }
83
84    @Override
85    public void reportStepdocsAsEmbeddables(List<String> classNames) {
86        embedder.reportStepdocsAsEmbeddables(classNames);
87    }
88
89    @Override
90    public void reportStepdocs(Configuration configuration, List<CandidateSteps> candidateSteps) {
91        embedder.reportStepdocs(configuration, candidateSteps);
92    }
93
94    @Override
95    public void reportMatchingStepdocs(String stepAsString) {
96        embedder.reportMatchingStepdocs(stepAsString);
97    }
98
99    @Override
100    public void processSystemProperties() {
101        embedder.processSystemProperties();
102    }
103
104    @Override
105    public EmbedderClassLoader classLoader() {
106        return embedder.classLoader();
107    }
108
109    @Override
110    public Configuration configuration() {
111        return embedder.configuration();
112    }
113
114    @Override
115    public List<CandidateSteps> candidateSteps() {
116        return embedder.candidateSteps();
117    }
118
119    @Override
120    public InjectableStepsFactory stepsFactory() {
121        return embedder.stepsFactory();
122    }
123
124    @Override
125    public EmbedderControls embedderControls() {
126        return embedder.embedderControls();
127    }
128
129    @Override
130    public EmbedderMonitor embedderMonitor() {
131        return embedder.embedderMonitor();
132    }
133
134    @Override
135    public EmbedderFailureStrategy embedderFailureStrategy() {
136        return embedder.embedderFailureStrategy();
137    }
138
139    @Override
140    public boolean hasExecutorService() {
141        return embedder.hasExecutorService();
142    }
143
144    @Override
145    public ExecutorService executorService() {
146        return embedder.executorService();
147    }
148
149    @Override
150    public StoryManager storyManager() {
151        return embedder.storyManager();
152    }
153
154    @Override
155    public List<String> metaFilters() {
156        return embedder.metaFilters();
157    }
158
159    @Override
160    public Map<String, MetaFilter.MetaMatcher> metaMatchers() {
161        return embedder.metaMatchers();
162    }
163
164    @Override
165    public MetaFilter metaFilter() {
166        return embedder.metaFilter();
167    }
168
169    @Override
170    public PerformableTree performableTree() {
171        return embedder.performableTree();
172    }
173
174    @Override
175    public Properties systemProperties() {
176        return embedder.systemProperties();
177    }
178
179    @Override
180    public StoryTimeouts.TimeoutParser[] timeoutParsers() {
181        return embedder.timeoutParsers();
182    }
183
184    @Override
185    public void useClassLoader(EmbedderClassLoader classLoader) {
186        embedder.useClassLoader(classLoader);
187    }
188
189    @Override
190    public void useConfiguration(Configuration configuration) {
191        embedder.useConfiguration(configuration);
192    }
193
194    @Override
195    public void useCandidateSteps(List<CandidateSteps> candidateSteps) {
196        embedder.useCandidateSteps(candidateSteps);
197    }
198
199    @Override
200    public void useStepsFactory(InjectableStepsFactory stepsFactory) {
201        embedder.useStepsFactory(stepsFactory);
202    }
203
204    @Override
205    public void useEmbedderControls(EmbedderControls embedderControls) {
206        embedder.useEmbedderControls(embedderControls);
207    }
208
209    @Override
210    public void useEmbedderFailureStrategy(EmbedderFailureStrategy failureStategy) {
211        embedder.useEmbedderFailureStrategy(failureStategy);
212    }
213
214    @Override
215    public void useEmbedderMonitor(EmbedderMonitor embedderMonitor) {
216        embedder.useEmbedderMonitor(embedderMonitor);
217    }
218
219    @Override
220    public void useExecutorService(ExecutorService executorService) {
221        embedder.useExecutorService(executorService);
222    }
223
224    @Override
225    public void useMetaFilters(List<String> metaFilters) {
226        embedder.useMetaFilters(metaFilters);
227    }
228
229    @Override
230    public void useMetaMatchers(Map<String, MetaFilter.MetaMatcher> metaMatchers) {
231        embedder.useMetaMatchers(metaMatchers);
232    }
233
234    @Override
235    public void usePerformableTree(PerformableTree performableTree) {
236        embedder.usePerformableTree(performableTree);
237    }
238
239    @Override
240    public void useSystemProperties(Properties systemProperties) {
241        embedder.useSystemProperties(systemProperties);
242    }
243
244    @Override
245    public void useTimeoutParsers(StoryTimeouts.TimeoutParser... timeoutParsers) {
246        embedder.useTimeoutParsers(timeoutParsers);
247    }
248
249    @Override
250    public String toString() {
251        return embedder.toString();
252    }
253}
254
Full Screen
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
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)