Skip to content
This repository was archived by the owner on Mar 3, 2023. It is now read-only.

Introduce an option to run Atom tests with an alternative test runner - #8917

Closed
bolinfest wants to merge 9 commits into
masterfrom
bf-alternative-test-runner
Closed

bolinfest wants to merge 9 commits into
masterfrom
bf-alternative-test-runner

Conversation

@bolinfest

Copy link
Copy Markdown
Contributor

On a high level, I would like to be able to use an alternative test runner for running tests in Atom. (Currently, Atom uses Jasmine 1.3 for its test runner.) Atom already does a lot of great work to set up the test environment and to enable the test runner to run in-process, on par with other JavaScript in Atom.

Previously, spec-bootstrap.coffee loaded jasmine-helper.coffee, which in turn loaded vendor/jasmine, jasmine-tagged, and spec-helper.coffee via spec-suite.coffee (which installs a bunch of properties on the globals jasmine and window, loading jasmine-json and vendor/jasmine-jquery, to boot!). The net effect of spec-bootstrap.coffee was to set up a bunch of helpers for Jasmine, register some Jasmine reporters, and run jasmine.Env.execute().

With this change, the only requirement to be a "test runner" is to be a function that takes a hash of options and synchronously returns an object with an execute() method. This is much simpler. It also makes it possible to introduce a test runner that is completely independent from Jasmine.

The default implementation maintains the old behavior: jasmine-helper.coffee has become jasmine-helper.js. Where it used to export a runSpecSuite() function that could load an arbitrary file (which was always spec-suite.coffee, in practice) and then create a new jasmine.Env and execute() it, now jasmine-helper.js exports runSpecSuite() with its defaults baked in and it returns the jasmine.Env without executing it. Now it is up to spec-bootstrap.coffee to decide whether to load jasmine-helper.coffee or some other file and to invoke the execute() method on the resulting object that it creates.

Here is an example of an alternative/trivial implementation of a custom test runner that satisfies the contract:

'use babel';
/* @flow */

type TestRunnerOptions = {
  logFile: ?string,
};

type TestRunner = {
  execute(): void,
};

export default function createTestRunner({logFile}: TestRunnerOptions): TestRunner {
  return {
    execute() {
      atom.exit(0);
    },
  };
}

This PR introduces a new flag for the Atom executable, --test-runner-bootstrap, that makes it possible to specify the source of the alternative test runner. For example, if the above were defined at /path/to/test-runner/bootstrap.js, then it could be used as a test runner as follows:

atom --dev --test --test-runner-bootstrap /path/to/test-runner/bootstrap.js --spec-directory $PWD/spec

Part of the work of this PR was defining the types for the Jasmine object model to clarify the contracts in jasmine-helper.js. As Atom's test runner is an amalgam of Jasmine packages (jasmine, jasmine-json, jasmine-node, jasmine-tagged, and jasmine-focused), this was no easy task. These definitions appear at the top of jasmine-helper.js (formerly jasmine-helper.coffee). Writing this file in JavaScript makes it possible to do this using Flow types.

Originally, I tried to implement this PR by making a "test runner" an object that satisfied the contract of jasmine.Env. In practice, this turned out to be too difficult because so many libraries were adding expando properties onto jasmine that it made it too hard to get a full picture of the API that was required of Jasmine. For example, I was getting failures because failure-tree.coffee was looking for (as far as I could tell) undocumented properties on jasmine.Spec objects. Note that failure-tree.coffee comes from @kevinsawicki's fork of jasmine-node (https://github.com/kevinsawicki/jasmine-node.git), making it tough to trace through. As such, trying to create a jasmine.Reporter that met the needs of Atom's built-in TerminalReporter and AtomReporter objects seemed too difficult. Admittedly, this means that a custom test runner will not be able to take advantage of the default UI that is provided for Atom tests, but for now, I think this is OK.

Note that in jasmine-helper.js, I did not hoist inline require() calls as import statements because at least one of them has important side-effects, so it was unclear as to what was safe to move. I did my best to match Atom's JavaScript style, so I did not use semicolons, put spaces between function and (), etc.

Although jasmine-helper.js does not come close to Flow checking cleanly (Flow can't understand the
CoffeeScript files when tracing through a require() statement), I added an initial .flowconfig
file anyway so that basic features like click-to-symbol work in Nuclide. This also makes it possible
for Flow to report intelligent things about intra-file contracts.

@bolinfest

Copy link
Copy Markdown
Contributor Author

When I run apm test, something seems to lock up on my machine, though that also appears to be the case on master for me. I guess we'll see what Travis-CI says.

@bolinfest

Copy link
Copy Markdown
Contributor Author

