cucumber / cucumber-js

Cucumber for JavaScript
https://cucumber.io
MIT License
5.06k stars 1.09k forks source link

Programmatic API for running cucumber-js #1711

Closed davidjgoss closed 2 years ago

davidjgoss commented 3 years ago

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:

This 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.:

etc

We would also expose functions (consumable by the CLI and by others) for:

Timescale

We'd target this at the upcoming 8.0.0 release.

davidjgoss commented 2 years ago

@MarufSharifi within the next week or two, but you can try 8.0.0-rc.3 in the meantime if that helps.

binarymist commented 2 years ago

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?

runConfiguration doesn't seem to contain anything of value.

loadSources(runConfiguration.sources) returns undefined

Can you please explain how this can replace our existing testPlan functionality, maybe even provide some tips to help with the guess work?

Thanks.

aurelien-reeves commented 2 years ago

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.

Fixed, thanks for the notification

aurelien-reeves commented 2 years ago

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?

runConfiguration doesn't seem to contain anything of value.

loadSources(runConfiguration.sources) returns undefined

Can you please explain how this can replace our existing testPlan functionality, maybe even provide some tips to help with the guess work?

Thanks.

loadConfiguration returns a runConfiguration and a useConfiguration. useConfiguration is the resolution of the configuration that the API has computed from the configuration file, environment, and other given parameters.

In your case, how does it looks like? If it does not looks as expected, give the proper argument to loadConfiguration method.

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

binarymist commented 2 years ago

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:

cucumber: {
    features: {
      doc: 'The location of the feature files.',
      format: String,
      default: 'src/features'
    },
    steps: {
      doc: 'The location of the step files.',
      format: String,
      default: 'src/steps'
    },
    binary: {
      doc: 'The location of the Cucumber binary.',
      format: String,
      // default: `${process.cwd()}/node_modules/.bin/cucumber-js`
      default: path.join(process.cwd(), '/bin/purpleteamCucumber.js')
    },
    timeout: {
      doc: 'The value used to set the timeout (https://github.com/cucumber/cucumber-js/blob/master/docs/support_files/timeouts.md)',
      format: 'duration',
      default: 5000
    }
  },

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:

  1. For the testplan command we...
  2. createCucumberArgs
  3. We pass the new CucCli instance to getActiveFeatureFileUris
  4. Which calls the legacy getConfiguration method of the cucumber CLI instance which no longer exists

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 loadConfiguration can replace the legacy CLI getConfiguration. I'm not sure if what it returns though provides us with the pickleFilterOptions and featurePaths that we need as seen in our getActiveFeatureFileUris?

I'm also unsure how we get from the current not passing anything to the CLI's getConfiguration method to the arguments (loadConfigurationOptions and runEnvironment) that the new loadConfiguration expects?

I've looked at both ILoadConfigurationOptions and IRunEnvironment docs.

Thanks.

davidjgoss commented 2 years ago

@binarymist so for the test plan case specifically you shouldn't need to use the Cli class at all. loadSources from the new API should, I think, give you what you need.

The loadConfiguration method is designed to source configuration from the standard cucumber configuration file that a user might have in their project, apply some defaults where nothing is specified, and return it in a shape that works for the other API functions. For your case it seems configuration is managed in its own way and you already have it to hand at runtime, so you could use the provided option to include that directly, and omit the file and profiles which wouldn't matter. This would be similar to what you do with createCucumberArgs and then passing that to the Cli, except it's in object form rather than an argv-style string, something like:

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
  }
})

runConfiguration.sources should then be what you need to give to loadSources, which returns an object with a plan property, which is a (pre-filtered by paths, tags, names etc) array of objects each representing a pickle (test case) to be run.

Both functions have an optional environment argument which you mentioned - you don't need to provide this unless you need any of the values to be different from the defaults, which are:

{
  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.

garfieldnate commented 2 years ago

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 loadConfiguration({provided: {...}}) to define the config inline. I'm unsure of how to do the same for loadSupport; I need to create an ISupportCodeLibrary from the steps and world in the current file, but there's no documentation on how to construct this.

binarymist commented 2 years ago

Thanks @davidjgoss that was really helpful to get testPlan working.

It looks like the update from rc.2 to rc.3 may have broken our test functionaly?

Have you seen this error before:

Error [ERR_REQUIRE_ESM]: require() of ES Module /usr/src/app/src/steps/BrowserApp/app_scan_steps.js from /usr/src/app/node_modules/@cucumber/cucumber/lib/api/support.js not supported.
 Instead change the require of app_scan_steps.js in /usr/src/app/node_modules/@cucumber/cucumber/lib/api/support.js to a dynamic import() which is available in all CommonJS modules.
     at /usr/src/app/node_modules/@cucumber/cucumber/lib/api/support.js:14:32
     at Array.map (<anonymous>)
     at getSupportCodeLibrary (/usr/src/app/node_modules/@cucumber/cucumber/lib/api/support.js:14:18)
     at runCucumber (/usr/src/app/node_modules/@cucumber/cucumber/lib/api/run_cucumber.js:33:53)
     at async Cli.run (/usr/src/app/node_modules/@cucumber/cucumber/lib/cli/index.js:45:29)
     at async run (file:///usr/src/app/src/scripts/runCuc.js:75:14) {
   code: 'ERR_REQUIRE_ESM'
 }

app_scan_steps.js is here
runCuc.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.

binarymist commented 2 years ago

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 requireing our ESM, so as expected the error makes sense.

So it seems that cucumber in rc.2 supports ESM but rc.3 has regressed to only supporting CJS?

davidjgoss commented 2 years ago

@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:

davidjgoss commented 2 years ago

(We should add better messaging for that, thanks for raising.)

davidjgoss commented 2 years ago

@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)
binarymist commented 2 years ago

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 '--format-options', '{"colorsEnabled": true}',. Has something else been changed around the formaters?

Thanks.

aurelien-reeves commented 2 years ago

That seems to be an issue. Indeed there have been recent changes under the hood, but not related to the API

Do you think you could submit a new issue for that, with a minimal reproducible example?

davidjgoss commented 2 years ago

Worth noting we switched from using colors to chalk in a hurry for well-known reasons, could be related to that.

binarymist commented 2 years ago

Do you think you could submit a new issue for that, with a minimal reproducible example?

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 '--format-options', '{"colorsEnabled": true}'
Nothing else special, we've been running the CLI this way for years.

aurelien-reeves commented 2 years ago

It's just running the CLI with '--format-options', '{"colorsEnabled": true}' Nothing else special, we've been running the CLI this way for years.

I already tried that, but I cannot reproduce your issue

image

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: '--format-options', '{"colorsEnabled": true}': how do you pass those parameters to cucumber?

First of all, that option is true per default, so you should be able to not specifying that option. Also, why that coma between format-options and the options? And the quotes? I would suggest trying this instead: --format-options '{"colorsEnabled": true}'

davidjgoss commented 2 years ago

@aurelien-reeves I think that's from running the Cli programmatically where you provide argv as string[]

I think I might see the/an issue here, going to raise something new though @binarymist as it's not API related per se.