Best Serenity jBehave code snippet using net.serenitybdd.jbehave.SerenityReporter.clearListeners
Source:SerenityReporter.java
...57 baseStepListeners = new ArrayList<>();58 givenStoryMonitor = new GivenStoryMonitor();59 this.environmentVariables = Injectors.getInjector().getInstance(EnvironmentVariables.class);60 }61 protected void clearListeners() {62 serenityListenersThreadLocal.remove();63 reportServiceThreadLocal.remove();64 givenStoryMonitor.clear();65 }66 protected SerenityListeners getSerenityListeners() {67 if (serenityListenersThreadLocal.get() == null) {68 SerenityListeners listeners = SerenityReports.setupListeners(systemConfiguration);69 serenityListenersThreadLocal.set(listeners);70 synchronized (baseStepListeners) {71 baseStepListeners.add(listeners.getBaseStepListener());72 }73 }74 return serenityListenersThreadLocal.get();75 }76 protected ReportService getReportService() {77 return SerenityReports.getReportService(systemConfiguration);78 }79 @Override80 public void storyNotAllowed(Story story, String filter) {81 logger.debug("not allowed story {}", story.getName());82 }83 @Override84 public void storyCancelled(Story story, StoryDuration storyDuration) {85 logger.debug("cancelled story {}", story.getName());86 }87 private Stack<Story> storyStack = new Stack<>();88 private Stack<Scenario> activeScenarios = new Stack<>();89 private List<String> givenStories = new ArrayList<>();90 private Story currentStory() {91 return storyStack.peek();92 }93 private void currentStoryIs(Story story) {94 storyStack.push(story);95 }96 private Map<String, String> storyMetadata;97 private void clearActiveScenariosData() {98 activeScenarios.clear();99 }100 @Override101 public void beforeStory(Story story, boolean givenStory) {102 logger.debug("before story {}", story.getName());103 prepareSerenityListeners();104 currentStoryIs(story);105 noteAnyGivenStoriesFor(story);106 storyMetadata = getMetadataFrom(story.getMeta());107 if (!isFixture(story) && !givenStory) {108 clearActiveScenariosData();109 configureDriver(story);110 SerenityStepFactory.resetContext();111 if (!isAStoryLevelGiven(story)) {112 startTestSuiteForStory(story);113 if (givenStoriesPresentFor(story)) {114 startTestForFirstScenarioIn(story);115 }116 }117 } else if (givenStory) {118 shouldNestScenarios(true);119 }120 registerStoryMeta(story.getMeta());121 }122 private void prepareSerenityListeners() {123 getSerenityListeners().withDriver(ThucydidesWebDriverSupport.getDriver());124 }125 private boolean nestScenarios = false;126 private boolean shouldNestScenarios() {127 return nestScenarios;128 }129 private void shouldNestScenarios(boolean nestScenarios) {130 this.nestScenarios = nestScenarios;131 }132 private void startTestForFirstScenarioIn(Story story) {133 startScenarioCalled(story.getScenarios().get(0), story);134 StepEventBus.getEventBus().stepStarted(ExecutedStepDescription.withTitle("Preconditions"));135 shouldNestScenarios(true);136 }137 @Override138 public void beforeScenario(Scenario scenario) {139 String scenarioTitle = scenario.getTitle();140 logger.debug("before scenario started {}", scenarioTitle);141 if (shouldResetStepsBeforeEachScenario()) {142 SerenityStepFactory.resetContext();143 }144 resetDriverIfNecessary();145 if (isCurrentScenario(scenarioTitle)) {146 return;147 }148 if (shouldNestScenarios()) {149 startNewStep(scenarioTitle);150 } else {151 startScenarioCalled(scenario, currentStory());152 }153 Meta meta = scenario.getMeta();154 logger.debug("scenario:\"{}\" registering metadata for {}",155 StringUtils.isEmpty(scenarioTitle) ? " don't know name " : scenarioTitle, meta);156 registerIssues(meta);157 registerFeaturesAndEpics(meta);158 registerTags(meta);159 registerMetadata(meta);160 registerScenarioMeta(meta);161 markAsSkippedOrPendingIfAnnotatedAsSuchIn(scenarioTags(scenario));162 }163 private List<String> scenarioTags(Scenario scenario) {164 List<String> scenarioTags = new ArrayList<>(scenario.getMeta().getPropertyNames());165 scenarioTags.addAll(currentStory().getMeta().getPropertyNames());166 return scenarioTags;167 }168 private void resetDriverIfNecessary() {169 if (Serenity.currentDriverIsDisabled()) {170 Serenity.getWebdriverManager().resetDriver();171 }172 }173 private boolean isCurrentScenario(String scenarioTitle) {174 return !activeScenarios.empty() && scenarioTitle.equals(activeScenarios.peek().getTitle());175 }176 private Scenario currentScenario() {177 return activeScenarios.peek();178 }179 private void startNewStep(String scenarioTitle) {180 if (givenStoryMonitor.isInGivenStory() && StepEventBus.getEventBus().areStepsRunning()) {181 StepEventBus.getEventBus().updateCurrentStepTitleAsPrecondition(scenarioTitle);182 } else {183 StepEventBus.getEventBus().stepStarted(ExecutedStepDescription.withTitle(scenarioTitle),184 givenStoryMonitor.isInGivenStory());185 }186 }187 private boolean givenStoriesPresentFor(Story story) {188 return !story.getGivenStories().getStories().isEmpty();189 }190 private void startTestSuiteForStory(Story story) {191 String storyName = removeSuffixFrom(story.getName());192 String storyTitle = (isNotEmpty(story.getDescription().asString())) ? story.getDescription().asString() : NameConverter.humanize(storyName);193 net.thucydides.core.model.Story userStory194 = net.thucydides.core.model.Story.withIdAndPath(storyName, storyTitle, stripStoriesFolderFrom(story.getPath()))195 .withNarrative(getNarrativeFrom(story));196 StepEventBus.getEventBus().testSuiteStarted(userStory);197 registerTags(story);198 }199 private String stripStoriesFolderFrom(String path) {200 String storyDirectory = environmentVariables.getProperty(STORY_DIRECTORY,"stories");201 return (path.toLowerCase().startsWith(storyDirectory + "/")) ? path.substring(storyDirectory.length() + 1) : path;202 }203 private String getNarrativeFrom(Story story) {204 return (!story.getNarrative().isEmpty()) ?205 story.getNarrative().asString(new Keywords()).trim() : "";206 }207 private void noteAnyGivenStoriesFor(Story story) {208 for (GivenStory given : story.getGivenStories().getStories()) {209 String givenStoryName = new File(given.getPath()).getName();210 givenStories.add(givenStoryName);211 }212 }213 private boolean isAStoryLevelGiven(Story story) {214 for (String givenStoryName : givenStories) {215 if (hasSameName(story, givenStoryName)) {216 return true;217 }218 }219 return false;220 }221 private void givenStoryDone(Story story) {222 givenStories.remove(story.getName());223 }224 private boolean hasSameName(Story story, String givenStoryName) {225 return story.getName().equalsIgnoreCase(givenStoryName);226 }227 private void configureDriver(Story story) {228 StepEventBus.getEventBus().setUniqueSession(systemConfiguration.shouldUseAUniqueBrowser());229 String requestedDriver = getRequestedDriver(story.getMeta());230 // An annotated driver that ends with "!" overrides the command-line configured driver231 if (isEmphatic(requestedDriver)) {232 ThucydidesWebDriverSupport.useDefaultDriver(unemphasised(requestedDriver));233 } else if (StringUtils.isNotEmpty(requestedDriver) && (!driverIsProvidedInTheEnvironmentVariables())){234 ThucydidesWebDriverSupport.useDefaultDriver(requestedDriver);235 }236 }237 private String unemphasised(String requestedDriver) {238 return requestedDriver.replace("!","");239 }240 private boolean isEmphatic(String requestedDriver) {241 return requestedDriver != null && requestedDriver.endsWith("!");242 }243 private boolean driverIsProvidedInTheEnvironmentVariables() {244 return (isNotEmpty(systemConfiguration.getEnvironmentVariables().getProperty(WEBDRIVER_DRIVER)));245 }246 private void registerTags(Story story) {247 registerStoryIssues(story.getMeta());248 registerStoryFeaturesAndEpics(story.getMeta());249 registerStoryTags(story.getMeta());250 registerStoryMeta(story.getMeta());251 }252 private boolean isFixture(Story story) {253 return (story.getName().equals(BEFORE_STORIES) || story.getName().equals(AFTER_STORIES));254 }255 private String getRequestedDriver(Meta metaData) {256 if (metaData == null) {257 return null;258 }259 if (StringUtils.isNotEmpty(metaData.getProperty("driver"))) {260 return metaData.getProperty("driver");261 }262 if (systemConfiguration.getDriverType() != null) {263 return systemConfiguration.getDriverType().toString();264 }265 return null;266 }267 private List<String> getIssueOrIssuesPropertyValues(Meta metaData) {268 return getTagPropertyValues(metaData, "issue");269 }270 private List<TestTag> getFeatureOrFeaturesPropertyValues(Meta metaData) {271 List<String> features = getTagPropertyValues(metaData, "feature");272 return features.stream().map(273 featureName -> TestTag.withName(featureName).andType("feature")274 ).collect(Collectors.toList());275 }276 private List<TestTag> getEpicOrEpicsPropertyValues(Meta metaData) {277 List<String> epics = getTagPropertyValues(metaData, "epic");278 return epics.stream().map(279 epicName -> TestTag.withName(epicName).andType("epic")280 ).collect(Collectors.toList());281 }282 private List<TestTag> getTagOrTagsPropertyValues(Meta metaData) {283 List<String> tags = getTagPropertyValues(metaData, "tag");284 return tags.stream()285 .map( this::toTag )286 .collect(Collectors.toList());287 }288 public TestTag toTag(String tag) {289 List<String> tagParts = Lists.newArrayList(Splitter.on(":").trimResults().split(tag));290 if (tagParts.size() == 2) {291 return TestTag.withName(tagParts.get(1)).andType(tagParts.get(0));292 } else {293 return TestTag.withName("true").andType(tagParts.get(0));294 }295 }296 private List<String> getTagPropertyValues(Meta metaData, String tagType) {297 if (metaData == null) {298 return new ArrayList<>();299 }300 String singularTag = metaData.getProperty(tagType);301 String pluralTagType = Inflector.getInstance().pluralize(tagType);302 String multipleTags = metaData.getProperty(pluralTagType);303 String allTags = Joiner.on(',').skipNulls().join(singularTag, multipleTags);304 return Lists.newArrayList(Splitter.on(',').omitEmptyStrings().trimResults().split(allTags));305 }306 private void registerIssues(Meta metaData) {307 List<String> issues = getIssueOrIssuesPropertyValues(metaData);308 if (!issues.isEmpty()) {309 StepEventBus.getEventBus().addIssuesToCurrentTest(issues);310 }311 }312 private void registerStoryIssues(Meta metaData) {313 List<String> issues = getIssueOrIssuesPropertyValues(metaData);314 if (!issues.isEmpty()) {315 StepEventBus.getEventBus().addIssuesToCurrentStory(issues);316 }317 }318 private void registerFeaturesAndEpics(Meta metaData) {319 List<TestTag> featuresAndEpics = featureAndEpicTags(metaData);320 if (!featuresAndEpics.isEmpty()) {321 StepEventBus.getEventBus().addTagsToCurrentTest(featuresAndEpics);322 }323 }324 private List<TestTag> featureAndEpicTags(Meta metaData) {325 List<TestTag> featuresAndEpics = new ArrayList<>();326 featuresAndEpics.addAll(getFeatureOrFeaturesPropertyValues(metaData));327 featuresAndEpics.addAll(getEpicOrEpicsPropertyValues(metaData));328 return featuresAndEpics;329 }330 private void registerStoryFeaturesAndEpics(Meta metaData) {331 List<TestTag> featuresAndEpics = featureAndEpicTags(metaData);332 if (!featuresAndEpics.isEmpty()) {333 StepEventBus.getEventBus().addTagsToCurrentStory(featuresAndEpics);334 }335 }336 private void registerTags(Meta metaData) {337 List<TestTag> tags = getTagOrTagsPropertyValues(metaData);338 if (!tags.isEmpty()) {339 StepEventBus.getEventBus().addTagsToCurrentTest(tags);340 }341 }342 private Map<String, String> getMetadataFrom(Meta metaData) {343 Map<String, String> metadataValues = new HashMap<>();344 if (metaData == null) {345 return metadataValues;346 }347 for (String propertyName : metaData.getPropertyNames()) {348 metadataValues.put(propertyName, metaData.getProperty(propertyName));349 }350 return metadataValues;351 }352 private void registerMetadata(Meta metaData) {353 Serenity.getCurrentSession().clearMetaData();354 Map<String, String> scenarioMetadata = getMetadataFrom(metaData);355 scenarioMetadata.putAll(storyMetadata);356 for (String key : scenarioMetadata.keySet()) {357 Serenity.getCurrentSession().addMetaData(key, scenarioMetadata.get(key));358 }359 }360 private void registerStoryTags(Meta metaData) {361 List<TestTag> tags = getTagOrTagsPropertyValues(metaData);362 if (!tags.isEmpty()) {363 StepEventBus.getEventBus().addTagsToCurrentStory(tags);364 }365 }366 private void registerStoryMeta(Meta metaData) {367 if (isPending(metaData)) {368 StepEventBus.getEventBus().suspendTest();369 } else if (isSkipped(metaData)) {370 StepEventBus.getEventBus().suspendTest();371 } else if (isIgnored(metaData)) {372 StepEventBus.getEventBus().suspendTest();373 } else if (isManual(metaData)) {374 StepEventBus.getEventBus().suspendTest();375 }376 }377 private boolean isStoryManual() {378 return isManual(currentStory().getMeta());379 }380 private void registerScenarioMeta(Meta metaData) {381 // Manual can be combined with the other tags to override the default result category382 if (isManual(metaData) || isStoryManual()) {383 StepEventBus.getEventBus().testIsManual();384 }385 }386 private String removeSuffixFrom(String name) {387 return (name.contains(".")) ? name.substring(0, name.indexOf(".")) : name;388 }389 @Override390 public void afterStory(boolean given) {391 logger.debug("afterStory {}", given);392 shouldNestScenarios(false);393 if (given) {394 givenStoryMonitor.exitingGivenStory();395 givenStoryDone(currentStory());396 } else {397 if (isAfterStory(currentStory())) {398 generateReports();399 } else if (!isFixture(currentStory()) && (!isAStoryLevelGiven(currentStory()))) {400 StepEventBus.getEventBus().testSuiteFinished();401 clearListeners();402 }403 }404 storyStack.pop();405 }406 private boolean isAfterStory(Story currentStory) {407 return (currentStory.getName().equals(AFTER_STORIES));408 }409 private synchronized void generateReports() {410 getReportService().generateReportsFor(getAllTestOutcomes());411 }412 public List<TestOutcome> getAllTestOutcomes() {413 return baseStepListeners.stream()414 .map(BaseStepListener::getTestOutcomes)415 .flatMap(Collection::stream)...
clearListeners
Using AI Code Generation
1package net.serenitybdd.jbehave;2import java.util.ArrayList;3import java.util.List;4import org.jbehave.core.reporters.StoryReporter;5public class SerenityReporter {6public SerenityReporter() {7}8public void clearListeners() {9}10public void addListeners(StoryReporter... listeners) {11}12public List<StoryReporter> getListeners() {13}14public void removeListeners(StoryReporter... listeners) {15}16}17package net.serenitybdd.jbehave;18import java.util.ArrayList;19import java.util.List;20import org.jbehave.core.reporters.StoryReporter;21public class SerenityReporter {22public SerenityReporter() {23}24public void clearListeners() {25}26public void addListeners(StoryReporter... listeners) {27}28public List<StoryReporter> getListeners() {29}30public void removeListeners(StoryReporter... listeners) {31}32}33package net.serenitybdd.jbehave;34import java.util.ArrayList;35import java.util.List;36import org.jbehave.core.reporters.StoryReporter;37public class SerenityReporter {38public SerenityReporter() {39}40public void clearListeners() {41}42public void addListeners(StoryReporter... listeners) {43}44public List<StoryReporter> getListeners() {45}46public void removeListeners(StoryReporter... listeners) {47}48}49package net.serenitybdd.jbehave;50import java
clearListeners
Using AI Code Generation
1public void clearListeners() {2 SerenityReporter.clearListeners();3}4public void clearListeners() {5 SerenityReporter.clearListeners();6}7java.lang.NoSuchMethodError: net.serenitybdd.jbehave.SerenityReporter.clearListeners()V8at net.serenitybdd.jbehave.SerenityReporter.clearListeners(SerenityReporter.java:0)9at net.serenitybdd.jbehave.SerenityReporter.afterStory(SerenityReporter.java:0)10at org.jbehave.core.reporters.DelegatingStoryReporter.afterStory(DelegatingStoryReporter.java:0)11at org.jbehave.core.reporters.DelegatingStoryReporter.afterStory(DelegatingStoryReporter.java:0)12at org.jbehave.core.reporters.DelegatingStoryReporter.afterStory(DelegatingStoryReporter.java:0)13at org.jbehave.core.reporters.DelegatingStoryReporter.afterStory(DelegatingStoryReporter.java:0)14at org.jbehave.core.reporters.DelegatingStoryReporter.afterStory(DelegatingStoryReporter.java:0)15at org.jbehave.core.embedder.PerformableTree$FineSoFar.run(PerformableTree.java:0)16at org.jbehave.core.embedder.PerformableTree$PerformableSteps.perform(PerformableTree.java:0)17at org.jbehave.core.embedder.PerformableTree$PerformableScenario.perform(PerformableTree.java:0)18at org.jbehave.core.embedder.PerformableTree$PerformableStory.perform(PerformableTree.java:0)19at org.jbehave.core.embedder.StoryManager$EnqueuedStory.call(StoryManager.java:0)20at org.jbehave.core.embedder.StoryManager$EnqueuedStory.call(StoryManager.java:0)21at java.util.concurrent.FutureTask.run(FutureTask.java:
clearListeners
Using AI Code Generation
1package net.serenitybdd.jbehave;2import net.thucydides.core.ThucydidesSystemProperty;3import net.thucydides.core.guice.Injectors;4import net.thucydides.core.model.TestOutcome;5import net.thucydides.core.reports.TestOutcomes;6import net.thucydides.core.steps.StepEventBus;7import net.thucydides.core.util.EnvironmentVariables;8import org.jbehave.core.configuration.Keywords;9import org.jbehave.core.configuration.MostUsefulConfiguration;10import org.jbehave.core.embedder.EmbedderControls;11import org.jbehave.core.embedder.PerformableTree;12import org.jbehave.core.embedder.StoryManager;13import org.jbehave.core.embedder.StoryTimeouts;14import org.jbehave.core.failures.BatchFailures;15import org.jbehave.core.failures.UUIDExceptionWrapper;16import org.jbehave.core.i18n.LocalizedKeywords;17import org.jbehave.core.io.*;18import org.jbehave.core.junit.JUnitStory;19import org.jbehave.core.model.*;20import org.jbehave.core.model.ExamplesTable.TableProperties;21import org.jbehave.core.parsers.*;22import org.jbehave.core.reporters.StoryReporter;23import org.jbehave.core.steps.*;24import org.jbehave.core.steps.StepCreator.PendingStepFound;25import org.jbehave.core.steps.StepCreator.StepExecutionType;26import org.slf4j.Logger;27import org.slf4j.LoggerFactory;28import java.io.File;29import java.io.IOException;30import java.util.*;31import java.util.concurrent.ConcurrentHashMap;32import static java.util.Arrays.asList;33import static org.apache.commons.lang3.StringUtils.isNotBlank;34public class SerenityReporter implements StoryReporter {35 private static final Logger LOGGER = LoggerFactory.getLogger(SerenityReporter.class);36 private final StoryReporter delegate;37 private final SerenityStepFactory stepFactory;38 private final Map<String, List<Step>> steps = new ConcurrentHashMap<String, List<Step>>();39 private final Map<String, List<Step>> beforeOrAfterSteps = new ConcurrentHashMap<String, List<Step>>();40 private final Map<String, List<Step>> beforeOrAfterStoriesSteps = new ConcurrentHashMap<String, List<Step>>();
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!