@bolinfest
bolinfest force-pushed the bf-alternative-test-runner branch 2 times, most recently from 0a59fa0 to 42059df Compare September 24, 2015 17:06
@bolinfest
bolinfest force-pushed the bf-alternative-test-runner branch 2 times, most recently from f98f32b to b6089fb Compare September 24, 2015 17:13
This introduces support for a `--test-runner-bootstrap` flag to the Atom CLI
that can be used to specify the file passed to `runSpecSuite()` in
`spec-bootstrap.coffee`. Without threading this parameter through to `apm`,
this can be used directly with `atom` as follows:

```
atom --dev --test --test-runner-bootstrap /path/to/test-runner/bootstrap.js --spec-directory $PWD/spec
```

Note that, in this example, `/path/to/test-runner/bootstrap.js` must return a function that
takes no arguments and returns a new object that satisfies the `JasmineEnv` type defined in `jasmine-helper.js`.
The key methods that it needs to support are:

```
addReporter(reporter: JasmineRunner)
execute()
```

Here is a complete example of a possible implementation for `/path/to/test-runner/bootstrap.js`:

```js
'use babel';

class Env {
  _reporters: JasmineRunner[];
  _includedTags: string[];

  constructor() {
    this._testDirectory = atom.getLoadSettings().specDirectory;
    this._reporters = [];
    this._includedTags = [];
    this._runner = new TestRunner(this);
  }

  addReporter(reporter: JasmineRunner) {
    this._reporters.push(reporter);
  }

  execute() {
    this._runner.execute();
  }

  setIncludedTags(tags: string[]): string[] {
    // I doubt anyone relies on the return value, but this is how this method is implemented in
    // https://github.com/atom/jasmine-tagged/blob/master/src/jasmine-tagged.coffee. I think this is
    // an accident due to CoffeeScript.
    return (this._includedTags = tags);
  }

  _reportRunnerStarting() {
    for (let reporter of this._reporters) {
      reporter.reportRunnerStarting(this._runner);
    }
  }

  _reportRunnerResults() {
    for (let reporter of this._reporters) {
      reporter.reportRunnerResults(this._runner);
    }
  }
}

class TestRunner {
  _env: Env;
  _testDirectory: string;

  constructor(env: Env) {
    this._env = env;
    this._testDirectory = atom.getLoadSettings().specDirectory;
  }

  execute() {
    this._env._reportRunnerStarting();
    console.log(`TODO: Run tests in ${this._testDirectory} and report results as they occur.`);
    this._env._reportRunnerResults();
  }

  results(): JasmineNestedResults {
    return {
      passed(): boolean {
        return true;
      },
    };
  }

  specs(): JasmineSpec[] {
    return [];
  }

  topLevelSuites(): JasmineSuite[] {
    return [];
  }
}

module.exports = function() {
  return new Env();
}
```
@bolinfest
bolinfest force-pushed the bf-alternative-test-runner branch from b6089fb to 9d788c4 Compare September 24, 2015 17:14
Comment thread spec/jasmine-helper.js Outdated

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔥 ;

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I was so close to getting all of them...

@nathansobo

Copy link
Copy Markdown
Contributor

Thanks for taking this on. I'm pretty excited about starting to introduce static typing and also a path towards a more sane testing environment that breaks with legacy baggage.

Comment thread src/browser/atom-application.coffee Outdated

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📝 Would be great to doc testRunnerBootstrap in the comment for this method.

@kevinsawicki

Copy link
Copy Markdown
Contributor

@bolinfest this looks like a great start to exploring types.

Should we be installing any Atom packages to make use of the type information, linters, autocomplete, etc.?

Do you have any screenshots/gifs of your setup where these types are used in Atom? Would be great to see what migrating will enable.

Also, since this PR adds a new command line flag (test-runner-bootstrap), could you document in the description of this pull request what it is for and how you plan to use it for what you are building?

@joefitzgerald

Copy link
Copy Markdown
Contributor

Don't suppose you want to bump up to Jasmine 2.x while you're at it? 😁

@bolinfest

Copy link
Copy Markdown
Contributor Author

@joefitzgerald I'm working on building a car rather than a faster horse :P

Comment thread spec/jasmine-helper.js Outdated

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@bolinfest Do you know if there's any documentation-generator tool that uses flow's type annotations to linkify things in the way that Atom's docs system does? If not, we should probably continue to use Atom's regular markdown-style doc format here, rather than these @param blocks.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@maxbrunsfeld I don't know of one yet. But between flow ast [--tokens] and flow get-def, we can probably create a solid annotator for the source code. It looks like the comments aren't included in there.

If you wan't to stick with Atom's existing doc system, I'm not sure how you want this to interop. For example, how would you want to rewrite the following in JSDoc:

###
Section: Accessing the git repository
###

Similarly, it looks like your Markdown usually uses asterisks for bullets that list parameters, but that would double the asterisk in my existing comment.

No matter what, I believe that you're going to need to do something different to extract the comments. Babel might be better than Flow for getting those nodes out of the AST.

@bolinfest

Copy link
Copy Markdown
Contributor Author

@kevinsawicki If you don't want to install all of Nuclide (though you probably should, at least once, to fully understand our reported issues like facebookarchive/nuclide#203, which is why #8217 is so important to us), then I would recommend installing the following packages:

(Also, looking through the landing pages for those packages, is there a good way to store the images for the README.md in the package's repo so that it can be referenced with a relative URL?)

@bolinfest bolinfest changed the title Convert jasmine-helper.coffee to jasmine-helper.js. Introduce an option to run Atom tests with an alternative test runner Sep 24, 2015
@joefitzgerald

Copy link
Copy Markdown
Contributor

@joefitzgerald I'm working on building a car rather than a faster horse :P

Not sure how this has anything to do with updating an outdated dependency (Jasmine) for which this PR directly addresses? Seems like an orthogonal statement. In any case, I'm interpreting your statement as "no".

…ve test runner.

In practice, the TerminalReporter seems to have all sorts of funny requirements due
to a transitive dependency on `failure-tree.coffee`, which is something that only exists
in @kevinsawicki's personal fork of `jasmine-node`: https://github.com/kevinsawicki/jasmine-node.git.

To simplify things, this keeps all of the Jasmine-specific stuff in its own file.
This simplifies the contract of a `--test-runner-bootstrap` such that its only requirement
is to produce an object with an `execute()` method.

It would be nice if the `execute()` method could return a `Promise` and have that handled
properly, though that's a little messy because the `spec-bootstrap.coffee` file is currently
written in CoffeeScript (so no async/await), which is in turn called from `atom-application.coffee`.
@nathansobo

Copy link
Copy Markdown
Contributor

Okay, upon reviewing this, we have a plan that differs a bit from what you've come up with here. The good news is that I'm going to start implementing this myself today, with an aim to land it some time next week. Here are the details we have in mind, which I'm happy to discuss and adjust:

  • Rather than a runtime flag, packages can specify an atomSpecRunner field in their package.json pointing at a path that is resolved relative to the package root.
  • The file corresponding to the atomSpecRunner path exports a single function. When the spec window opens, this function will be invoked with an environment object containing the following parameters:
    • logFile
    • packagePath The absolute path to the package for which we're running specs.
    • createAtomEnvironment This is a function that can be called to construct an instance of the Atom environment (the same type of object that is currently located on global.atom). It may accept parameters to customize environment construction as needed.
  • I will rename the Atom class to AtomEnvironment, and refactor it so it can be instantiated via createAtomEnvironment in a fully-ready state. I'll replace all global references in the Atom environment such that an environment instance can be used locally without assigning it to a global.
  • I will add AtomEnvironment.prototype.reset, which can be used in specs to clear all state from an environment instance as needed between specs.
  • I will adjust our legacy spec runner to consume the same APIs to make sure there's nothing we're doing privately that can't be done by a custom runner.

This should give your runner a blank-slate global environment, while at the same time giving it access to the raw materials needed to setup an environment that mimics Atom. You can instantiate an Atom environment and assign it to global.atom, or you can run unit tests and dependency-inject specific properties on an as-needed basis without polluting the global environment.

We tried running flow, but couldn't get the changed file to type check. Not sure if that's what you were explaining in your description, but I'm not really keen to add type signatures unless we can get flow to pass with them. I think the proposed changes should meet your needs, and we can treat translation to ES6 and employment of static types as an orthogonal concern? Does this work for you?

@bolinfest

Copy link
Copy Markdown
Contributor Author

@nathansobo Thanks for the detailed response! In general, this sounds good. I have only a couple of concerns.

Let's say I'm creating my new test harness in a new package named nuclide-test-harness. The JavaScript file that satisfies your new atomSpecRunner should live in that package. So what would I do in my package.json? I guess I could do:

"atomSpecRunner": "./node_modules/nuclide-test-harness/lib/atom-spec-runner.js",
"devDependencies": {
  "nuclide-test-harness": "0.0.0"
}

which is OK, but a bit verbose, and of course a little dicey because theoretically, nuclide-test-harness could end up in a directory "above" the current one given how npm dedupe works.

Also, we would really like to get away from apm test testing an entire directory. I would like to be able to specify apm test spec/my-spec.js and have it test only that file rather than having to edit my code to add an fdescribe() or something like that. (Or multiple files: apm test spec/1.js spec/2.js.) I don't think that works with what you have spec'd out for "packagePath".

The AtomEnvironment and reset() stuff sounds very cool.

How you use Flow is up to you. No, it won't work today because when you say require('foo'), it parses foo.js to see what it exports. But if it's actually foo.coffee, then it can't do anything. Given that constraint, I don't think it's good to wait until all of Atom core is switched over to JavaScript before using Flow types because 100% conversion may never happen.

Though as I said, there are many cases where you can at least get some signal from intra-file contracts, so maybe if you stick to those, you can still get Flow to work without reporting any errors. Note that you can also suppress Flow errors on an individual basis by specifying the format of the line comment to use for suppression in your .flowconfig. Example:

https://github.com/facebook/nuclide/blob/master/pkg/nuclide/commons/.flowconfig#L12
https://github.com/facebook/nuclide/blob/master/pkg/nuclide/commons/lib/array.js#L19

If Flow fixes the error that you are suppressing in a future version, then using the annotation when there is nothing to suppress becomes a Flow error. It's pretty sweet.

@bolinfest

Copy link
Copy Markdown
Contributor Author

Also, I anticipate being in a transient state where some of our tests are written the old way and some are written the new way. By making it a command line option, I was planning to remap npm test for each of our packages to run two commands:

"scripts": {
  "test": "apm test && atom --dev --test --test-runner-bootstrap ..."
}

Or something like that.

Then once I finished migrating all of my tests, it would just be one or the other.

@nathansobo

Copy link
Copy Markdown
Contributor

So what would I do in my package.json? I guess I could do

Ideally I'd like to resolve that field as if you passed it to require.resolve from the package root. Then you could use 'nuclide-test-runner' rather than a path.

I would like to be able to specify apm test spec/my-spec.js and have it test only that file rather than having to edit my code to add an fdescribe() or something like that.

What about passing the command line arguments through to the test runner as parameters or something so you can handle this however you want?

Also, I anticipate being in a transient state where some of our tests are written the old way and some are written the new way

This one is tricky. I'd really like packages to be able to bundle their own runners without users having to specify command line args. For example, a pretty common practice for me is to launch specs interactively from within Atom... it would be nice if the correct runner were just dealt with automatically.

What about a runLegacySpecs parameter that's exposes Atom's internal runner. Then you can parse command line options yourself and decide when you just want to invoke the legacy runner.

@bolinfest

Copy link
Copy Markdown
Contributor Author

OK, so if it gets passed to require.resolve, I could specify nuclide-test-runner or nuclide-test-runner/lib/apm.js, right? The reason I ask is because I would expect the main export of nuclide-test-runner to be a general programmatic API rather than the Atom-specific one (and I would prefer the user not to have to depend on both nuclide-test-runner and nuclide-test-runner-apm or something like that).

Passing the command line arguments through to the test runner would be good. Maybe even too general? If you could assume that all of the args were paths and then Atom did the work of resolving them to absolute paths before passing them to the runner, then I think that would be sufficient. I think that might even work better for your common practice of launching specs interactively from within Atom. (You could even support right-clicking on a spec and asking Atom to run it!)

I can live without supporting my transient state use case. Thinking about it more, it's probably not worth building a hook for since it isn't something I would expect to exist long-term.

At some point in the future (definitely not required now), it would be nice to come up with a more specific object model for talking to things like atom-reporter.coffee. The tricky bit would be creating an adapter from Jasmine's reporter. As I noted in this PR, I did try that, and it was a bit messy, and more than I wanted to take on right now.

@nathansobo

Copy link
Copy Markdown
Contributor

(You could even support right-clicking on a spec and asking Atom to run it!)

Nice idea. I'll try to think about a more abstract, path-oriented interface for running specs.

At some point in the future (definitely not required now), it would be nice to come up with a more specific object model for talking to things like atom-reporter.coffee.

I'd really like to ditch our current reporter and let people experiment with their own libraries. I'd be keen to eventually provide a recommended reporting mechanism.

I'm starting surgery now. I'll try to keep your concerns in mind and we can iterate until this fits.

@nathansobo nathansobo mentioned this pull request Sep 28, 2015
36 of 38 tasks
@nathansobo

Copy link
Copy Markdown
Contributor

@bolinfest I'm going to close this now that #8968 has been merged. We can address any remaining issues as separate PRs.

@nathansobo nathansobo closed this Oct 19, 2015
@damieng
damieng deleted the bf-alternative-test-runner branch December 9, 2016 00:19
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants