-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
This issue was moved to a discussion.
You can continue the conversation there. Go to discussion →
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Programmatic API for running cucumber-js #1711
Comments
Paging for initial feedback: @aslakhellesoy @charlierudolph @aurelien-reeves @mattwynne @nicojs @jan-molak |
I love this proposal! We already an API like this in fake-cucumber's runCucumber |
@davidjgoss - sounds great! For your reference, here's how Serenity/JS invokes Cucumber at the moment - Being able to provide an options object instead of argv would be much nicer 👍🏻 |
Love it! |
While specifying that new public API, we may also consider what recently happened with issue #1489 and think about providing public APIs to have more and better interaction with the filters and the resulting features under test |
And to add to that - let's make something that would make it easier for Cucumber-Electron too: |
Having a public API is better than nothing, so go ahead 👍! Preferably I would also have an API to load profiles using the same rules as loadProfiles(directory = process.cwd()): Record<string, Profile> StrykerJS will also rely heavily on the custom_formatters API and the events published by the |
This is a good point. Profiles (in their current form at least) are fundamentally coupled to the CLI so it feels right to keep them on that side of the boundary, but we could still expose a function to load them and generate a partial options object. |
I think we could include an option for providing a custom pickle filter when calling the API (in addition to the names, tags etc that drive the built-in filtering). |
The current syntax for profiles if very command-line-y. I would ❤️❤️❤️ to be able to specify profiles in a more generic format such as JSON, JavaScript, YAML or environment variables. In JSON it could look like this:
{
"default": {
"requireModule": ["ts-node/register"],
"require": ["support/**/*./ts"],
"worldParameters": {
"appUrl": "http://localhost:3000/",
},
"format": ["progress-bar", "html:./cucumber-report.html"]
},
"ci": {
"requireModule": ["ts-node/register"],
"require": ["support/**/*./ts"],
"worldParameters": {
"appUrl": "http://localhost:3000/",
},
"format": ["html:./cucumber-report.html"],
"publish": true
}
} Or, using JavaScript
const common = {
"requireModule": ["ts-node/register"],
"require": ["support/**/*./ts"],
"worldParameters": {
"appUrl": "http://localhost:3000/",
}
}
module.exports = {
default: {
...common,
"format": ["progress-bar", "html:./cucumber-report.html"]
},
ci: {
...common,
"format": ["html:./cucumber-report.html"],
"publish": true
}
} Or even with environment variables (for example loaded with a tool like dotenv):
CUCUMBER_PROFILE_DEFAULT_REQUIREMODULE=ts-node/register
CUCUMBER_PROFILE_DEFAULT_REQUIRE=ts-node/register
CUCUMBER_PROFILE_DEFAULT_WORLDPARAMETERS_APPURL=http://localhost:3000/
CUCUMBER_PROFILE_DEFAULT_FORMAT=progress-bar,html:./cucumber-report.html
CUCUMBER_PROFILE_CI_REQUIREMODULE=ts-node/register
CUCUMBER_PROFILE_CI_REQUIRE=ts-node/register
CUCUMBER_PROFILE_CI_WORLDPARAMETERS_APPURL=http://localhost:3000/
CUCUMBER_PROFILE_CI_FORMAT=progress-bar,html:./cucumber-report.html
CUCUMBER_PROFILE_CI_PUBLISH=true In fact, the config library does exactly this. We never ended up integrating it in Cucumber-JVM because other stuff got in the way, but maybe we could give it a go with a JavaScript implementation? |
@aslakhellesoy agree that would be awesome! I'll try and get a POC going for this proposal so we have something a bit more concrete to talk around, and would love to make profiles right as part of it (4.5 years and counting on #751 😄) |
Refs. #1004 |
Yes, that would be awesome and much appreciated from the point of view of plugin creators.
That sounds great! And is also exactly the reason I would appreciate an API to load them the same way as cucumberJS does. Loading a single |
Q: Would I be able to run We want to load the environment and run the tests multiple times in quick succession while changing a global variable in order to switch the active mutant. Right now, we're using the Pseudo code of our use case: const profiles = await loadProfiles();
const options = {
...profiles.default,
formatter: require.resolve('./our-awesomely-crafted-formatter'),
some: 'other options we want to override',
}
const cucumber = new Cucumber(options);
// Allow cucumber to load the step definitions once.
// This is `async`, so support for esm can be added without a breaking change
await cucumber.initialize();
// Initial test run ("dry run"), without mutants active
await cucumber.run();
collectMutantCoveragePerTestFromFormatter();
// Start mutation testing:
global.activeMutant = 1;
await cucumber.run({ features: ['features/a.feature:24']);
collectResultsFromFormatterToDetermineKilledOrSurvivedMutant()
global.activeMutant = 2;
await cucumber.run({ features: ['features/b.feature:24:25:26', 'features/c.feature:12']);
collectResultsFromFormatterToDetermineKilledOrSurvivedMutant()
// etc |
@nicojs definitely agree we need this, it's come up a few times before with e.g. people wanting to run cucumber in a lambda, and I'd also like to add an interactive mode which would need it too. What I had sketched out so far was in more of a functional style but same fundamental concept I think: const runnerOptions = {
support: {
require: ['features/support/**/*.js']
}
}
// initial run returns support code library
const { support } = await runCucumber(runnerOptions)
// subsequent run reuses support code library
await runCucumber({
...runnerOptions,
support
}) |
That works for us 👍 |
Works for us too 👍🏻 |
I really think that something like this would be extremely useful as an alternative for the great mess we have today with testing tool integrations (Jest, Cypress), for example I found these problems (in the order of importance):
I would rather see some minimal glue code between Jest/Karma/Cypress/etc. and cucumber-js so I don't have to suffer for all those missing features I need to use. |
Great suggestion @davidjgoss 👍 This separation of concerns between the command-line user interface and the "business logic" of parsing and executing scenarios as tests reminds me of the hexagonal architecture pattern. In cucumber-ruby we actually split the core domain logic (or "inner hexagon") into a separate gem package, as we were rebuilding it from scratch in a "clean room". I realise that's not the context here, but it might be worth drawing some inspiration from, or feeding back innovations from this design into the Ruby API. There's an example in the cucumber-ruby-core gem's README of how to use that API. |
Okay, here's a first pass at the API signature for the "run" bit. It's heavily based on the export interface IRunCucumberOptions {
cwd: string
features: {
defaultDialect?: string
paths: string[]
}
filters: {
name?: string[]
tagExpression?: string
}
support:
| {
transpileWith?: string[]
paths: string[]
}
| ISupportCodeLibrary
runtime: {
dryRun?: boolean
failFast?: boolean
filterStacktraces?: boolean
parallel?: {
count: number
}
retry?: {
count: number
tagExpression?: string
}
strict: boolean
worldParameters?: any
}
formats: {
stdout: string
files: Record<string, string>
options: IParsedArgvFormatOptions
}
}
export interface IRunResult {
success: boolean
support: ISupportCodeLibrary
}
export async function runCucumber(
options: IRunCucumberOptions
): Promise<IRunResult> {
// do stuff
} And a very contrived example usage: const result = await runCucumber({
cwd: process.cwd(),
features: {
paths: ['features/**/*.feature'],
},
filters: {
name: ['Acme'],
tagExpression: '@interesting',
},
support: {
transpileWith: ['ts-node'],
paths: ['features/support/**/*.ts'],
},
runtime: {
failFast: true,
retry: {
count: 1,
tagExpression: '@flaky',
},
strict: true,
worldParameters: {
foo: 'bar',
},
},
formats: {
stdout: '@cucumber/pretty-formatter',
files: {
'report.html': 'html',
'TEST-cucumber.xml': 'junit',
},
options: {
printAttachments: false,
},
},
}) Feedback welcome! Note this doesn't cover the profile/config loading stuff which would be another function. |
I think this looks good. Question: How would I configure a custom formatter? |
@nicojs sorta like on the CLI formats: {
files: {
'report.html': './my/fancy-reporter.js',
'other-report.html': '@me/reporter-package',
}
}, |
Yes, I think so in retrospect. |
8.0.0-rc.3 has been released including this new API, there are some docs here - a little thin at the moment but will continue to expand them. If anyone has any early feedback that'd be fantastic (cc @jan-molak @nicojs @binarymist). |
Hey thanks for doing this great job, I need to use from @cucumber/cucumber: 8.0.0, when it will be available to use? |
@MarufSharifi within the next week or two, but you can try |
Thanks @davidjgoss . https://github.com/cucumber/cucumber-js/releases/tag/v8.0.0-rc.3 links to https://github.com/cucumber/cucumber-js/blob/v8.0.0-rc.3/docs/cli.md#printing-attachments-details which doesn't appear to exist. I'm assuming https://github.com/cucumber/cucumber-js/blob/main/docs/javascript_api.md#sources-example is what I'm looking for to recreate our testplan functionality?
Can you please explain how this can replace our existing Thanks. |
Fixed, thanks for the notification |
loadConfiguration returns a In your case, how does it looks like? If it does not looks as expected, give the proper argument to Refs to the documentation of the API:
If you are still not able to make it work, please provide more info to us like your piece of code, what is expected, and what is the actual result |
What is the configuration file in this context? We have a set of environment application config files with the following relevant cucumber properties in them:
Is this what you're refering to as "the configuration file"? We have no other cucumber specific configuration file. Sadly the file documentation tells us nothing of what should be inside it. Is the contents described else where? It's still not clear how to get from where we currently are (as clearly specified above) and reiterated again below for your convenience to the new API:
I'd imagine that because we've had the same functionality working for a long time previously then we obviously have all the information that cucumber needs, it's just a matter of how do we get the information into a form that the new API can deal with? So it looks like the new I'm also unsure how we get from the current not passing anything to the CLI's I've looked at both
Thanks. |
@binarymist so for the test plan case specifically you shouldn't need to use the The const { runConfiguration } = await loadConfiguration({
provided: {
paths: [`${this.#cucumber.features}/${sessionProps.sUtType}`],
require: [`${this.#cucumber.steps}/${sessionProps.sUtType}`],
format: [`message:${this.#results.dir}result_appScannerId-${sessionProps.testSession ? sessionProps.testSession.id : 'noSessionPropsAvailable'}_${this.#strings.NowAsFileName('-')}.NDJSON`],
// etc
}
})
Both functions have an optional {
cwd: process.cwd(), // files would be loaded relative to this dir
stdout: process.stdout,
stderr: process.stderr,
env: process.env,
} I hope this helps. I appreciate the docs are a little thin right now but they'll improve quickly and feedback like this is helpful. |
I might be too late to the party to give input, but the API still seems fairly similar to running cucumber from the CLI, and I'm having some trouble understanding how to apply this for my use case. I want to write a test file that contains all of the steps, then run those steps on one or more associated feature-files. I'm using TS, and I want to be able to compile the test and then run it repeatedly as I develop the feature file without having to re-do the transpilation step repeatedly, which slows down the development loop. It's already been mentioned that I can use |
Thanks @davidjgoss that was really helpful to get It looks like the update from rc.2 to rc.3 may have broken our Have you seen this error before:
app_scan_steps.js is here I've created a diff where the only difference is rc.2 vs rc.3 which has confirmed that this error doesn't exist with rc.2 and is introduced with rc.3. Thanks. |
There doesn't appear to be a lib/api/support.js in the root of the cucumber repo, but I found a src/api/support.ts which appears to be new in rc.3 and it appears to be So it seems that cucumber in rc.2 supports ESM but rc.3 has regressed to only supporting CJS? |
@binarymist it’s still there but uses a specfic option for import vs require now - previously it was inferred but the heuristics were too fuzzy so we changed it to be explicit: |
(We should add better messaging for that, thanks for raising.) |
@garfieldnate just to make sure I understand, you want to:
If so, I think you could implement this now. You can't create the support code library inline, but you can load it once and use it multiple times. Something like: import {loadConfiguration, loadSupport, runCucumber} from '@cucumber/cucumber/api'
const {runConfiguration} = await loadConfiguration()
const support = await loadSupport(runConfiguration)
const merged = {...runConfiguration, support}
// do this bit as many times as you want e.g. in a loop or callback
await runCucumber(merged) |
Thanks @davidjgoss. Initial testing has the import working. It seems that the colour characters (green ticks, red crosses, dashes, etc) that are usually written are no longer colour. We haven't changed the Thanks. |
That seems to be an issue. Do you think you could submit a new issue for that, with a minimal reproducible example? |
Worth noting we switched from using |
Currently we're going through the release phase with no colours (as a known issue). We're unable to keep PurpleTeam users waiting any longer. Will try and circle back to this. I'm not sure how minimal a seperate reproducable example would be. My guess is that everyone else expecting colours on this version will also be facing the same problem. It's just running the CLI with |
I already tried that, but I cannot reproduce your issue How do you pass the format options to cucumber? Through the CLI directly? Using a config file? I am puzzled with the format you are using. Why such format? I mean: First of all, that option is true per default, so you should be able to not specifying that option. |
@aurelien-reeves I think that's from running the I think I might see the/an issue here, going to raise something new though @binarymist as it's not API related per se. |
cucumber/cucumber-js#1711 (comment) With the upgrade to rc.3 colours are now broken: cucumber/cucumber-js#1711 (comment)
Also change cucumber args to import ESM: cucumber/cucumber-js#1711 (comment) With the upgrade to rc.3 colours are now broken: cucumber/cucumber-js#1711 (comment)
This issue was moved to a discussion.
You can continue the conversation there. Go to discussion →
Problem
Currently we don't have a good way to programmatically run cucumber-js. The need is from several angles:
As-is
What tends to happen at the moment is a new instance of
Cli
is created with strung-together argv input. It's obviously very unweildy and also isn't on the public API.Sometimes (possibly due to perceived fragility of the above) frameworks will just rely on the cucumber-js CLI but struggle to find ways to integrate and have their own options.
The
Runtime
class is currently part of the public API but it's not useful in these contexts, depending on the pickles and support code to be provided by the caller.Proposal
Two components in the project:
runCucumber
New async function that executes a test run in-process. Responsibilities:
This would be part of the public API and we'd encourage framework maintainers to use it when "wrapping" cucumber-js. We'd also use it for our own testing.
As much as possible, it would avoid direct interaction with
process
, instead accepting normalised options and stream interfaces for output, and leaving it to the caller to decide how to exit based on the result or an unhandled error.Also
Runtime
should come off the public API as it's really an internal thing.CLI
Effectively a "client" of
runCucumber
. Responsibilities:runCucumber
with the resolved optionsThis would continue to not be on the public API. Also it would only use functions/interfaces that are on the public API, such that we could easily break it out into its own package at some point, as is a common pattern now with projects like Jest.
This decoupling also paves the way for some interesting new CLI features without having them bleed into the internals, e.g.:
--gui
for the cucumber-electron stuff--interactive
for quick targeted reruns when TDD'ingetc
We would also expose functions (consumable by the CLI and by others) for:
i18nKeywords
andi18nLanguages
Timescale
We'd target this at the upcoming 8.0.0 release.
The text was updated successfully, but these errors were encountered: