How to use PathUtils class of net.serenitybdd.cucumber.util package

Best Serenity Cucumber code snippet using net.serenitybdd.cucumber.util.PathUtils

Source:SerenityReporter.java Github

copy

Full Screen

...13import net.serenitybdd.core.SerenityListeners;14import net.serenitybdd.core.SerenityReports;15import net.serenitybdd.cucumber.CucumberWithSerenity;16import net.serenitybdd.cucumber.formatting.ScenarioOutlineDescription;17import net.serenitybdd.cucumber.util.PathUtils;18import net.serenitybdd.cucumber.util.StepDefinitionAnnotationReader;19import net.thucydides.core.guice.Injectors;20import net.thucydides.core.model.DataTable;21import net.thucydides.core.model.TestStep;22import net.thucydides.core.model.*;23import net.thucydides.core.model.screenshots.StepDefinitionAnnotations;24import net.thucydides.core.model.stacktrace.RootCauseAnalyzer;25import net.thucydides.core.reports.ReportService;26import net.thucydides.core.steps.*;27import net.thucydides.core.util.Inflector;28import net.thucydides.core.webdriver.Configuration;29import net.thucydides.core.webdriver.ThucydidesWebDriverSupport;30import org.jetbrains.annotations.NotNull;31import org.junit.internal.AssumptionViolatedException;32import org.slf4j.Logger;33import org.slf4j.LoggerFactory;34import java.io.File;35import java.net.URI;36import java.util.*;37import java.util.stream.Collectors;38import static io.cucumber.core.plugin.TaggedScenario.*;39import static java.util.stream.Collectors.toList;40import static org.apache.commons.lang3.StringUtils.isEmpty;41import static org.apache.commons.lang3.StringUtils.isNotEmpty;42/**43 * Cucumber Formatter for Serenity.44 *45 * @author L.Carausu (liviu.carausu@gmail.com)46 */47public class SerenityReporter implements Plugin, ConcurrentEventListener {48 private static final String OPEN_PARAM_CHAR = "\uff5f";49 private static final String CLOSE_PARAM_CHAR = "\uff60";50 private static final String SCENARIO_OUTLINE_NOT_KNOWN_YET = "";51 private Configuration systemConfiguration;52 private final List<BaseStepListener> baseStepListeners;53 private final static String FEATURES_ROOT_PATH = "features";54 private FeatureFileLoader featureLoader = new FeatureFileLoader();55 private LineFilters lineFilters;56 private List<Tag> scenarioTags;57 private static final Logger LOGGER = LoggerFactory.getLogger(SerenityReporter.class);58 private ManualScenarioChecker manualScenarioDateChecker;59 private ThreadLocal<ScenarioContext> localContext = ThreadLocal.withInitial(ScenarioContext::new);60 private ScenarioContext getContext() {61 return localContext.get();62 }63 /**64 * Constructor automatically called by cucumber when class is specified as plugin65 * in @CucumberOptions.66 */67 public SerenityReporter() {68 this.systemConfiguration = Injectors.getInjector().getInstance(Configuration.class);69 this.manualScenarioDateChecker = new ManualScenarioChecker(systemConfiguration.getEnvironmentVariables());70 baseStepListeners = Collections.synchronizedList(new ArrayList<>());71 lineFilters = LineFilters.forCurrentContext();72 }73 public SerenityReporter(Configuration systemConfiguration) {74 this.systemConfiguration = systemConfiguration;75 this.manualScenarioDateChecker = new ManualScenarioChecker(systemConfiguration.getEnvironmentVariables());76 baseStepListeners = Collections.synchronizedList(new ArrayList<>());77 lineFilters = LineFilters.forCurrentContext();78 }79 private FeaturePathFormatter featurePathFormatter = new FeaturePathFormatter();80 private StepEventBus getStepEventBus(URI featurePath) {81 URI prefixedPath = featurePathFormatter.featurePathWithPrefixIfNecessary(featurePath);82 return StepEventBus.eventBusFor(prefixedPath);83 }84 private void setStepEventBus(URI featurePath) {85 URI prefixedPath = featurePathFormatter.featurePathWithPrefixIfNecessary(featurePath);86 StepEventBus.setCurrentBusToEventBusFor(prefixedPath);87 }88 private void initialiseListenersFor(URI featurePath) {89 if (getStepEventBus(featurePath).isBaseStepListenerRegistered()) {90 return;91 }92 SerenityListeners listeners = new SerenityListeners(getStepEventBus(featurePath), systemConfiguration);93 baseStepListeners.add(listeners.getBaseStepListener());94 }95 private EventHandler<TestSourceRead> testSourceReadHandler = this::handleTestSourceRead;96 private EventHandler<TestCaseStarted> caseStartedHandler = this::handleTestCaseStarted;97 private EventHandler<TestCaseFinished> caseFinishedHandler = this::handleTestCaseFinished;98 private EventHandler<TestStepStarted> stepStartedHandler = this::handleTestStepStarted;99 private EventHandler<TestStepFinished> stepFinishedHandler = this::handleTestStepFinished;100 private EventHandler<TestRunStarted> runStartedHandler = this::handleTestRunStarted;101 private EventHandler<TestRunFinished> runFinishedHandler = this::handleTestRunFinished;102 private EventHandler<WriteEvent> writeEventHandler = this::handleWrite;103 private void handleTestRunStarted(TestRunStarted event) {104 }105 @Override106 public void setEventPublisher(EventPublisher publisher) {107 publisher.registerHandlerFor(TestSourceRead.class, testSourceReadHandler);108 publisher.registerHandlerFor(TestRunStarted.class, runStartedHandler);109 publisher.registerHandlerFor(TestRunFinished.class, runFinishedHandler);110 publisher.registerHandlerFor(TestCaseStarted.class, caseStartedHandler);111 publisher.registerHandlerFor(TestCaseFinished.class, caseFinishedHandler);112 publisher.registerHandlerFor(TestStepStarted.class, stepStartedHandler);113 publisher.registerHandlerFor(TestStepFinished.class, stepFinishedHandler);114 publisher.registerHandlerFor(WriteEvent.class, writeEventHandler);115 }116 private void handleTestSourceRead(TestSourceRead event) {117 featureLoader.addTestSourceReadEvent(event);118 URI featurePath = event.getUri();119 featureFrom(featurePath).ifPresent(120 feature -> {121 getContext().setFeatureTags(feature.getTags());122 resetEventBusFor(featurePath);123 initialiseListenersFor(featurePath);124 configureDriver(feature, featurePath);125 Story userStory = userStoryFrom(feature, relativeUriFrom(event.getUri()));126 getStepEventBus(event.getUri()).testSuiteStarted(userStory);127 }128 );129 }130 private void resetEventBusFor(URI featurePath) {131 StepEventBus.clearEventBusFor(featurePath);132 }133 private String relativeUriFrom(URI fullPathUri) {134 String pathURIAsString = fullPathUri.toString();135 String featuresRoot = File.separatorChar + FEATURES_ROOT_PATH + File.separatorChar;136 if (pathURIAsString.contains(featuresRoot)) {137 return pathURIAsString.substring(pathURIAsString.lastIndexOf(featuresRoot) + FEATURES_ROOT_PATH.length() + 2);138 } else {139 return pathURIAsString;140 }141 }142 private Optional<Feature> featureFrom(URI featureFileUri) {143 LOGGER.info("Running feature from " + featureFileUri.toString());144 String featuresRoot = File.separatorChar + FEATURES_ROOT_PATH + File.separatorChar;145 if(!featureFileUri.toString().contains(featuresRoot)) {146 LOGGER.warn("Feature from " + featureFileUri + " is not under the 'features' directory. Requirements report will not be correctly generated!");147 }148 String defaultFeatureId = PathUtils.getAsFile(featureFileUri).getName().replace(".feature", "");149 String defaultFeatureName = Inflector.getInstance().humanize(defaultFeatureId);150 parseGherkinIn(featureFileUri);151 if (isEmpty(featureLoader.getFeatureName(featureFileUri))) {152 return Optional.empty();153 }154 Feature feature = featureLoader.getFeature(featureFileUri);155 if (feature.getName().isEmpty()) {156 feature = featureLoader.featureWithDefaultName(feature, defaultFeatureName);157 }158 return Optional.of(feature);159 }160 private void parseGherkinIn(URI featureFileUri) {161 try {162 featureLoader.getFeature(featureFileUri);...

Full Screen

Full Screen

Source:CucumberSerenityRunner.java Github

copy

Full Screen

...25import net.serenitybdd.cucumber.suiteslicing.CucumberSuiteSlicer;26import net.serenitybdd.cucumber.suiteslicing.ScenarioFilter;27import net.serenitybdd.cucumber.suiteslicing.TestStatistics;28import net.serenitybdd.cucumber.suiteslicing.WeightedCucumberScenarios;29import net.serenitybdd.cucumber.util.PathUtils;30import net.serenitybdd.cucumber.util.Splitter;31import net.thucydides.core.ThucydidesSystemProperty;32import net.thucydides.core.guice.Injectors;33import net.thucydides.core.util.EnvironmentVariables;34import net.thucydides.core.webdriver.Configuration;35import org.junit.runner.Description;36import org.junit.runner.manipulation.NoTestsRemainException;37import org.junit.runner.notification.RunNotifier;38import org.junit.runners.ParentRunner;39import org.junit.runners.model.InitializationError;40import org.junit.runners.model.RunnerScheduler;41import org.junit.runners.model.Statement;42import org.slf4j.Logger;43import org.slf4j.LoggerFactory;44import java.net.URI;45import java.nio.file.Paths;46import java.util.ArrayList;47import java.util.Collection;48import java.util.List;49import java.util.Optional;50import java.util.concurrent.atomic.AtomicInteger;51import java.util.function.Function;52import java.util.function.Predicate;53import static java.util.stream.Collectors.toList;54import static net.thucydides.core.ThucydidesSystemProperty.SERENITY_BATCH_COUNT;55import static net.thucydides.core.ThucydidesSystemProperty.SERENITY_BATCH_NUMBER;56import static net.thucydides.core.ThucydidesSystemProperty.SERENITY_FORK_COUNT;57import static net.thucydides.core.ThucydidesSystemProperty.SERENITY_FORK_NUMBER;58/**59 * Glue code for running Cucumber via Serenity.60 * Sets up Serenity reporting and instrumentation.61 */62public class CucumberSerenityRunner extends ParentRunner<FeatureRunner> {63 private static final Logger LOGGER = LoggerFactory.getLogger(CucumberSerenityRunner.class);64 private final List<FeatureRunner> children = new ArrayList<FeatureRunner>();65 private final EventBus bus;66 private final ThreadLocalRunnerSupplier runnerSupplier;67 private static ThreadLocal<RuntimeOptions> RUNTIME_OPTIONS = new ThreadLocal<>();68 private final List<CucumberFeature> features;69 private final Plugins plugins;70 private boolean multiThreadingAssumed = false;71 /**72 * Constructor called by JUnit.73 *74 * @param clazz the class with the @RunWith annotation.75 * @throws InitializationError if there is another problem76 */77 public CucumberSerenityRunner(Class clazz) throws InitializationError {78 super(clazz);79 ClassLoader classLoader = clazz.getClassLoader();80 ResourceLoader resourceLoader = new MultiLoader(classLoader);81 Assertions.assertNoCucumberAnnotatedMethods(clazz);82 83 // Parse the options early to provide fast feedback about invalid options84 RuntimeOptions annotationOptions = new CucumberOptionsAnnotationParser(resourceLoader)85 .withOptionsProvider(new JUnitCucumberOptionsProvider())86 .parse(clazz)87 .build();88 RuntimeOptions runtimeOptions = new EnvironmentOptionsParser(resourceLoader)89 .parse(Env.INSTANCE)90 .build(annotationOptions);91 runtimeOptions.addUndefinedStepsPrinterIfSummaryNotDefined();92 JUnitOptions junitAnnotationOptions = new JUnitOptionsParser()93 .parse(clazz)94 .build();95 JUnitOptions junitOptions = new JUnitOptionsParser()96 .parse(runtimeOptions.getJunitOptions())97 .setStrict(runtimeOptions.isStrict())98 .build(junitAnnotationOptions);99 setRuntimeOptions(runtimeOptions);100 FeatureLoader featureLoader = new FeatureLoader(resourceLoader);101 FeaturePathFeatureSupplier featureSupplier = new FeaturePathFeatureSupplier(featureLoader, runtimeOptions);102 // Parse the features early. Don't proceed when there are lexer errors103 this.features = featureSupplier.get();104 ClassFinder classFinder = new ResourceLoaderClassFinder(resourceLoader, classLoader);105 this.plugins = new Plugins(classLoader, new PluginFactory(),runtimeOptions);106 this.bus = new TimeServiceEventBus(TimeService.SYSTEM);107 Configuration systemConfiguration = Injectors.getInjector().getInstance(Configuration.class);108 SerenityReporter reporter = new SerenityReporter(systemConfiguration, resourceLoader);109 addSerenityReporterPlugin(plugins,reporter);110 BackendSupplier backendSupplier = new BackendModuleBackendSupplier(resourceLoader, classFinder, runtimeOptions);111 this.runnerSupplier = new ThreadLocalRunnerSupplier(runtimeOptions, bus, backendSupplier);112 Filters filters = new Filters(runtimeOptions);113 for (CucumberFeature cucumberFeature : features) {114 FeatureRunner featureRunner = new FeatureRunner(cucumberFeature, filters, runnerSupplier, junitOptions);115 if (!featureRunner.isEmpty()) {116 children.add(featureRunner);117 }118 }119 }120 private static RuntimeOptions DEFAULT_RUNTIME_OPTIONS;121 public static void setRuntimeOptions(RuntimeOptions runtimeOptions) {122 RUNTIME_OPTIONS.set(runtimeOptions);123 DEFAULT_RUNTIME_OPTIONS = runtimeOptions;124 }125 public static RuntimeOptions currentRuntimeOptions() {126 return (RUNTIME_OPTIONS.get() != null) ? RUNTIME_OPTIONS.get() : DEFAULT_RUNTIME_OPTIONS;127 }128 private static Collection<String> environmentSpecifiedTags(List<?> existingTags) {129 EnvironmentVariables environmentVariables = Injectors.getInjector().getInstance(EnvironmentVariables.class);130 String tagsExpression = ThucydidesSystemProperty.TAGS.from(environmentVariables,"");131 List<String> existingTagsValues = existingTags.stream().map(Object::toString).collect(toList());132 return Splitter.on(",").trimResults().omitEmptyStrings().splitToList(tagsExpression).stream()133 .map(CucumberSerenityRunner::toCucumberTag).filter(t -> !existingTagsValues.contains(t)).collect(toList());134 }135 private static String toCucumberTag(String from) {136 String tag = from.replaceAll(":","=");137 if (tag.startsWith("~@") || tag.startsWith("@")) { return tag; }138 if (tag.startsWith("~")) { return "~@" + tag.substring(1); }139 return "@" + tag;140 }141 public static Runtime createSerenityEnabledRuntime(ResourceLoader resourceLoader,142 ClassLoader classLoader,143 RuntimeOptions runtimeOptions,144 Configuration systemConfiguration) {145 ClassFinder classFinder = new ResourceLoaderClassFinder(resourceLoader, classLoader);146 setRuntimeOptions(runtimeOptions);147 FeatureLoader featureLoader = new FeatureLoader(resourceLoader);148 FeaturePathFeatureSupplier featureSupplier = new FeaturePathFeatureSupplier(featureLoader, runtimeOptions);149 // Parse the features early. Don't proceed when there are lexer errors150 final List<CucumberFeature> features = featureSupplier.get();151 EventBus bus = new TimeServiceEventBus(TimeService.SYSTEM);152 153 SerenityReporter serenityReporter = new SerenityReporter(systemConfiguration, resourceLoader);154 Runtime runtime = Runtime.builder().withResourceLoader(resourceLoader).withClassFinder(classFinder).155 withClassLoader(classLoader).withRuntimeOptions(runtimeOptions).156 withAdditionalPlugins(serenityReporter).157 withEventBus(bus).withFeatureSupplier(featureSupplier).158 build();159 return runtime;160 }161 private static void addSerenityReporterPlugin(Plugins plugins, SerenityReporter plugin)162 {163 for(Plugin currentPlugin : plugins.getPlugins()){164 if (currentPlugin instanceof SerenityReporter) {165 return;166 }167 }168 plugins.addPlugin(plugin);169 }170 @Override171 protected Description describeChild(FeatureRunner child) {172 return child.getDescription();173 }174 @Override175 protected void runChild(FeatureRunner child, RunNotifier notifier) {176 child.run(notifier);177 }178 @Override179 protected Statement childrenInvoker(RunNotifier notifier) {180 Statement runFeatures = super.childrenInvoker(notifier);181 return new RunCucumber(runFeatures);182 }183 class RunCucumber extends Statement {184 private final Statement runFeatures;185 RunCucumber(Statement runFeatures) {186 this.runFeatures = runFeatures;187 }188 @Override189 public void evaluate() throws Throwable {190 if (multiThreadingAssumed) {191 plugins.setSerialEventBusOnEventListenerPlugins(bus);192 } else {193 plugins.setEventBusOnEventListenerPlugins(bus);194 }195 bus.send(new TestRunStarted(bus.getTime(), bus.getTimeMillis()));196 for (CucumberFeature feature : features) {197 feature.sendTestSourceRead(bus);198 }199 StepDefinitionReporter stepDefinitionReporter = plugins.stepDefinitionReporter();200 runnerSupplier.get().reportStepDefinitions(stepDefinitionReporter);201 runFeatures.evaluate();202 bus.send(new TestRunFinished(bus.getTime(), bus.getTimeMillis()));203 }204 }205 @Override206 public void setScheduler(RunnerScheduler scheduler) {207 super.setScheduler(scheduler);208 multiThreadingAssumed = true;209 }210 @Override211 public List<FeatureRunner> getChildren() {212 try {213 EnvironmentVariables environmentVariables = Injectors.getInjector().getInstance(EnvironmentVariables.class);214 RuntimeOptions runtimeOptions = currentRuntimeOptions();215 List<String> tagFilters = runtimeOptions.getTagFilters();216 List<URI> featurePaths = runtimeOptions.getFeaturePaths();217 int batchNumber = environmentVariables.getPropertyAsInteger(SERENITY_BATCH_NUMBER, 1);218 int batchCount = environmentVariables.getPropertyAsInteger(SERENITY_BATCH_COUNT, 1);219 int forkNumber = environmentVariables.getPropertyAsInteger(SERENITY_FORK_NUMBER, 1);220 int forkCount = environmentVariables.getPropertyAsInteger(SERENITY_FORK_COUNT, 1);221 if ((batchCount == 1) && (forkCount == 1)) {222 return children;223 } else {224 LOGGER.info("Running slice {} of {} using fork {} of {} from feature paths {}", batchNumber, batchCount, forkNumber, forkCount, featurePaths);225 WeightedCucumberScenarios weightedCucumberScenarios = new CucumberSuiteSlicer(featurePaths, TestStatistics.from(environmentVariables, featurePaths))226 .scenarios(batchNumber, batchCount, forkNumber, forkCount, tagFilters);227 List<FeatureRunner> unfilteredChildren = children;228 AtomicInteger filteredInScenarioCount = new AtomicInteger();229 List<FeatureRunner> filteredChildren = unfilteredChildren.stream()230 .filter(forIncludedFeatures(weightedCucumberScenarios))231 .map(toPossibleFeatureRunner(weightedCucumberScenarios, filteredInScenarioCount))232 .filter(Optional::isPresent)233 .map(Optional::get)234 .collect(toList());235 if (filteredInScenarioCount.get() != weightedCucumberScenarios.totalScenarioCount()) {236 LOGGER.warn(237 "There is a mismatch between the number of scenarios included in this test run ({}) and the expected number of scenarios loaded ({}). This suggests that the scenario filtering is not working correctly or feature file(s) of an unexpected structure are being run",238 filteredInScenarioCount.get(),239 weightedCucumberScenarios.scenarios.size());240 }241 LOGGER.info("Running {} of {} features", filteredChildren.size(), unfilteredChildren.size());242 return filteredChildren;243 }244 } catch (Exception e) {245 LOGGER.error("Test failed to start", e);246 throw e;247 }248 }249 private Function<FeatureRunner, Optional<FeatureRunner>> toPossibleFeatureRunner(WeightedCucumberScenarios weightedCucumberScenarios, AtomicInteger filteredInScenarioCount) {250 return featureRunner -> {251 int initialScenarioCount = featureRunner.getDescription().getChildren().size();252 String featureName = FeatureRunnerExtractors.extractFeatureName(featureRunner);253 try {254 ScenarioFilter filter = weightedCucumberScenarios.createFilterContainingScenariosIn(featureName);255 String featurePath = FeatureRunnerExtractors.featurePathFor(featureRunner);256 featureRunner.filter(filter);257 if (!filter.scenariosIncluded().isEmpty()) {258 LOGGER.info("{} scenario(s) included for '{}' in {}", filter.scenariosIncluded().size(), featureName, featurePath);259 filter.scenariosIncluded().forEach(scenario -> {260 LOGGER.info("Included scenario '{}'", scenario);261 filteredInScenarioCount.getAndIncrement();262 });263 }264 if (!filter.scenariosExcluded().isEmpty()) {265 LOGGER.debug("{} scenario(s) excluded for '{}' in {}", filter.scenariosExcluded().size(), featureName, featurePath);266 filter.scenariosExcluded().forEach(scenario -> LOGGER.debug("Excluded scenario '{}'", scenario));267 }268 return Optional.of(featureRunner);269 } catch (NoTestsRemainException e) {270 LOGGER.info("Filtered out all {} scenarios for feature '{}'", initialScenarioCount, featureName);271 return Optional.empty();272 }273 };274 }275 private Predicate<FeatureRunner> forIncludedFeatures(WeightedCucumberScenarios weightedCucumberScenarios) {276 return featureRunner -> {277 String featureName = FeatureRunnerExtractors.extractFeatureName(featureRunner);278 String featurePath = PathUtils.getAsFile(FeatureRunnerExtractors.featurePathFor(featureRunner)).getName();279 boolean matches = weightedCucumberScenarios.scenarios.stream().anyMatch(scenario -> featurePath.equals(scenario.featurePath));280 LOGGER.debug("{} in filtering '{}' in {}", matches ? "Including" : "Not including", featureName, featurePath);281 return matches;282 };283 }284}...

Full Screen

Full Screen

Source:CucumberScenarioLoader.java Github

copy

Full Screen

...7import gherkin.ast.Scenario;8import gherkin.ast.ScenarioDefinition;9import gherkin.ast.ScenarioOutline;10import gherkin.ast.Tag;11import net.serenitybdd.cucumber.util.PathUtils;12import org.slf4j.Logger;13import org.slf4j.LoggerFactory;14import java.math.BigDecimal;15import java.net.URI;16import java.util.Collections;17import java.util.List;18import java.util.Set;19import java.util.function.Function;20import static java.util.Arrays.asList;21import static java.util.stream.Collectors.toList;22import static java.util.stream.Collectors.toSet;23/**24 * Reads cucumber feature files and breaks them down into a collection of scenarios (WeightedCucumberScenarios).25 */26public class CucumberScenarioLoader {27 private static final Logger LOGGER = LoggerFactory.getLogger(CucumberScenarioLoader.class);28 private final List<URI> featurePaths;29 private final TestStatistics statistics;30 public CucumberScenarioLoader(List<URI> featurePaths, TestStatistics statistics) {31 this.featurePaths = featurePaths;32 this.statistics = statistics;33 }34 public WeightedCucumberScenarios load() {35 LOGGER.debug("Feature paths are {}", featurePaths);36 ResourceLoader resourceLoader = new MultiLoader(CucumberSuiteSlicer.class.getClassLoader());37 List<WeightedCucumberScenario> weightedCucumberScenarios = new FeatureLoader(resourceLoader).load(featurePaths).stream()38 .map(getScenarios())39 .flatMap(List::stream)40 .collect(toList());41 return new WeightedCucumberScenarios(weightedCucumberScenarios);42 }43 private Function<CucumberFeature, List<WeightedCucumberScenario>> getScenarios() {44 return cucumberFeature -> {45 try {46 return (cucumberFeature.getGherkinFeature().getFeature() == null) ? Collections.emptyList() : cucumberFeature.getGherkinFeature().getFeature().getChildren()47 .stream()48 .filter(child -> asList(ScenarioOutline.class, Scenario.class).contains(child.getClass()))49 .map(scenarioDefinition -> new WeightedCucumberScenario(50 PathUtils.getAsFile(cucumberFeature.getUri()).getName(),51 cucumberFeature.getGherkinFeature().getFeature().getName(),52 scenarioDefinition.getName(),53 scenarioWeightFor(cucumberFeature, scenarioDefinition),54 tagsFor(cucumberFeature, scenarioDefinition),55 scenarioCountFor(scenarioDefinition)))56 .collect(toList());57 } catch (Exception e) {58 throw new IllegalStateException(String.format("Could not extract scenarios from %s", cucumberFeature.getUri()), e);59 }60 };61 }62 private int scenarioCountFor(ScenarioDefinition scenarioDefinition) {63 if (scenarioDefinition instanceof ScenarioOutline) {64 return ((ScenarioOutline) scenarioDefinition).getExamples().stream().map(examples -> examples.getTableBody().size()).mapToInt(Integer::intValue).sum();...

Full Screen

Full Screen

Source:CucumberScenarioVisualiser.java Github

copy

Full Screen

1package net.serenitybdd.cucumber.suiteslicing;2import com.google.gson.GsonBuilder;3import net.serenitybdd.cucumber.util.PathUtils;4import net.thucydides.core.util.EnvironmentVariables;5import org.slf4j.Logger;6import org.slf4j.LoggerFactory;7import java.net.URI;8import java.nio.file.Files;9import java.nio.file.Paths;10import java.util.List;11import java.util.stream.IntStream;12import static com.google.common.collect.Lists.newArrayList;13import static java.util.stream.Collectors.toList;14import static net.thucydides.core.ThucydidesSystemProperty.SERENITY_OUTPUT_DIRECTORY;15public class CucumberScenarioVisualiser {16 private final Logger LOGGER = LoggerFactory.getLogger(CucumberScenarioVisualiser.class);17 private final EnvironmentVariables environmentVariables;18 public CucumberScenarioVisualiser(EnvironmentVariables environmentVariables) {19 this.environmentVariables = environmentVariables;20 }21 private String outputDirectory() {22 return environmentVariables.getProperty(SERENITY_OUTPUT_DIRECTORY, "target/site/serenity");23 }24 public static List<VisualisableCucumberScenarios> sliceIntoForks(int forkCount, List<WeightedCucumberScenarios> slices) {25 return slices.stream()26 .map(slice -> IntStream.rangeClosed(1, forkCount).mapToObj(forkNumber -> VisualisableCucumberScenarios.create(slices.indexOf(slice) + 1, forkNumber, slice.slice(forkNumber).of(forkCount)))27 .collect(toList())).flatMap(List::stream).collect(toList());28 }29 public void visualise(URI rootFolderURI, int sliceCount, int forkCount, TestStatistics testStatistics) {30 try {31 Files.createDirectories(Paths.get(outputDirectory()));32 List<WeightedCucumberScenarios> slices = new CucumberScenarioLoader(newArrayList(rootFolderURI), testStatistics).load().sliceInto(sliceCount);33 List<VisualisableCucumberScenarios> visualisedSlices = CucumberScenarioVisualiser.sliceIntoForks(forkCount, slices);34 String jsonFile = String.format("%s/%s-slice-config-%s-forks-in-each-of-%s-slices-using-%s.json", outputDirectory(), PathUtils35 .getAsFile(rootFolderURI).getPath().replaceAll("[:/]", "-"), forkCount, sliceCount, testStatistics);36 Files.write(Paths.get(jsonFile), new GsonBuilder().setPrettyPrinting().create().toJson(visualisedSlices).getBytes());37 LOGGER.info("Wrote visualisation as JSON for {} slices -> {}", visualisedSlices.size(), jsonFile);38 } catch (Exception e) {39 throw new RuntimeException("failed to visualise scenarios", e);40 }41 }42}...

Full Screen

Full Screen

Source:PathUtils.java Github

copy

Full Screen

...6import java.util.Objects;78import io.cucumber.core.model.Classpath;910public class PathUtils {1112 private PathUtils() {13 }1415 public static File getAsFile(URI cucumberFeatureUri) {16 Objects.requireNonNull(cucumberFeatureUri, "cucumber feature URI cannot be null");17 String featureFilePath;18 switch (cucumberFeatureUri.getScheme()) {19 case "file": {20 try {21 featureFilePath = cucumberFeatureUri.toURL().getPath();22 break;23 } catch (MalformedURLException e) {24 throw new IllegalArgumentException("Cannot convert cucumber feature URI to URL", e);25 }26 } ...

Full Screen

Full Screen

PathUtils

Using AI Code Generation

copy

Full Screen

1import net.serenitybdd.cucumber.util.PathUtils;2import net.thucydides.core.util.EnvironmentVariables;3import net.thucydides.core.util.SystemEnvironmentVariables;4import org.apache.commons.lang3.StringUtils;5import org.openqa.selenium.WebDriver;6import org.openqa.selenium.chrome.ChromeDriver;7import org.openqa.selenium.chrome.ChromeOptions;8import org.openqa.selenium.firefox.FirefoxDriver;9import org.openqa.selenium.firefox.FirefoxProfile;10import org.openqa.selenium.ie.InternetExplorerDriver;11import org.openqa.selenium.remote.DesiredCapabilities;12import org.openqa.selenium.remote.RemoteWebDriver;13import org.openqa.selenium.safari.SafariDriver;14import java.io.File;15import java.io.IOException;16import java.net.MalformedURLException;17import java.net.URL;18import java.util.HashMap;19import java.util.Map;20public class DriverFactory {21 private static final String DEFAULT_WEBDRIVER = "chrome";22 private static final String DEFAULT_WEBDRIVER_CAPABILITIES = "chrome";23 private static final String DEFAULT_CHROME_DRIVER = "src/test/resources/drivers/chromedriver";24 private static final String DEFAULT_IE_DRIVER = "src/test/resources/drivers/IEDriverServer";25 private static final String DEFAULT_FIREFOX_PROFILE = "src/test/resources/drivers/firefoxProfile";26 private static final String ENVIRONMENT = System.getProperty("environment", "local");27 private static final String WEBDRIVER = System.getProperty("webdriver", DEFAULT_WEBDRIVER);28 private static final String WEBDRIVER_CAPABILITIES = System.getProperty("webdriver.capabilities", DEFAULT_WEBDRIVER_CAPABILITIES);29 private static final String REMOTE_URL = System.getProperty("remote.url", DEFAULT_REMOTE_URL);30 private static final String CHROME_DRIVER = System.getProperty("chrome.driver", DEFAULT_CHROME_DRIVER);31 private static final String IE_DRIVER = System.getProperty("ie.driver", DEFAULT_IE_DRIVER);32 private static final String FIREFOX_PROFILE = System.getProperty("firefox.profile", DEFAULT_FIREFOX_PROFILE);33 private static final String CHROME = "chrome";34 private static final String FIREFOX = "firefox";35 private static final String IE = "ie";36 private static final String SAFARI = "safari";37 private static final String REMOTE = "remote";38 private static final String CHROME_CAPABILITIES = "chrome";39 private static final String FIREFOX_CAPABILITIES = "firefox";

Full Screen

Full Screen

PathUtils

Using AI Code Generation

copy

Full Screen

1import net.serenitybdd.cucumber.util.PathUtils;2import java.io.File;3import java.util.List;4import java.util.ArrayList;5import java.util.Arrays;6import java.util.Collections;7import java.util.stream.Collectors;8import java.util.stream.Stream;9import java.util.stream.IntStream;10public class Test {11 public static void main(String[] args) {12 List<String> files = Arrays.asList("a.txt", "b.txt", "c.txt", "d.txt");13 List<String> files1 = files.stream().map(f -> PathUtils.getRelativePath(new File(f))).collect(Collectors.toList());14 System.out.println(files1);15 }16}

Full Screen

Full Screen

PathUtils

Using AI Code Generation

copy

Full Screen

1import net.serenitybdd.cucumber.util.PathUtils;2 @Given("I have a file named {string} with the following content")3 public void iHaveAFileNamedWithTheFollowingContent(String filename, String content) throws IOException {4 Path path = PathUtils.pathTo(PathUtils.currentDirectory(), filename);5 Files.write(path, content.getBytes());6 }7 @When("I run the {string} command")8 public void iRunTheCommand(String command) {9 commandOutput = runCommand(command);10 }11 @Then("the command should succeed")12 public void theCommandShouldSucceed() {13 assertThat(commandOutput.exitCode).isEqualTo(0);14 }15 @Then("the command should fail")16 public void theCommandShouldFail() {17 assertThat(commandOutput.exitCode).isNotEqualTo(0);18 }19 @Then("the command should provide the following output")20 public void theCommandShouldProvideTheFollowingOutput(String expectedOutput) {21 assertThat(commandOutput.output).contains(expectedOutput);22 }23 private CommandOutput runCommand(String command) {24 try {25 Process process = Runtime.getRuntime().exec(command);26 process.waitFor();27 String output = new String(process.getInputStream().readAllBytes());28 return new CommandOutput(output, process.exitValue());29 } catch (Exception e) {30 return new CommandOutput("", -1);31 }32 }33 private static class CommandOutput {34 String output;35 int exitCode;36 public CommandOutput(String output, int exitCode) {37 this.output = output;38 this.exitCode = exitCode;39 }40 }41}42package net.serenitybdd.cucumber.examples;43import io.cucumber.java.en.Given;44import io.cucumber.java.en.Then;45import io.cucumber.java.en.When;46import net

Full Screen

Full Screen

PathUtils

Using AI Code Generation

copy

Full Screen

1public class PathUtils {2 public static String getSystemProperty(String propertyName) {3 return System.getProperty(propertyName);4 }5}6public class MyStepdefs {7 @Given("^I am on the (.*) page$")8 public void iAmOnThePage(String pageName) {9 String url = PathUtils.getSystemProperty("url");10 }11}12In this example, we have defined a PathUtils class that has a method called getSystemProperty() that returns the value of a given system property. In the MyStepdefs class, we have defined a step definition that uses the PathUtils class to get the value of the url system property. We can now run our tests with different values for the url system property. For example:13@Value("${url}")14String url;15@Given("^I am on the (.*) page$")16public void iAmOnThePage(String pageName) {17}18@Value("${url}")19String url;20@Given("^I am on the (.*) page$")21public void iAmOnThePage(String pageName) {22}23@Value("${url}")24String url;25@Given("^I am on the (.*) page$")26public void iAmOnThePage(String pageName) {27}28@Value("${url}")29String url;

Full Screen

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Serenity Cucumber automation tests on LambdaTest cloud grid

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

Most used methods in PathUtils

Test Your Web Or Mobile Apps On 3000+ Browsers

Signup for free

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful