How to use getStoryPath method of net.serenitybdd.jbehave.SerenityStories class

Best Serenity jBehave code snippet using net.serenitybdd.jbehave.SerenityStories.getStoryPath

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;
2
3import net.serenitybdd.jbehave.samples.levels.first.SerenityStorySampleForFistLevel;
4import net.serenitybdd.jbehave.samples.levels.second.SerenityStorySampleForSecondLevel;
5import net.thucydides.core.model.TestOutcome;
6import net.thucydides.core.model.TestResult;
7import net.thucydides.core.reports.TestOutcomes;
8import net.thucydides.core.util.EnvironmentVariables;
9import org.junit.Test;
10
11import java.util.List;
12import java.util.stream.Collectors;
13
14import static org.hamcrest.MatcherAssert.assertThat;
15import static org.hamcrest.Matchers.*;
16
17public class WhenRunningASelectionOfJBehaveStories extends AbstractJBehaveStory {
18
19    final static class AStorySample extends SerenityStories {
20
21        public AStorySample() {
22            super();
23        }
24
25        protected AStorySample(String storyName) {
26            findStoriesCalled(storyName);
27        }
28    }
29
30    @Test
31    public void all_stories_on_the_classpath_should_be_run_by_default() {
32
33        // Given
34        SerenityStories first = new SerenityStorySampleForFistLevel();
35        SerenityStories second = new SerenityStorySampleForSecondLevel();
36        // Then
37        assertThat(first.getRootPackage(), equalTo(second.getRootPackage()));
38        assertThat(first.getStoryPath(), equalTo(second.getStoryPath()));
39        assertThat(first.stepsFactory().createCandidateSteps().containsAll(second.stepsFactory().createCandidateSteps()), is(true));
40        assertThat(first.getStoryPath(), is("**/*.story"));
41    }
42
43    final static class StoriesInTheSubsetFolderSample extends SerenityStories {
44        StoriesInTheSubsetFolderSample(EnvironmentVariables environmentVariables) {
45            super(environmentVariables);
46            findStoriesIn("stories/subset");
47        }
48    }
49
50    @Test
51    public void a_subset_of_the_stories_can_be_run_individually() {
52
53        // Given
54        SerenityStories stories = new StoriesInTheSubsetFolderSample(environmentVariables);
55
56        // When
57        run(stories);
58
59        // Then
60
61        List<TestOutcome> outcomes = loadTestOutcomes();
62        assertThat(outcomes.size(), is(5));
63    }
64
65    @Test
66    public void stories_with_a_matching_name_can_be_run() {
67
68        // Given
69        SerenityStories stories = newStory("*PassingBehavior.story");
70
71        // When
72        run(stories);
73
74        // Then
75        List<TestOutcome> outcomes = loadTestOutcomes();
76        assertThat(outcomes.size(), is(6));
77    }
78
79    @Test
80    public void environment_specific_stories_should_be_executed_if_the_corresponding_environment_variable_is_set() {
81
82        // Given
83        systemConfiguration.getEnvironmentVariables().setProperty("metafilter", "+environment uat");
84        SerenityStories uatStory = new ASampleBehaviorForUatOnly(systemConfiguration);
85//        uatStory.setSystemConfiguration(systemConfiguration);
86        uatStory.setEnvironmentVariables(environmentVariables);
87
88        // When
89        run(uatStory);
90
91        // Then
92        List<TestOutcome> outcomes = loadTestOutcomes();
93        assertThat(outcomes.size(), is(1));
94        assertThat(outcomes.get(0).getResult(), is(TestResult.SUCCESS));
95    }
96
97
98    @Test
99    public void should_be_possible_to_define_multiple_metafilters() {
100
101        // Given
102        systemConfiguration.getEnvironmentVariables().setProperty("metafilter", "+environment uat, +speed fast");
103        SerenityStories allStories = new SerenityStories(systemConfiguration);
104        allStories.setSystemConfiguration(systemConfiguration);
105        allStories.setEnvironmentVariables(environmentVariables);
106
107        // When
108        run(allStories);
109
110        // Then
111        List<TestOutcome> outcomes = loadTestOutcomes();
112        assertThat(excludeSkippedAndIgnored(outcomes).size(), is(4));
113    }
114
115    @Test
116    public void should_be_possible_to_define_metafilters_in_annotations() {
117
118        // Given
119        SerenityStories allStories = new WithAnAnnotatedMetafilter();
120        allStories.setSystemConfiguration(systemConfiguration);
121        allStories.setEnvironmentVariables(environmentVariables);
122
123        // When
124        run(allStories);
125
126        // Then
127        List<TestOutcome> outcomes = loadTestOutcomes();
128        assertThat(excludeSkippedAndIgnored(outcomes).size(), is(2));
129    }
130
131    @Test
132    public void system_property_metafilters_should_override_annotations() {
133
134        // Given
135        systemConfiguration.getEnvironmentVariables().setProperty("metafilter", "+environment uat, +speed fast");
136        SerenityStories allStories = new WithAnAnnotatedMetafilter();
137        allStories.setSystemConfiguration(systemConfiguration);
138        allStories.setEnvironmentVariables(environmentVariables);
139
140        // When
141        run(allStories);
142
143        // Then
144        List<TestOutcome> outcomes = loadTestOutcomes();
145        assertThat(excludeSkippedAndIgnored(outcomes).size(), is(4));
146    }
147
148    @Test
149    public void should_be_possible_to_define_groovy_metafilters() {
150
151        // Given
152        systemConfiguration.getEnvironmentVariables().setProperty("webdriver.driver", "htmlunit");
153        systemConfiguration.getEnvironmentVariables().setProperty("metafilter", "groovy:('a'=='b')");
154        SerenityStories allStories = new SerenityStories(systemConfiguration);
155        allStories.setSystemConfiguration(systemConfiguration);
156        allStories.setEnvironmentVariables(environmentVariables);
157
158        // When
159        run(allStories);
160
161        // Then
162        List<TestOutcome> outcomes = loadTestOutcomes();
163        assertThat(excludeSkippedAndIgnored(outcomes).size(), is(0));
164    }
165
166    @Test
167    public void environment_specific_stories_should_not_be_executed_if_a_filter_excludes_it() {
168
169        systemConfiguration.getEnvironmentVariables().setProperty("metafilter", "-environment uat");
170
171        // Given
172        SerenityStories uatStory = new ASampleBehaviorForUatOnly(systemConfiguration);
173
174        // When
175        run(uatStory);
176
177        // Then
178        List<TestOutcome> outcomes = loadTestOutcomes();
179        assertThat(outcomes.size(), is(0));
180    }
181
182    final class AnotherStorySample extends SerenityStories {
183
184        public AnotherStorySample() {
185            super(environmentVariables);
186            findStoriesCalled("stories/samples/*Behavior.story");
187        }
188    }
189
190    @Test
191    public void test_should_run_stories_in_a_specified_place() {
192
193        // Given
194        SerenityStories story = new AnotherStorySample();
195
196        // When
197        run(story);
198
199        // Then
200        List<TestOutcome> outcomes = loadTestOutcomes();
201        assertThat(outcomes.size(), is(3));
202    }
203
204    private List<? extends TestOutcome> excludeSkippedAndIgnored(final List<TestOutcome> source) {
205        return TestOutcomes.of(source.stream()
206                .filter(t -> {
207                    TestResult result = t.getResult();
208                    return TestResult.SKIPPED != result && TestResult.IGNORED != result;
209                })
210                .collect(Collectors.toList())).getOutcomes();
211    }
212
213}
214
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.ImmutableList;
6import com.google.common.collect.Lists;
7import net.serenitybdd.core.Serenity;
8import net.serenitybdd.core.di.WebDriverInjectors;
9import net.serenitybdd.jbehave.runners.SerenityReportingRunner;
10import net.thucydides.core.ThucydidesSystemProperty;
11import net.thucydides.core.guice.Injectors;
12import net.thucydides.core.util.EnvironmentVariables;
13import net.thucydides.core.webdriver.DriverConfiguration;
14import org.codehaus.plexus.util.StringUtils;
15import org.jbehave.core.configuration.Configuration;
16import org.jbehave.core.io.StoryFinder;
17import org.jbehave.core.junit.JUnitStories;
18import org.jbehave.core.reporters.Format;
19import org.jbehave.core.steps.InjectableStepsFactory;
20import org.junit.runner.RunWith;
21
22import java.io.IOException;
23import java.net.MalformedURLException;
24import java.net.URL;
25import java.util.ArrayList;
26import java.util.Arrays;
27import java.util.Collections;
28import java.util.HashSet;
29import java.util.List;
30import java.util.Set;
31
32import static org.jbehave.core.reporters.Format.*;
33
34/**
35 * A JUnit-runnable test case designed to run a set of SerenityWebdriverIntegration-enabled JBehave stories in a given package.
36 * By default, it will look for *.story files on the classpath, and steps in or underneath the current package.
37 * You can redefine these constraints as follows:
38 */
39@RunWith(SerenityReportingRunner.class)
40public class SerenityStories extends JUnitStories {
41
42    public static final String DEFAULT_STORY_NAME = "**/*.story";
43    public static final List<String> DEFAULT_GIVEN_STORY_PREFIX
44            = ImmutableList.of("Given", "Precondition", "preconditions");
45
46    private net.thucydides.core.webdriver.DriverConfiguration systemConfiguration;
47    private EnvironmentVariables environmentVariables;
48
49    private String storyFolder = "";
50    private String storyNamePattern = DEFAULT_STORY_NAME;
51
52    private Configuration configuration;
53    private List<Format> formats = Arrays.asList(CONSOLE, HTML, XML);
54
55    public SerenityStories() {
56        Serenity.throwExceptionsImmediately();
57    }
58
59    protected SerenityStories(EnvironmentVariables environmentVariables) {
60        this.environmentVariables = environmentVariables.copy();
61    }
62
63    protected SerenityStories(net.thucydides.core.webdriver.DriverConfiguration configuration) {
64        this.setSystemConfiguration(configuration);
65    }
66
67    public EnvironmentVariables getEnvironmentVariables() {
68        if (environmentVariables == null) {
69            environmentVariables = Injectors.getInjector().getProvider(EnvironmentVariables.class).get().copy();
70        }
71        return environmentVariables;
72    }
73
74    @Override
75    public Configuration configuration() {
76        if (configuration == null) {
77            net.thucydides.core.webdriver.DriverConfiguration<DriverConfiguration> thucydidesConfiguration = getSystemConfiguration();
78            if (environmentVariables != null) {
79                thucydidesConfiguration = thucydidesConfiguration.withEnvironmentVariables(environmentVariables);
80            }
81            configuration = SerenityJBehave.defaultConfiguration(thucydidesConfiguration, formats, this);
82        }
83        return configuration;
84    }
85
86    @Override
87    public InjectableStepsFactory stepsFactory() {
88        return SerenityStepFactory.withStepsFromPackage(getRootPackage(), configuration()).andClassLoader(getClassLoader());
89    }
90
91    /**
92     * The class loader used to obtain the JBehave and Step implementation classes.
93     * You normally don't need to worry about this, but you may need to override it if your application
94     * is doing funny business with the class loaders.
95     */
96    public ClassLoader getClassLoader() {
97        return Thread.currentThread().getContextClassLoader();
98    }
99
100    @Override
101    public List<String> storyPaths() {
102        Set<String> storyPaths = new HashSet<>();
103
104        List<String> pathExpressions = getStoryPathExpressions();
105        StoryFinder storyFinder = new StoryFinder();
106        for (String pathExpression : pathExpressions) {
107            if (absolutePath(pathExpression)) {
108                storyPaths.add(pathExpression);
109            }
110            for (URL classpathRootUrl : allClasspathRoots()) {
111                storyPaths.addAll(storyFinder.findPaths(classpathRootUrl, pathExpression, ""));
112            }
113            storyPaths = removeDuplicatesFrom(storyPaths);
114            storyPaths = pruneGivenStoriesFrom(storyPaths);
115        }
116        return sorted(storyPaths);
117    }
118
119    private List<String> sorted(Set<String> storyPaths) {
120        List<String> sortedStories = Lists.newArrayList(storyPaths);
121        Collections.sort(sortedStories);
122        return sortedStories;
123    }
124
125    private Set<String> removeDuplicatesFrom(Set<String> storyPaths) {
126        Set<String> trimmedPaths = new HashSet<>();
127        for(String storyPath : storyPaths) {
128            if (!thereExistsALongerVersionOf(storyPath, storyPaths)) {
129                trimmedPaths.add(storyPath);
130            }
131        }
132        return trimmedPaths;
133    }
134
135    private boolean thereExistsALongerVersionOf(String storyPath, Set<String> storyPaths) {
136        for(String existingPath : storyPaths) {
137            if ((existingPath.endsWith("/" + storyPath)) || (existingPath.endsWith("\\" + storyPath))) {
138                return true;
139            }
140        }
141        return false;
142    }
143
144    private Set<String> pruneGivenStoriesFrom(Set<String> storyPaths) {
145        List<String> filteredPaths = Lists.newArrayList(storyPaths);
146        for (String skippedPrecondition : skippedPreconditions()) {
147            filteredPaths = removeFrom(filteredPaths)
148                    .pathsNotStartingWith(skippedPrecondition)
149                    .and().pathsNotStartingWith("/" + skippedPrecondition)
150                    .filter();
151        }
152        return new HashSet<>(filteredPaths);
153    }
154
155    class FilterBuilder {
156
157        private final List<String> paths;
158
159        public FilterBuilder(List<String> paths) {
160            this.paths = paths;
161        }
162
163        public FilterBuilder pathsNotStartingWith(String skippedPrecondition) {
164            List<String> filteredPaths = new ArrayList<>();
165            for (String path : paths) {
166                if (!startsWith(skippedPrecondition, path)) {
167                    filteredPaths.add(path);
168                }
169            }
170            return new FilterBuilder(filteredPaths);
171        }
172
173        public FilterBuilder and() {
174            return this;
175        }
176
177        public List<String> filter() {
178            return ImmutableList.copyOf(paths);
179        }
180
181        private boolean startsWith(String skippedPrecondition, String path) {
182            return path.toLowerCase().startsWith(skippedPrecondition.toLowerCase());
183        }
184    }
185
186    private FilterBuilder removeFrom(List<String> filteredPaths) {
187        return new FilterBuilder(filteredPaths);
188    }
189
190    private List<String> skippedPreconditions() {
191        return DEFAULT_GIVEN_STORY_PREFIX;
192    }
193
194    private boolean absolutePath(String pathExpression) {
195        return (!pathExpression.contains("*"));
196    }
197
198    private Set<URL> allClasspathRoots() {
199        try {
200            Set<URL> baseRoots = new HashSet<>(Collections.list(getClassLoader().getResources(".")));
201            return addGradleResourceRootsTo(baseRoots);
202        } catch (IOException e) {
203            throw new IllegalArgumentException("Could not load the classpath roots when looking for story files", e);
204        }
205    }
206
207    private Set<URL> addGradleResourceRootsTo(Set<URL> baseRoots) throws MalformedURLException {
208        Set<URL> rootsWithGradleResources = new HashSet<>(baseRoots);
209        for (URL baseUrl : baseRoots) {
210            String gradleResourceUrl = baseUrl.toString().replace("/build/classes/", "/build/resources/");
211            rootsWithGradleResources.add(new URL(gradleResourceUrl));
212        }
213        return rootsWithGradleResources;
214    }
215
216    /**
217     * The root package on the classpath containing the JBehave stories to be run.
218     */
219    protected String getRootPackage() {
220        return RootPackage.forPackage(getClass().getPackage());
221    }
222
223
224    protected List<String> getStoryPathExpressions() {
225        return Lists.newArrayList(Splitter.on(';').trimResults().omitEmptyStrings().split(getStoryPath()));
226    }
227
228    /**
229     * The root package on the classpath containing the JBehave stories to be run.
230     */
231    protected String getStoryPath() {
232        return (StringUtils.isEmpty(storyFolder)) ? storyNamePattern : storyFolder + "/" + storyNamePattern;
233    }
234
235    /**
236     * Define the folder on the class path where the stories should be found
237     */
238    public void findStoriesIn(String storyFolder) {
239        this.storyFolder = storyFolder;
240    }
241
242    public void useFormats(Format... formats) {
243        this.formats = Arrays.asList(formats);
244    }
245
246    public void findStoriesCalled(String storyNames) {
247        Set<String> storyPathElements = new StoryPathFinder(getEnvironmentVariables(), storyNames).findAllElements();
248        storyNamePattern = Joiner.on(";").join(storyPathElements);
249    }
250
251    private String storyFilter;
252
253    public void matchStories(String storyFilter) {
254        this.storyFilter = storyFilter;
255    }
256
257    public String getStoryFilter() {
258        return storyFilter;
259    }
260
261
262    /**
263     * Use this to override the default ThucydidesWebdriverIntegration configuration - for testing purposes only.
264     */
265    protected void setSystemConfiguration(net.thucydides.core.webdriver.DriverConfiguration systemConfiguration) {
266        this.systemConfiguration = systemConfiguration;
267    }
268
269    protected void setEnvironmentVariables(EnvironmentVariables environmentVariables) {
270        this.environmentVariables = environmentVariables;
271    }
272
273    public net.thucydides.core.webdriver.DriverConfiguration getSystemConfiguration() {
274        if (systemConfiguration == null) {
275            systemConfiguration = WebDriverInjectors.getInjector().getInstance(net.thucydides.core.webdriver.DriverConfiguration.class);
276        }
277        return systemConfiguration;
278    }
279
280    protected void useDriver(String driver) {
281        getSystemConfiguration().setIfUndefined(ThucydidesSystemProperty.DRIVER.getPropertyName(), driver);
282    }
283
284    protected void useUniqueSession() {
285        getSystemConfiguration().setIfUndefined(ThucydidesSystemProperty.THUCYDIDES_USE_UNIQUE_BROWSER.getPropertyName(), "true");
286    }
287
288    public ThucydidesConfigurationBuilder runSerenity() {
289        return new ThucydidesConfigurationBuilder(this);
290    }
291
292    public class ThucydidesConfigurationBuilder {
293        private final SerenityStories serenityStories;
294
295        public ThucydidesConfigurationBuilder(SerenityStories serenityStories) {
296            this.serenityStories = serenityStories;
297        }
298
299        public ThucydidesConfigurationBuilder withDriver(String driver) {
300            useDriver(driver);
301            return this;
302        }
303
304        public ThucydidesPropertySetter withProperty(ThucydidesSystemProperty property) {
305            return new ThucydidesPropertySetter(serenityStories, property);
306        }
307
308        public ThucydidesPropertySetter withProperty(String property) {
309            return new ThucydidesPropertySetter(serenityStories, property);
310        }
311
312        public ThucydidesConfigurationBuilder inASingleSession() {
313            useUniqueSession();
314            return this;
315        }
316    }
317
318    public class ThucydidesPropertySetter {
319        private final SerenityStories serenityStories;
320        private final String propertyToSet;
321
322        public ThucydidesPropertySetter(SerenityStories serenityStories,
323                                        ThucydidesSystemProperty propertyToSet) {
324            this.serenityStories = serenityStories;
325            this.propertyToSet = propertyToSet.getPropertyName();
326        }
327
328        public ThucydidesPropertySetter(SerenityStories serenityStories,
329                                        String propertyToSet) {
330            this.serenityStories = serenityStories;
331            this.propertyToSet = propertyToSet;
332        }
333
334        public void setTo(boolean value) {
335            serenityStories.getSystemConfiguration().setIfUndefined(propertyToSet,
336                    Boolean.toString(value));
337        }
338
339        public void setTo(String value) {
340            serenityStories.getSystemConfiguration().setIfUndefined(propertyToSet, value);
341        }
342
343        public void setTo(Integer value) {
344            serenityStories.getSystemConfiguration().setIfUndefined(propertyToSet,
345                    Integer.toString(value));
346        }
347    }
348}
349
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 getStoryPath code on LambdaTest Cloud Grid

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