diff --git a/docs/contributing.md b/docs/contributing.md index 0d33ba36..d6b7c74b 100644 --- a/docs/contributing.md +++ b/docs/contributing.md @@ -49,19 +49,17 @@ To send a pull request: ## I'm submitting a PR. How do I run tests? -Assuming you have forked this repo, you can open the `index.html` file in a module's `tests` folder and look at console output to see only tests for that module, or you can run `ospec/bin/ospec` from the command line to run all tests. +After having run `npm install` (a one-time operation), run `npm run test` from the command line to run all tests. While testing, you can modify a test to use `o.only(description, test)` instead of `o(description, test)` if you wish to run only a specific test to speed up your debugging experience. Don't forget to remove the `.only` after you're done! -There is no need to `npm install` anything in order to run the test suite, however NodeJS is required to run the test suite from the command line. You do need to `npm install` if you want to lint or get a code coverage report though. - ## How do I build Mithril.js? If all you're trying to do is run examples in the codebase, you don't need to build Mithril.js, you can just open the various html files and things should just work. -To generate the bundled file for testing, run `npm run dev` from the command line. To generate the minified file, run `npm run build`. There is no need to `npm install` anything, but NodeJS is required to run the build scripts. +To generate the bundled file for testing, run `npm run dev` from the command line. To generate the minified file, run `npm run build`. diff --git a/docs/nav-methods.md b/docs/nav-methods.md index b553c77e..6d15f06e 100644 --- a/docs/nav-methods.md +++ b/docs/nav-methods.md @@ -14,4 +14,4 @@ - Optional - [Stream](stream.md) - Tooling - - [Ospec](https://github.com/MithrilJS/mithril.js/blob/master/ospec) + - [Ospec](https://github.com/MithrilJS/ospec) diff --git a/ospec/LICENSE b/ospec/LICENSE deleted file mode 100644 index 2aae0f1e..00000000 --- a/ospec/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2017 Leo Horie - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/ospec/README.md b/ospec/README.md deleted file mode 100644 index b2fa93b1..00000000 --- a/ospec/README.md +++ /dev/null @@ -1,667 +0,0 @@ -ospec [![npm Version](https://img.shields.io/npm/v/ospec.svg)](https://www.npmjs.com/package/ospec) [![npm License](https://img.shields.io/npm/l/ospec.svg)](https://www.npmjs.com/package/ospec) -===== - -[About](#about) | [Usage](#usage) | [CLI](#command-line-interface) | [API](#api) | [Goals](#goals) - -Noiseless testing framework - -## About - -- ~360 LOC including the CLI runner -- terser and faster test code than with mocha, jasmine or tape -- test code reads like bullet points -- assertion code follows [SVO](https://en.wikipedia.org/wiki/Subject%E2%80%93verb%E2%80%93object) structure in present tense for terseness and readability -- supports: - - test grouping - - assertions - - spies - - `equals`, `notEquals`, `deepEquals` and `notDeepEquals` assertion types - - `before`/`after`/`beforeEach`/`afterEach` hooks - - test exclusivity (i.e. `.only`) - - async tests and hooks -- explicitly regulates test-space configuration to encourage focus on testing, and to provide uniform test suites across projects - -## Usage - -### Single tests - -Both tests and assertions are declared via the `o` function. Tests should have a description and a body function. A test may have one or more assertions. Assertions should appear inside a test's body function and compare two values. - -```javascript -var o = require("ospec") - -o("addition", function() { - o(1 + 1).equals(2) -}) -o("subtraction", function() { - o(1 - 1).notEquals(2) -}) -``` - -Assertions may have descriptions: - -```javascript -o("addition", function() { - o(1 + 1).equals(2)("addition should work") - - /* in ES6, the following syntax is also possible - o(1 + 1).equals(2) `addition should work` - */ -}) -/* for a failing test, an assertion with a description outputs this: - -addition should work - -1 should equal 2 - -Error - at stacktrace/goes/here.js:1:1 -*/ -``` - -### Grouping tests - -Tests may be organized into logical groups using `o.spec` - -```javascript -o.spec("math", function() { - o("addition", function() { - o(1 + 1).equals(2) - }) - o("subtraction", function() { - o(1 - 1).notEquals(2) - }) -}) -``` - -Group names appear as a breadcrumb trail in test descriptions: `math > addition: 2 should equal 2` - -### Nested test groups - -Groups can be nested to further organize test groups. Note that tests cannot be nested inside other tests. - -```javascript -o.spec("math", function() { - o.spec("arithmetics", function() { - o("addition", function() { - o(1 + 1).equals(2) - }) - o("subtraction", function() { - o(1 - 1).notEquals(2) - }) - }) -}) -``` - -### Callback test - -The `o.spy()` method can be used to create a stub function that keeps track of its call count and received parameters - -```javascript -// code to be tested -function call(cb, arg) {cb(arg)} - -// test suite -var o = require("ospec") - -o.spec("call()", function() { - o("works", function() { - var spy = o.spy() - call(spy, 1) - - o(spy.callCount).equals(1) - o(spy.args[0]).equals(1) - o(spy.calls[0]).deepEquals([1]) - }) -}) -``` - -A spy can also wrap other functions, like a decorator: - -```javascript -// code to be tested -var count = 0 -function inc() { - count++ -} - -// test suite -var o = require("ospec") - -o.spec("call()", function() { - o("works", function() { - var spy = o.spy(inc) - spy() - - o(count).equals(1) - }) -}) - -``` - -### Asynchronous tests - -If a test body function declares a named argument, the test is assumed to be asynchronous, and the argument is a function that must be called exactly one time to signal that the test has completed. As a matter of convention, this argument is typically named `done`. - -```javascript -o("setTimeout calls callback", function(done) { - setTimeout(done, 10) -}) -``` - -Alternativly you can return a promise or even use an async function in tests: - -```javascript -o("promise test", function() { - return new Promise(function(resolve) { - setTimeout(resolve, 10) - }) -}) -``` - -```javascript -o("promise test", async function() { - await someOtherAsyncFunction() -}) -``` - -#### Timeout delays - -By default, asynchronous tests time out after 200ms. You can change that default for the current test suite and -its children by using the `o.specTimeout(delay)` function. - -```javascript -o.spec("a spec that must timeout quickly", function(done, timeout) { - // wait 20ms before bailing out of the tests of this suite and - // its descendants - o.specTimeout(20) - o("some test", function(done) { - setTimeout(done, 10) // this will pass - }) - - o.spec("a child suite where the delay also applies", function () { - o("some test", function(done) { - setTimeout(done, 30) // this will time out. - }) - }) -}) -o.spec("a spec that uses the default delay", function() { - // ... -}) -``` - -This can also be changed on a per-test basis using the `o.timeout(delay)` function from within a test: - -```javascript -o("setTimeout calls callback", function(done, timeout) { - o.timeout(500) // wait 500ms before bailing out of the test - - setTimeout(done, 300) -}) -``` - -Note that the `o.timeout` function call must be the first statement in its test. It also works with Promise-returning tests: - -```javascript -o("promise test", function() { - o.timeout(1000) - return someOtherAsyncFunctionThatTakes900ms() -}) -``` - -```javascript -o("promise test", async function() { - o.timeout(1000) - await someOtherAsyncFunctionThatTakes900ms() -}) -``` - -Asynchronous tests generate an assertion that succeeds upon calling `done` or fails on timeout with the error message `async test timed out`. - -### `before`, `after`, `beforeEach`, `afterEach` hooks - -These hooks can be declared when it's necessary to setup and clean up state for a test or group of tests. The `before` and `after` hooks run once each per test group, whereas the `beforeEach` and `afterEach` hooks run for every test. - -```javascript -o.spec("math", function() { - var acc - o.beforeEach(function() { - acc = 0 - }) - - o("addition", function() { - acc += 1 - - o(acc).equals(1) - }) - o("subtraction", function() { - acc -= 1 - - o(acc).equals(-1) - }) -}) -``` - -It's strongly recommended to ensure that `beforeEach` hooks always overwrite all shared variables, and avoid `if/else` logic, memoization, undo routines inside `beforeEach` hooks. - -### Asynchronous hooks - -Like tests, hooks can also be asynchronous. Tests that are affected by asynchronous hooks will wait for the hooks to complete before running. - -```javascript -o.spec("math", function() { - var acc - o.beforeEach(function(done) { - setTimeout(function() { - acc = 0 - done() - }) - }) - - // tests only run after async hooks complete - o("addition", function() { - acc += 1 - - o(acc).equals(1) - }) - o("subtraction", function() { - acc -= 1 - - o(acc).equals(-1) - }) -}) -``` - -### Running only some tests - -One or more tests can be temporarily made to run exclusively by calling `o.only()` instead of `o`. This is useful when troubleshooting regressions, to zero-in on a failing test, and to avoid saturating console log w/ irrelevant debug information. - -```javascript -o.spec("math", function() { - // will not run - o("addition", function() { - o(1 + 1).equals(2) - }) - - // this test will be run, regardless of how many groups there are - o.only("subtraction", function() { - o(1 - 1).notEquals(2) - }) - - // will not run - o("multiplication", function() { - o(2 * 2).equals(4) - }) - - // this test will be run, regardless of how many groups there are - o.only("division", function() { - o(6 / 2).notEquals(2) - }) -}) -``` - -### Running the test suite - -```javascript -// define a test -o("addition", function() { - o(1 + 1).equals(2) -}) - -// run the suite -o.run() -``` - -### Running test suites concurrently - -The `o.new()` method can be used to create new instances of ospec, which can be run in parallel. Note that each instance will report independently, and there's no aggregation of results. - -```javascript -var _o = o.new('optional name') -_o("a test", function() { - _o(1).equals(1) -}) -_o.run() -``` - -## Command Line Interface - -Create a script in your package.json: -``` - "scripts": { - "test": "ospec", - ... - } -``` -...and run it from the command line: - -``` -$ npm test -``` - -**NOTE:** `o.run()` is automatically called by the cli - no need to call it in your test code. - -### CLI Options - -Running ospec without arguments is equivalent to running `ospec '**/tests/**/*.js'`. In english, this tells ospec to evaluate all `*.js` files in any sub-folder named `tests/` (the `node_modules` folder is always excluded). - -If you wish to change this behavior, just provide one or more glob match patterns: - -``` -ospec '**/spec/**/*.js' '**/*.spec.js' -``` - -You can also provide ignore patterns (note: always add `--ignore` AFTER match patterns): - -``` -ospec --ignore 'folder1/**' 'folder2/**' -``` - -Finally, you may choose to load files or modules before any tests run (**note:** always add `--require` AFTER match patterns): - -``` -ospec --require esm -``` - -Here's an example of mixing them all together: - -``` -ospec '**/*.test.js' --ignore 'folder1/**' --require esm ./my-file.js -``` - -### Run ospec directly from the command line: - -ospec comes with an executable named `ospec`. npm auto-installs local binaries to `./node_modules/.bin/`. You can run ospec by running `./node_modules/.bin/ospec` from your project root, but there are more convenient methods to do so that we will soon describe. - -ospec doesn't work when installed globally (`npm install -g`). Using global scripts is generally a bad idea since you can end up with different, incompatible versions of the same package installed locally and globally. - -Here are different ways of running ospec from the command line. This knowledge applies to not just ospec, but any locally installed npm binary. - -#### npx - -If you're using a recent version of npm (v5+), you can use run `npx ospec` from your project folder. - -#### npm-run - -If you're using a recent version of npm (v5+), you can use run `npx ospec` from your project folder. - -Otherwise, to work around this limitation, you can use [`npm-run`](https://www.npmjs.com/package/npm-run) which enables one to run the binaries of locally installed packages. - -``` -npm install npm-run -g -``` - -Then, from a project that has ospec installed as a (dev) dependency: - -``` -npm-run ospec -``` - -#### PATH - -If you understand how your system's PATH works (e.g. for [OSX](https://coolestguidesontheplanet.com/add-shell-path-osx/)), then you can add the following to your PATH... - -``` -export PATH=./node_modules/.bin:$PATH -``` - -...and you'll be able to run `ospec` without npx, npm, etc. This one-time setup will also work with other binaries across all your node projects, as long as you run binaries from the root of your projects. - ---- - -## API - -Square brackets denote optional arguments - -### void o.spec(String title, Function tests) - -Defines a group of tests. Groups are optional - ---- - -### void o(String title, Function([Function done [, Function timeout]]) assertions) - -Defines a test. - -If an argument is defined for the `assertions` function, the test is deemed to be asynchronous, and the argument is required to be called exactly one time. - ---- - -### Assertion o(any value) - -Starts an assertion. There are six types of assertion: `equals`, `notEquals`, `deepEquals`, `notDeepEquals`, `throws`, `notThrows`. - -Assertions have this form: - -```javascript -o(actualValue).equals(expectedValue) -``` - -As a matter of convention, the actual value should be the first argument and the expected value should be the second argument in an assertion. - -Assertions can also accept an optional description curried parameter: - -```javascript -o(actualValue).equals(expectedValue)("this is a description for this assertion") -``` - -Assertion descriptions can be simplified using ES6 tagged template string syntax: - -```javascript -o(actualValue).equals(expectedValue) `this is a description for this assertion` -``` - -#### Function(String description) o(any value).equals(any value) - -Asserts that two values are strictly equal (`===`) - -#### Function(String description) o(any value).notEquals(any value) - -Asserts that two values are strictly not equal (`!==`) - -#### Function(String description) o(any value).deepEquals(any value) - -Asserts that two values are recursively equal - -#### Function(String description) o(any value).notDeepEquals(any value) - -Asserts that two values are not recursively equal - -#### Function(String description) o(Function fn).throws(Object constructor) - -Asserts that a function throws an instance of the provided constructo - -#### Function(String description) o(Function fn).throws(String message) - -Asserts that a function throws an Error with the provided message - -#### Function(String description) o(Function fn).notThrows(Object constructor) - -Asserts that a function does not throw an instance of the provided constructor - -#### Function(String description) o(Function fn).notThrows(String message) - -Asserts that a function does not throw an Error with the provided message - ---- - -### void o.before(Function([Function done [, Function timeout]]) setup) - -Defines code to be run at the beginning of a test group - -If an argument is defined for the `setup` function, this hook is deemed to be asynchronous, and the argument is required to be called exactly one time. - ---- - -### void o.after(Function([Function done [, Function timeout]]) teardown) - -Defines code to be run at the end of a test group - -If an argument is defined for the `teardown` function, this hook is deemed to be asynchronous, and the argument is required to be called exactly one time. - ---- - -### void o.beforeEach(Function([Function done [, Function timeout]]) setup) - -Defines code to be run before each test in a group - -If an argument is defined for the `setup` function, this hook is deemed to be asynchronous, and the argument is required to be called exactly one time. - ---- - -### void o.afterEach(Function([Function done [, Function timeout]]) teardown) - -Defines code to be run after each test in a group - -If an argument is defined for the `teardown` function, this hook is deemed to be asynchronous, and the argument is required to be called exactly one time. - ---- - -### void o.only(String title, Function([Function done [, Function timeout]]) assertions) - -Declares that only a single test should be run, instead of all of them - ---- - -### Function o.spy([Function fn]) - -Returns a function that records the number of times it gets called, and its arguments - -#### Number o.spy().callCount - -The number of times the function has been called - -#### Array o.spy().args - -The arguments that were passed to the function in the last time it was called - ---- - -### void o.run([Function reporter]) - -Runs the test suite. By default passing test results are printed using -`console.log` and failing test results are printed using `console.error`. - -If you have custom continuous integration needs then you can use a -reporter to process [test result data](#result-data) yourself. - -If running in Node.js, ospec will call `process.exit` after reporting -results by default. If you specify a reporter, ospec will not do this -and allow your reporter to respond to results in its own way. - - ---- - -### Number o.report(results) - -The default reporter used by `o.run()` when none are provided. Returns the number of failures, doesn't exit Node.js by itself. It expects an array of [test result data](#result-data) as argument. - ---- - -### Function o.new() - -Returns a new instance of ospec. Useful if you want to run more than one test suite concurrently - -```javascript -var $o = o.new() -$o("a test", function() { - $o(1).equals(1) -}) -$o.run() -``` - ---- - -## Result data - -Test results are available by reference for integration purposes. You -can use custom reporters in `o.run()` to process these results. - -```javascript -o.run(function(results) { - // results is an array - - results.forEach(function(result) { - // ... - }) -}) -``` - ---- - -### Boolean|Null result.pass - -- `true` if the assertion passed. -- `false` if the assertion failed. -- `null` if the assertion was incomplete (`o("partial assertion) // and that's it`). - ---- - -### Error result.error - -The `Error` object explaining the reason behind a failure. If the assertion failed, the stack will point to the actuall error. If the assertion did pass or was incomplete, this field is identical to `result.testError`. - ---- - -### Error result.testError - -An `Error` object whose stack points to the test definition that wraps the assertion. Useful as a fallback because in some async cases the main may not point to test code. - ---- - -### String result.message - -If an exception was thrown inside the corresponding test, this will equal that Error's `message`. Otherwise, this will be a preformatted message in [SVO form](https://en.wikipedia.org/wiki/Subject%E2%80%93verb%E2%80%93object). More specifically, `${subject}\n${verb}\n${object}`. - -As an example, the following test's result message will be `"false\nshould equal\ntrue"`. - -```javascript -o.spec("message", function() { - o(false).equals(true) -}) -``` - -If you specify an assertion description, that description will appear two lines above the subject. - -```javascript -o.spec("message", function() { - o(false).equals(true)("Candyland") // result.message === "Candyland\n\nfalse\nshould equal\ntrue" -}) -``` - ---- - -### String result.context - -A `>`-separated string showing the structure of the test specification. -In the below example, `result.context` would be `testing > rocks`. - -```javascript -o.spec("testing", function() { - o.spec("rocks", function() { - o(false).equals(true) - }) -}) -``` - - - ---- - -## Goals - -- Do the most common things that the mocha/chai/sinon triad does without having to install 3 different libraries and several dozen dependencies -- Disallow configuration in test-space: - - Disallow ability to pick between API styles (BDD/TDD/Qunit, assert/should/expect, etc) - - Disallow ability to add custom assertion types - - Provide a default simple reporter -- Make assertion code terse, readable and self-descriptive -- Have as few assertion types as possible for a workable usage pattern - -Explicitly disallowing modularity and configuration in test-space has a few benefits: - -- tests always look the same, even across different projects and teams -- single source of documentation for entire testing API -- no need to hunt down plugins to figure out what they do, especially if they replace common JavaScript idioms with fuzzy spoken language constructs (e.g. what does `.is()` do?) -- no need to pollute project-space with ad-hoc configuration code -- discourages side-tracking and yak-shaving diff --git a/ospec/bin/ospec b/ospec/bin/ospec deleted file mode 100755 index 80a21bf1..00000000 --- a/ospec/bin/ospec +++ /dev/null @@ -1,45 +0,0 @@ -#!/usr/bin/env node -"use strict" - -var o = require("../ospec") -var path = require("path") -var glob = require("glob") - - -function parseArgs(argv) { - argv = ["--globs"].concat(argv.slice(2)) - var args = {} - var name - argv.forEach(function(arg) { - if ((/^--/).test(arg)) { - name = arg.substr(2) - args[name] = args[name] || [] - } else { - args[name].push(arg) - } - }) - return args -} - - -var args = parseArgs(process.argv) -var globList = args.globs && args.globs.length ? args.globs : ["**/tests/**/*.js"] -var ignore = ["**/node_modules/**"].concat(args.ignore || []) -var cwd = process.cwd() - -if (args.require) { - args.require.forEach(function(module) { - // eslint-disable-next-line global-require - if (module) require(require.resolve(module, {paths: [cwd]})) - }) -} - -var pending = globList.length -globList.forEach(function(globPattern) { - glob(globPattern, {ignore: ignore}) - .on("match", function(fileName) { require(path.join(cwd, fileName)) }) // eslint-disable-line global-require - .on("error", function(e) { console.error(e) }) - .on("end", function() { if (--pending === 0) o.run()}) -}); - -process.on("unhandledRejection", function(e) { console.error("Uncaught (in promise) " + e.stack) }) diff --git a/ospec/bin/ospec.cmd b/ospec/bin/ospec.cmd deleted file mode 100644 index bd917c4a..00000000 --- a/ospec/bin/ospec.cmd +++ /dev/null @@ -1 +0,0 @@ -node ospec diff --git a/ospec/change-log.md b/ospec/change-log.md deleted file mode 100644 index dbf31977..00000000 --- a/ospec/change-log.md +++ /dev/null @@ -1,110 +0,0 @@ -# Change log for ospec - -- [Upcoming](#upcoming) -- [4.0.1](#401) -- [4.0.0](#400) -- [3.1.0](#310) -- [3.0.1](#301) -- [3.0.0](#300) -- [2.1.0](#210) -- [2.0.0](#200) -- [1.4.1](#141) -- [1.4.0](#140) -- [1.3 and earlier](#13-and-earlier) - -### Upcoming... - -### 4.0.1 -_2019-08-18_ - -- Fix `require` with relative paths - -### 4.0.0 -_2019-07-24_ - -- Pull ESM support out - -### 3.1.0 -_2019-02-07_ - -- ospec: Test results now include `.message` and `.context` regardless of whether the test passed or failed. (#2227 @robertakarobin) - -- Add `spy.calls` array property to get the `this` and `arguments` values for any arbitrary call. (#2221 [@dead-claudia](https://github.com/dead-claudia)) -- Added `.throws` and `.notThrows` assertions to ospec. (#2255 @robertakarobin) -- Update `glob` dependency. - -### 3.0.1 -_2018-06-30_ - -#### Bug fix -- Move `glob` from `devDependencies` to `dependencies`, fix the test runner ([#2186](https://github.com/MithrilJS/mithril.js/pull/2186) [@porsager](https://github.com/porsager) - -### 3.0.0 -_2018-06-26_ - -#### Breaking -- Better input checking to prevent misuses of the library. Misues of the library will now throw errors, rather than report failures. This may uncover bugs in your test suites. Since it is potentially a disruptive update this change triggers a semver major bump. ([#2167](https://github.com/MithrilJS/mithril.js/pull/2167)) -- Change the reserved character for hooks and test suite meta-information from `"__"` to `"\x01"`. Tests whose name start with `"\0x01"` will be rejected ([#2167](https://github.com/MithrilJS/mithril.js/pull/2167)) - -#### Features -- Give async timeout a stack trace that points to the problematic test ([#2154](https://github.com/MithrilJS/mithril.js/pull/2154) [@gilbert](github.com/gilbert), [#2167](https://github.com/MithrilJS/mithril.js/pull/2167)) -- deprecate the `timeout` parameter in async tests in favour of `o.timeout()` for setting the timeout delay. The `timeout` parameter still works for v3, and will be removed in v4 ([#2167](https://github.com/MithrilJS/mithril.js/pull/2167)) -- add `o.defaultTimeout()` for setting the the timeout delay for the current spec and its children ([#2167](https://github.com/MithrilJS/mithril.js/pull/2167)) -- adds the possibility to select more than one test with o.only ([#2171](https://github.com/MithrilJS/mithril.js/pull/2171)) - -#### Bug fixes -- Detect duplicate calls to `done()` properly [#2162](https://github.com/MithrilJS/mithril.js/issues/2162) ([#2167](https://github.com/MithrilJS/mithril.js/pull/2167)) -- Don't try to report internal errors as assertion failures, throw them instead ([#2167](https://github.com/MithrilJS/mithril.js/pull/2167)) -- Don't ignore, silently, tests whose name start with the test suite meta-information sequence (was `"__"` up to this version) ([#2167](https://github.com/MithrilJS/mithril.js/pull/2167)) -- Fix the `done()` call detection logic [#2158](https://github.com/MithrilJS/mithril.js/issues/2158) and assorted fixes (accept non-English names, tolerate comments) ([#2167](https://github.com/MithrilJS/mithril.js/pull/2167)) -- Catch exceptions thrown in synchronous tests and report them as assertion failures ([#2171](https://github.com/MithrilJS/mithril.js/pull/2171)) -- Fix a stack overflow when using `o.only()` with a large test suite ([#2171](https://github.com/MithrilJS/mithril.js/pull/2171)) - -### 2.1.0 -_2018-05-25_ - -#### Features -- Pinpoint the `o.only()` call site ([#2157](https://github.com/MithrilJS/mithril.js/pull/2157)) -- Improved wording, spacing and color-coding of report messages and errors ([#2147](https://github.com/MithrilJS/mithril.js/pull/2147), [@maranomynet](https://github.com/maranomynet)) - -#### Bug fixes -- Convert the exectuable back to plain ES5 [#2160](https://github.com/MithrilJS/mithril.js/issues/2160) ([#2161](https://github.com/MithrilJS/mithril.js/pull/2161)) - - -### 2.0.0 -_2018-05-09_ - -- Added `--require` feature to the ospec executable ([#2144](https://github.com/MithrilJS/mithril.js/pull/2144), [@gilbert](https://github.com/gilbert)) -- In Node.js, ospec only uses colors when the output is sent to a terminal ([#2143](https://github.com/MithrilJS/mithril.js/pull/2143)) -- the CLI runner now accepts globs as arguments ([#2141](https://github.com/MithrilJS/mithril.js/pull/2141), [@maranomynet](https://github.com/maranomynet)) -- Added support for custom reporters ([#2020](https://github.com/MithrilJS/mithril.js/pull/2020), [@zyrolasting](https://github.com/zyrolasting)) -- Make ospec more [Flems](https://flems.io)-friendly ([#2034](https://github.com/MithrilJS/mithril.js/pull/2034)) - - Works either as a global or in CommonJS environments - - the o.run() report is always printed asynchronously (it could be synchronous before if none of the tests were async). - - Properly point to the assertion location of async errors [#2036](https://github.com/MithrilJS/mithril.js/issues/2036) - - expose the default reporter as `o.report(results)` - - Don't try to access the stack traces in IE9 - - - -### 1.4.1 -_2018-05-03_ - -- Identical to v1.4.0, but with UNIX-style line endings so that BASH is happy. - - - -### 1.4.0 -_2017-12-01_ - -- Added support for async functions and promises in tests ([#1928](https://github.com/MithrilJS/mithril.js/pull/1928), [@StephanHoyer](https://github.com/StephanHoyer)) -- Error handling for async tests with `done` callbacks supports error as first argument ([#1928](https://github.com/MithrilJS/mithril.js/pull/1928)) -- Error messages which include newline characters do not swallow the stack trace [#1495](https://github.com/MithrilJS/mithril.js/issues/1495) ([#1984](https://github.com/MithrilJS/mithril.js/pull/1984), [@RodericDay](https://github.com/RodericDay)) - - - -### 1.3 and earlier - -- Log using util.inspect to show object content instead of "[object Object]" ([#1661](https://github.com/MithrilJS/mithril.js/issues/1661), [@porsager](https://github.com/porsager)) -- Shell command: Ignore hidden directories and files ([#1855](https://github.com/MithrilJS/mithril.js/pull/1855) [@pdfernhout)](https://github.com/pdfernhout)) -- Library: Add the possibility to name new test suites ([#1529](https://github.com/MithrilJS/mithril.js/pull/1529)) diff --git a/ospec/ospec.js b/ospec/ospec.js deleted file mode 100644 index efda3c88..00000000 --- a/ospec/ospec.js +++ /dev/null @@ -1,397 +0,0 @@ -"use strict" -;(function(m) { -if (typeof module !== "undefined") module["exports"] = m() -else window.o = m() -})(function init(name) { - console.warn( - "Please switch to the `ospec` package to remove this warning and see " + - "the most recent features. Using the `ospec` bundled within Mithril.js " + - "is deprecated, and it will be removed in the next major release." - ) - - var spec = {}, subjects = [], results, only = [], ctx = spec, start, stack = 0, nextTickish, hasProcess = typeof process === "object", hasOwn = ({}).hasOwnProperty - var ospecFileName = getStackName(ensureStackTrace(new Error), /[\/\\](.*?):\d+:\d+/), timeoutStackName - var globalTimeout = noTimeoutRightNow - var currentTestError = null - if (name != null) spec[name] = ctx = {} - - try {throw new Error} catch (e) { - var ospecFileName = e.stack && (/[\/\\](.*?):\d+:\d+/).test(e.stack) ? e.stack.match(/[\/\\](.*?):\d+:\d+/)[1] : null - } - function o(subject, predicate) { - if (predicate === undefined) { - if (!isRunning()) throw new Error("Assertions should not occur outside test definitions.") - return new Assert(subject) - } else { - if (isRunning()) throw new Error("Test definitions and hooks shouldn't be nested. To group tests, use 'o.spec()'.") - subject = String(subject) - if (subject.charCodeAt(0) === 1) throw new Error("test names starting with '\\x01' are reserved for internal use.") - ctx[unique(subject)] = new Task(predicate, ensureStackTrace(new Error)) - } - } - o.before = hook("\x01before") - o.after = hook("\x01after") - o.beforeEach = hook("\x01beforeEach") - o.afterEach = hook("\x01afterEach") - o.specTimeout = function (t) { - if (isRunning()) throw new Error("o.specTimeout() can only be called before o.run().") - if (hasOwn.call(ctx, "\x01specTimeout")) throw new Error("A default timeout has already been defined in this context.") - if (typeof t !== "number") throw new Error("o.specTimeout() expects a number as argument.") - ctx["\x01specTimeout"] = t - } - o.new = init - o.spec = function(subject, predicate) { - var parent = ctx - ctx = ctx[unique(subject)] = {} - predicate() - ctx = parent - } - o.only = function(subject, predicate, silent) { - if (!silent) console.log( - highlight("/!\\ WARNING /!\\ o.only() mode") + "\n" + o.cleanStackTrace(ensureStackTrace(new Error)) + "\n", - cStyle("red"), "" - ) - only.push(predicate) - o(subject, predicate) - } - o.spy = function(fn) { - var spy = function() { - spy.this = this - spy.args = [].slice.call(arguments) - spy.calls.push({this: this, args: spy.args}) - spy.callCount++ - - if (fn) return fn.apply(this, arguments) - } - if (fn) - Object.defineProperties(spy, { - length: {value: fn.length}, - name: {value: fn.name} - }) - spy.args = [] - spy.calls = [] - spy.callCount = 0 - return spy - } - o.cleanStackTrace = function(error) { - // For IE 10+ in quirks mode, and IE 9- in any mode, errors don't have a stack - if (error.stack == null) return "" - var i = 0, header = error.message ? error.name + ": " + error.message : error.name, stack - // some environments add the name and message to the stack trace - if (error.stack.indexOf(header) === 0) { - stack = error.stack.slice(header.length).split(/\r?\n/) - stack.shift() // drop the initial empty string - } else { - stack = error.stack.split(/\r?\n/) - } - if (ospecFileName == null) return stack.join("\n") - // skip ospec-related entries on the stack - while (stack[i] != null && stack[i].indexOf(ospecFileName) !== -1) i++ - // now we're in user code (or past the stack end) - return stack[i] - } - o.timeout = function(n) { - globalTimeout(n) - } - o.run = function(reporter) { - results = [] - start = new Date - test(spec, [], [], new Task(function() { - setTimeout(function () { - timeoutStackName = getStackName({stack: o.cleanStackTrace(ensureStackTrace(new Error))}, /([\w \.]+?:\d+:\d+)/) - if (typeof reporter === "function") reporter(results) - else { - var errCount = o.report(results) - if (hasProcess && errCount !== 0) process.exit(1) // eslint-disable-line no-process-exit - } - }) - }, null), 200 /*default timeout delay*/) - - function test(spec, pre, post, finalize, defaultDelay) { - if (hasOwn.call(spec, "\x01specTimeout")) defaultDelay = spec["\x01specTimeout"] - pre = [].concat(pre, spec["\x01beforeEach"] || []) - post = [].concat(spec["\x01afterEach"] || [], post) - series([].concat(spec["\x01before"] || [], Object.keys(spec).reduce(function(tasks, key) { - if (key.charCodeAt(0) !== 1 && (only.length === 0 || only.indexOf(spec[key].fn) !== -1 || !(spec[key] instanceof Task))) { - tasks.push(new Task(function(done) { - o.timeout(Infinity) - subjects.push(key) - var pop = new Task(function pop() {subjects.pop(), done()}, null) - if (spec[key] instanceof Task) series([].concat(pre, spec[key], post, pop), defaultDelay) - else test(spec[key], pre, post, pop, defaultDelay) - }, null)) - } - return tasks - }, []), spec["\x01after"] || [], finalize), defaultDelay) - } - - function series(tasks, defaultDelay) { - var cursor = 0 - next() - - function next() { - if (cursor === tasks.length) return - - var task = tasks[cursor++] - var fn = task.fn - currentTestError = task.err - var timeout = 0, delay = defaultDelay, s = new Date - var current = cursor - var arg - - globalTimeout = setDelay - - var isDone = false - // public API, may only be called once from use code (or after returned Promise resolution) - function done(err) { - if (!isDone) isDone = true - else throw new Error("'" + arg + "()' should only be called once.") - if (timeout === undefined) console.warn("# elapsed: " + Math.round(new Date - s) + "ms, expected under " + delay + "ms\n" + o.cleanStackTrace(task.err)) - finalizeAsync(err) - } - // for internal use only - function finalizeAsync(err) { - if (err == null) { - if (task.err != null) succeed(new Assert) - } else { - if (err instanceof Error) fail(new Assert, err.message, err) - else fail(new Assert, String(err), null) - } - if (timeout !== undefined) timeout = clearTimeout(timeout) - if (current === cursor) next() - } - function startTimer() { - timeout = setTimeout(function() { - timeout = undefined - finalizeAsync("async test timed out after " + delay + "ms") - }, Math.min(delay, 2147483647)) - } - function setDelay (t) { - if (typeof t !== "number") throw new Error("timeout() and o.timeout() expect a number as argument.") - delay = t - } - if (fn.length > 0) { - var body = fn.toString() - arg = (body.match(/^(.+?)(?:\s|\/\*[\s\S]*?\*\/|\/\/.*?\n)*=>/) || body.match(/\((?:\s|\/\*[\s\S]*?\*\/|\/\/.*?\n)*(.+?)(?:\s|\/\*[\s\S]*?\*\/|\/\/.*?\n)*[,\)]/) || []).pop() - if (body.indexOf(arg) === body.lastIndexOf(arg)) { - var e = new Error - e.stack = "'" + arg + "()' should be called at least once\n" + o.cleanStackTrace(task.err) - throw e - } - try { - fn(done, setDelay) - } - catch (e) { - if (task.err != null) finalizeAsync(e) - // The errors of internal tasks (which don't have an Err) are ospec bugs and must be rethrown. - else throw e - } - if (timeout === 0) { - startTimer() - } - } else { - try{ - var p = fn() - if (p && p.then) { - startTimer() - p.then(function() { done() }, done) - } else { - nextTickish(next) - } - } catch (e) { - if (task.err != null) finalizeAsync(e) - // The errors of internal tasks (which don't have an Err) are ospec bugs and must be rethrown. - else throw e - } - } - globalTimeout = noTimeoutRightNow - } - } - } - function unique(subject) { - if (hasOwn.call(ctx, subject)) { - console.warn("A test or a spec named '" + subject + "' was already defined.") - while (hasOwn.call(ctx, subject)) subject += "*" - } - return subject - } - function hook(name) { - return function(predicate) { - if (ctx[name]) throw new Error(name.slice(1) + " should be defined outside of a loop or inside a nested test group.") - ctx[name] = new Task(predicate, ensureStackTrace(new Error)) - } - } - - define("equals", "should equal", function(a, b) {return a === b}) - define("notEquals", "should not equal", function(a, b) {return a !== b}) - define("deepEquals", "should deep equal", deepEqual) - define("notDeepEquals", "should not deep equal", function(a, b) {return !deepEqual(a, b)}) - define("throws", "should throw a", throws) - define("notThrows", "should not throw a", function(a, b) {return !throws(a, b)}) - - function isArguments(a) { - if ("callee" in a) { - for (var i in a) if (i === "callee") return false - return true - } - } - function deepEqual(a, b) { - if (a === b) return true - if (a === null ^ b === null || a === undefined ^ b === undefined) return false // eslint-disable-line no-bitwise - if (typeof a === "object" && typeof b === "object") { - var aIsArgs = isArguments(a), bIsArgs = isArguments(b) - if (a.constructor === Object && b.constructor === Object && !aIsArgs && !bIsArgs) { - for (var i in a) { - if ((!(i in b)) || !deepEqual(a[i], b[i])) return false - } - for (var i in b) { - if (!(i in a)) return false - } - return true - } - if (a.length === b.length && (a instanceof Array && b instanceof Array || aIsArgs && bIsArgs)) { - var aKeys = Object.getOwnPropertyNames(a), bKeys = Object.getOwnPropertyNames(b) - if (aKeys.length !== bKeys.length) return false - for (var i = 0; i < aKeys.length; i++) { - if (!hasOwn.call(b, aKeys[i]) || !deepEqual(a[aKeys[i]], b[aKeys[i]])) return false - } - return true - } - if (a instanceof Date && b instanceof Date) return a.getTime() === b.getTime() - if (typeof Buffer === "function" && a instanceof Buffer && b instanceof Buffer) { - for (var i = 0; i < a.length; i++) { - if (a[i] !== b[i]) return false - } - return true - } - if (a.valueOf() === b.valueOf()) return true - } - return false - } - function throws(a, b){ - try{ - a() - }catch(e){ - if(typeof b === "string"){ - return (e.message === b) - }else{ - return (e instanceof b) - } - } - return false - } - - function isRunning() {return results != null} - function Assert(value) { - this.value = value - this.i = results.length - results.push({pass: null, context: "", message: "Incomplete assertion in the test definition starting at...", error: currentTestError, testError: currentTestError}) - } - function Task(fn, err) { - this.fn = fn - this.err = err - } - function define(name, verb, compare) { - Assert.prototype[name] = function assert(value) { - var self = this - var message = serialize(self.value) + "\n " + verb + "\n" + serialize(value) - if (compare(self.value, value)) succeed(self, message) - else fail(self, message) - var result = results[self.i] - return function(message) { - if (!result.pass) { - result.message = message + "\n\n" + result.message - } - } - } - } - function succeed(assertion, message) { - results[assertion.i].pass = true - results[assertion.i].context = subjects.join(" > ") - results[assertion.i].message = message - } - function fail(assertion, message, error) { - results[assertion.i].pass = false - results[assertion.i].context = subjects.join(" > ") - results[assertion.i].message = message - results[assertion.i].error = error != null ? error : ensureStackTrace(new Error) - } - function serialize(value) { - if (hasProcess) return require("util").inspect(value) // eslint-disable-line global-require - if (value === null || (typeof value === "object" && !(value instanceof Array)) || typeof value === "number") return String(value) - else if (typeof value === "function") return value.name || "" - try {return JSON.stringify(value)} catch (e) {return String(value)} - } - function noTimeoutRightNow() { - throw new Error("o.timeout must be called snchronously from within a test definition or a hook.") - } - var colorCodes = { - red: "31m", - red2: "31;1m", - green: "32;1m" - } - function highlight(message, color) { - var code = colorCodes[color] || colorCodes.red; - return hasProcess ? (process.stdout.isTTY ? "\x1b[" + code + message + "\x1b[0m" : message) : "%c" + message + "%c " - } - function cStyle(color, bold) { - return hasProcess||!color ? "" : "color:"+color+(bold ? ";font-weight:bold" : "") - } - function ensureStackTrace(error) { - // mandatory to get a stack in IE 10 and 11 (and maybe other envs?) - if (error.stack === undefined) try { throw error } catch(e) {return e} - else return error - } - function getStackName(e, exp) { - return e.stack && exp.test(e.stack) ? e.stack.match(exp)[1] : null - } - - o.report = function (results) { - var errCount = 0 - for (var i = 0, r; r = results[i]; i++) { - if (r.pass == null) { - r.testError.stack = r.message + "\n" + o.cleanStackTrace(r.testError) - r.testError.message = r.message - throw r.testError - } - if (!r.pass) { - var stackTrace = o.cleanStackTrace(r.error) - var couldHaveABetterStackTrace = !stackTrace || timeoutStackName != null && stackTrace.indexOf(timeoutStackName) !== -1 - if (couldHaveABetterStackTrace) stackTrace = r.testError != null ? o.cleanStackTrace(r.testError) : r.error.stack || "" - console.error( - (hasProcess ? "\n" : "") + - highlight(r.context + ":", "red2") + "\n" + - highlight(r.message, "red") + - (stackTrace ? "\n" + stackTrace + "\n" : ""), - - cStyle("black", true), "", // reset to default - cStyle("red"), cStyle("black") - ) - errCount++ - } - } - var pl = results.length === 1 ? "" : "s" - var resultSummary = (errCount === 0) ? - highlight((pl ? "All " : "The ") + results.length + " assertion" + pl + " passed", "green"): - highlight(errCount + " out of " + results.length + " assertion" + pl + " failed", "red2") - var runningTime = " in " + Math.round(Date.now() - start) + "ms" - - console.log( - (hasProcess ? "––––––\n" : "") + - (name ? name + ": " : "") + resultSummary + runningTime, - cStyle((errCount === 0 ? "green" : "red"), true), "" - ) - return errCount - } - - if (hasProcess) { - nextTickish = process.nextTick - } else { - nextTickish = function fakeFastNextTick(next) { - if (stack++ < 5000) next() - else setTimeout(next, stack = 0) - } - } - - return o -}) diff --git a/ospec/package.json b/ospec/package.json deleted file mode 100644 index 4706b9f9..00000000 --- a/ospec/package.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "name": "ospec", - "version": "4.0.1", - "description": "Noiseless testing framework", - "main": "ospec.js", - "directories": { - "test": "tests" - }, - "keywords": [ "testing" ], - "author": "Leo Horie ", - "license": "MIT", - "bin": { - "ospec": "./bin/ospec" - }, - "repository": "MithrilJS/mithril.js", - "dependencies": { - "glob": "^7.1.3" - } -} diff --git a/ospec/tests/test-ospec.js b/ospec/tests/test-ospec.js deleted file mode 100644 index 434f6895..00000000 --- a/ospec/tests/test-ospec.js +++ /dev/null @@ -1,769 +0,0 @@ -"use strict" - -// So it can load correctly in browsers using a global instance. -var o, callAsync - -if (typeof require !== "undefined") { - /* eslint-disable global-require */ - callAsync = require("../../test-utils/callAsync") - var warn = console.warn - // Let's drop the warning to leave the console a little less noisy. - console.warn = function() {} - o = require("../ospec") - console.warn = warn - /* eslint-enable global-require */ -} else { - callAsync = typeof setImmediate === "function" ? setImmediate : setTimeout - o = window.o -} - -// this throws an async error that can't be caught in browsers -if (typeof process !== "undefined") { - o("incomplete assertion", function(done) { - var stackMatcher = /([\w\.\\\/\-]+):(\d+):/ - // /!\ this test relies on the `new Error` expression being six lines - // above the `oo("test", function(){...})` call. - var matches = (new Error).stack.match(stackMatcher) - if (matches != null) { - var name = matches[1] - var num = Number(matches[2]) - } - var oo = o.new() - oo("test", function() { - oo("incomplete") - }) - oo.run(function(results) { - o(results.length).equals(1) - o(results[0].message).equals("Incomplete assertion in the test definition starting at...") - o(results[0].pass).equals(null) - var stack = o.cleanStackTrace(results[0].testError) - var matches2 = stack && stack.match(stackMatcher) - if (matches != null && matches2 != null) { - o(matches[1]).equals(name) - o(Number(matches2[2])).equals(num + 6) - } - done() - }) - }) -} - -o("o.only", function(done) { - var oo = o.new() - - oo.spec("won't run", function() { - oo("nope, skipped", function() { - o(true).equals(false) - }) - }) - - oo.spec("ospec", function() { - oo("skipped as well", function() { - oo(true).equals(false) - }) - oo.only(".only()", function() { - oo(2).equals(2) - }, true) - oo.only("another .only()", function(done) { - done("that fails") - }, true) - }) - - oo.run(function(results){ - o(results.length).equals(2) - o(results[0].pass).equals(true) - o(results[1].pass).equals(false) - - done() - }) -}) - -// Predicate test passing on clone results -o.spec("reporting", function() { - var oo - o.beforeEach(function(){ - oo = o.new() - - oo.spec("clone", function() { - oo("fail", function() { - oo(true).equals(false) - }) - - oo("pass", function() { - oo(true).equals(true) - }) - }) - }) - o("reports per instance", function(done, timeout) { - timeout(100) // Waiting on clone - - oo.run(function(results) { - o(typeof results).equals("object") - o("length" in results).equals(true) - o(results.length).equals(2)("Two results") - - o("error" in results[0] && "pass" in results[0]).equals(true)("error and pass keys present in failing result") - o("message" in results[0] && "context" in results[0]).equals(true)("message and context keys present in failing result") - o("message" in results[1] && "context" in results[1]).equals(true)("message and context keys present in passing result") - o(results[0].pass).equals(false)("Test meant to fail has failed") - o(results[1].pass).equals(true)("Test meant to pass has passed") - - done() - }) - }) - o("o.report() returns the number of failures", function () { - var log = console.log, error = console.error - console.log = o.spy() - console.error = o.spy() - - function makeError(msg) {try{throw msg ? new Error(msg) : new Error} catch(e){return e}} - try { - var errCount = o.report([{pass: true}, {pass: true}]) - - o(errCount).equals(0) - o(console.log.callCount).equals(1) - o(console.error.callCount).equals(0) - - errCount = o.report([ - {pass: false, error: makeError("hey"), message: "hey"} - ]) - - o(errCount).equals(1) - o(console.log.callCount).equals(2) - o(console.error.callCount).equals(1) - - errCount = o.report([ - {pass: false, error: makeError("hey"), message: "hey"}, - {pass: true}, - {pass: false, error: makeError("ho"), message: "ho"} - ]) - - o(errCount).equals(2) - o(console.log.callCount).equals(3) - o(console.error.callCount).equals(3) - } catch (e) { - o(1).equals(0)("Error while testing the reporter") - } - - console.log = log - console.error = error - }) -}) - -o.spec("ospec", function() { - o.spec("sync", function() { - var a = 0, b = 0, illegalAssertionThrows = false - var reservedTestNameTrows = false - - o.before(function() {a = 1}) - o.after(function() {a = 0}) - - o.beforeEach(function() {b = 1}) - o.afterEach(function() {b = 0}) - - try {o("illegal assertion")} catch (e) {illegalAssertionThrows = true} - try {o("\x01reserved test name", function(){})} catch (e) {reservedTestNameTrows = true} - - o("assertions", function() { - var nestedTestDeclarationThrows = false - try {o("illegal nested test", function(){})} catch (e) {nestedTestDeclarationThrows = true} - - o(illegalAssertionThrows).equals(true) - o(nestedTestDeclarationThrows).equals(true) - o(reservedTestNameTrows).equals(true) - - var spy = o.spy() - spy(a) - - o(a).equals(b) - o(a).notEquals(2) - o({a: [1, 2], b: 3}).deepEquals({a: [1, 2], b: 3}) - o([{a: 1, b: 2}, {c: 3}]).deepEquals([{a: 1, b: 2}, {c: 3}]) - o(function(){throw new Error()}).throws(Error) - o(function(){"ayy".foo()}).throws(TypeError) - o(function(){Math.PI.toFixed(Math.pow(10,20))}).throws(RangeError) - o(function(){decodeURIComponent("%")}).throws(URIError) - - o(function(){"ayy".foo()}).notThrows(SyntaxError) - o(function(){throw new Error("foo")}).throws("foo") - o(function(){throw new Error("foo")}).notThrows("bar") - - var undef1 = {undef: void 0} - var undef2 = {UNDEF: void 0} - - o(undef1).notDeepEquals(undef2) - o(undef1).notDeepEquals({}) - o({}).notDeepEquals(undef1) - - var sparse1 = [void 1, void 2, void 3] - delete sparse1[0] - var sparse2 = [void 1, void 2, void 3] - delete sparse2[1] - - o(sparse1).notDeepEquals(sparse2) - - var monkeypatch1 = [1, 2] - monkeypatch1.field = 3 - var monkeypatch2 = [1, 2] - monkeypatch2.field = 4 - - o(monkeypatch1).notDeepEquals([1, 2]) - o(monkeypatch1).notDeepEquals(monkeypatch2) - - monkeypatch2.field = 3 - o(monkeypatch1).deepEquals(monkeypatch2) - - monkeypatch1.undef = undefined - monkeypatch2.UNDEF = undefined - - o(monkeypatch1).notDeepEquals(monkeypatch2) - - var values = ["a", "", 1, 0, true, false, null, undefined, Date(0), ["a"], [], function() {return arguments}.call(), new Uint8Array(), {a: 1}, {}] - for (var i = 0; i < values.length; i++) { - for (var j = 0; j < values.length; j++) { - if (i === j) o(values[i]).deepEquals(values[j]) - else o(values[i]).notDeepEquals(values[j]) - } - } - - o(spy.callCount).equals(1) - o(spy.args.length).equals(1) - o(spy.args[0]).equals(1) - o(spy.calls.length).equals(1) - o(spy.calls[0]).deepEquals({this: undefined, args: [1]}) - }) - o("spy wrapping", function() { - var spy = o.spy(function view(vnode){ - this.drawn = true - - return {tag: "div", children: vnode.children} - }) - var children = [""] - var state = {} - - var output = spy.call(state, {children: children}) - - o(spy.length).equals(1) - o(spy.name).equals("view") - o(spy.callCount).equals(1) - o(spy.args.length).equals(1) - o(spy.args[0]).deepEquals({children: children}) - o(spy.calls.length).equals(1) - o(spy.calls[0]).deepEquals({this: state, args: [{children: children}]}) - o(state).deepEquals({drawn: true}) - o(output).deepEquals({tag: "div", children: children}) - }) - }) - o.spec("async callback", function() { - var a = 0, b = 0 - o.after(function() { - o(a).equals(0) - o(b).equals(0) - }) - o.spec("", function(){ - o.before(function(done) { - callAsync(function() { - a = 1 - done() - }) - }) - o.after(function(done) { - callAsync(function() { - a = 0 - done() - }) - }) - - o.beforeEach(function(done) { - o(b).equals(0) - callAsync(function() { - b = 1 - done() - }) - }) - o.afterEach(function(done) { - callAsync(function() { - b = 0 - done() - }) - }) - - o("hooks work as intended the first time", function(done) { - callAsync(function() { - var spy = o.spy() - spy(a) - - o(a).equals(1) - o(b).equals(1) - - done() - }) - }) - o("hooks work as intended the second time", function(done) { - callAsync(function() { - var spy = o.spy() - spy(a) - - o(a).equals(1) - o(b).equals(1) - - done() - }) - }) - }) - }) - - o.spec("throwing in test context is recorded as a failure", function() { - var oo - o.beforeEach(function(){oo = o.new()}) - o.afterEach(function() { - oo.run(function(results) { - o(results.length).equals(1) - o(results[0].pass).equals(false) - }) - }) - o("sync test", function() { - oo("throw in sync test", function() {throw new Error}) - }) - o("async test", function() { - oo("throw in async test", function(done) { - throw new Error - done() // eslint-disable-line no-unreachable - }) - }) - }) - - o.spec("timeout", function () { - o("when using done()", function(done) { - var oo = o.new() - var err - // the success of this test is dependent on having the - // oo() call three linew below this one - try {throw new Error} catch(e) {err = e} - if (err.stack) { - var line = Number(err.stack.match(/:(\d+):/)[1]) - oo("", function(oodone, timeout) { - // oodone() keep this line for now - timeout(1) - }) - oo.run((function(results) { - o(results.length).equals(1) - o(results[0].pass).equals(false) - // todo test cleaned up results[0].error stack trace for the presence - // of the timeout stack entry - o(results[0].testError instanceof Error).equals(true) - o(o.cleanStackTrace(results[0].testError).indexOf("test-ospec.js:" + (line + 3) + ":")).notEquals(-1) - - done() - })) - } else { - done() - } - }) - o("when using a thenable", function(done) { - var oo = o.new() - var err - // the success of this test is dependent on having the - // oo() call three linew below this one - try {throw new Error} catch(e) {err = e} - if (err.stack) { - var line = Number(err.stack.match(/:(\d+):/)[1]) - oo("", function() { - oo.timeout(1) - return {then: function(){}} - }) - oo.run((function(results) { - o(results.length).equals(1) - o(results[0].pass).equals(false) - o(results[0].testError instanceof Error).equals(true) - o(o.cleanStackTrace(results[0].testError).indexOf("test-ospec.js:" + (line + 3) + ":")).notEquals(-1) - - done() - })) - } else { - done() - } - }) - }) - o.spec("o.timeout", function() { - o("throws when called out of test definitions", function(done) { - var oo = o.new() - var count = 0 - try { oo.timeout(1) } catch (e) { count++ } - oo.spec("a spec", function() { - try { oo.timeout(1) } catch (e) { count++ } - }) - oo("", function() { - oo.timeout(30) - return {then: function(f) {setTimeout(f)}} - }) - oo.run(function(){ - o(count).equals(2) - - done() - }) - }) - o("works", function(done) { - var oo = o.new() - var t = new Date - oo("", function() { - oo.timeout(10) - return {then: function() {}} - }) - oo.run(function(){ - o(new Date - t >= 10).equals(true) - o(200 > new Date - t).equals(true) - - done() - }) - }) - }) - o.spec("o.specTimeout", function() { - o("throws when called inside of test definitions", function(done) { - var err - var oo = o.new() - oo("", function() { - try { oo.specTimeout(5) } catch (e) {err = e} - return {then: function(f) {setTimeout(f)}} - }) - oo.run(function(){ - o(err instanceof Error).equals(true) - - done() - }) - }) - o("works", function(done) { - var oo = o.new() - var t - - oo.specTimeout(10) - oo.beforeEach(function () { - t = new Date - }) - oo.afterEach(function () { - var diff = new Date - t - o(diff >= 10).equals(true) - o(diff < 200).equals(true) - }) - - oo("", function() { - oo(true).equals(true) - - return {then: function() {}} - }) - - oo.run(function(results) { - o(results.length).equals(2) - o(results[0].pass).equals(true) - o(results[1].pass).equals(false) - done() - }) - }) - o("The parent and sibling suites are not affected by the specTimeout", function(done) { - var oo = o.new() - var t - - oo.specTimeout(50) - oo.beforeEach(function () { - t = new Date - }) - oo.afterEach(function () { - var diff = new Date - t - o(diff >= 50).equals(true) - o(diff < 80).equals(true) - }) - - oo.spec("nested 1", function () { - oo.specTimeout(80) - }) - - oo("", function() { - oo(true).equals(true) - - return {then: function() {}} - }) - oo.spec("nested 2", function () { - oo.specTimeout(80) - }) - oo.spec("nested 3", function () { - oo("", function() { - oo(true).equals(true) - - return {then: function() {}} - }) - }) - oo.run(function(results) { - o(results.length).equals(4) - o(results[0].pass).equals(true) - o(results[1].pass).equals(false) - o(results[2].pass).equals(true) - o(results[3].pass).equals(false) - done() - }) - }) - o("nested suites inherit the specTimeout", function(done) { - var oo = o.new() - - oo.specTimeout(50) - oo.spec("nested", function () { - oo.spec("deeply", function() { - var t - - oo.beforeEach(function () { - t = new Date - }) - oo.afterEach(function () { - var diff = new Date - t - o(diff >= 50).equals(true) - o(diff < 80).equals(true) - }) - - oo("", function() { - oo(true).equals(true) - - return {then: function() {}} - }) - }) - }) - oo.run(function(results) { - o(results.length).equals(2) - o(results[0].pass).equals(true) - o(results[1].pass).equals(false) - done() - }) - }) - }) - - o.spec("calling done() twice throws", function () { - o("two successes", function(done) { - var oo = o.new() - var err = null - oo("foo", function(oodone) { - try { - oodone() - oodone() - } catch (e) { - err = e - } - o(err instanceof Error).equals(true) - o(err.message).equals("'oodone()' should only be called once.") - }) - oo.run(function(results) { - o(results.length).equals(1) - o(results[0].pass).equals(true) - done() - }) - }) - o("a success followed by an error", function(done) { - var oo = o.new() - var err = null - oo("foo", function(oodone) { - try { - oodone() - oodone("error") - } catch (e) { - err = e - } - o(err instanceof Error).equals(true) - o(err.message).equals("'oodone()' should only be called once.") - }) - oo.run(function(results) { - o(results.length).equals(1) - o(results[0].pass).equals(true) - done() - }) - }) - o("two errors", function(done) { - var oo = o.new() - var err = null - oo("foo", function(oodone) { - try { - oodone("bar") - oodone("baz") - } catch (e) { - err = e - } - o(err instanceof Error).equals(true) - o(err.message).equals("'oodone()' should only be called once.") - }) - oo.run(function(results) { - o(results.length).equals(1) - o(results[0].pass).equals(false) - o(results[0].message).equals("bar") - done() - }) - }) - o("an error followed by a success", function(done) { - var oo = o.new() - var err = null - oo("foo", function(oodone) { - try { - oodone("bar") - oodone() - } catch (e) { - err = e - } - o(err instanceof Error).equals(true) - o(err.message).equals("'oodone()' should only be called once.") - }) - oo.run(function(results) { - o(results.length).equals(1) - o(results[0].pass).equals(false) - o(results[0].message).equals("bar") - done() - }) - }) - }) - - o.spec("stack trace cleaner", function() { - o("handles line breaks", function() { - try { - throw new Error("line\nbreak") - } catch(error) { - var trace = o.cleanStackTrace(error) - o(trace).notEquals("break") - o(trace.indexOf("test-ospec.js") !== -1).equals(true) - } - }) - }) - - o.spec("async promise", function() { - var a = 0, b = 0 - - function wrapPromise(fn) { - return new Promise(function (resolve, reject) { - callAsync(function () { - try { - fn() - resolve() - } catch(e) { - reject(e) - } - }) - }) - } - - o.before(function() { - return wrapPromise(function () { - a = 1 - }) - }) - - o.after(function() { - return wrapPromise(function() { - a = 0 - }) - }) - - o.beforeEach(function() { - return wrapPromise(function() { - b = 1 - }) - }) - o.afterEach(function() { - return wrapPromise(function() { - b = 0 - }) - }) - - o("promise functions", function() { - return wrapPromise(function() { - o(a).equals(b) - o(a).equals(1)("a and b should be initialized") - }) - }) - }) - - o.spec("descriptions", function() { - o("description returned on failure", function(done) { - var oo = o.new() - oo("no description", function() { - oo(1).equals(2) - }) - oo("description", function() { - oo(1).equals(2)("howdy") - }) - oo.run(function(results) { - o(results.length).equals(2) - o(results[1].message).equals(`howdy\n\n${results[0].message}`) - o(results[1].pass).equals(false) - done() - }) - }) - }) -}) -o.spec("the done parser", function() { - o("accepts non-English names", function() { - var oo = o.new() - var threw = false - oo("test", function(完了) { - oo(true).equals(true) - 完了() - }) - try {oo.run(function(){})} catch(e) {threw = true} - o(threw).equals(false) - }) - o("tolerates comments", function() { - var oo = o.new() - var threw = false - oo("test", function(/*hey - */ /**/ //ho - done /*hey - */ /**/ //huuu - , timeout - ) { - timeout(5) - oo(true).equals(true) - done() - }) - try {oo.run(function(){})} catch(e) {threw = true} - o(threw).equals(false) - }) - /*eslint-disable no-eval*/ - try {eval("(()=>{})()"); o.spec("with ES6 arrow functions", function() { - function getCommentContent(f) { - f = f.toString() - return f.slice(f.indexOf("/*") + 2, f.lastIndexOf("*/")) - } - o("has no false positives 1", function(){ - var oo = o.new() - var threw = false - eval(getCommentContent(function(){/* - oo( - 'Async test parser mistakenly identified 1st token after a parens to be `done` reference', - done => { - oo(threw).equals(false) - done() - } - ) - */})) - try {oo.run(function(){})} catch(e) {threw = true} - o(threw).equals(false) - }) - o("has no false negatives", function(){ - var oo = o.new() - var threw = false - eval(getCommentContent(function(){/* - oo( - "Multiple references to the wrong thing doesn't fool the checker", - done => { - oo(threw).equals(false) - oo(threw).equals(false) - } - ) - */})) - try {oo.run(function(){})} catch(e) {threw = true} - o(threw).equals(true) - }) - o("isn't fooled by comments", function(){ - var oo = o.new() - var threw = false - oo( - "comments won't throw the parser off", - eval("done /*hey*/ /**/ => {oo(threw).equals(false);done()}") - ) - try {oo.run(function(){})} catch(e) {threw = true} - o(threw).equals(false) - }) - })} catch (e) {/*ES5 env, or no eval, ignore*/} - /*eslint-enable no-eval*/ -}) diff --git a/ospec/tests/test.html b/ospec/tests/test.html deleted file mode 100644 index 302b7afe..00000000 --- a/ospec/tests/test.html +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - - - - - diff --git a/package.json b/package.json index 58e3c084..a5ef3470 100644 --- a/package.json +++ b/package.json @@ -25,7 +25,7 @@ "pretest": "npm run lint", "test": "run-s test:js", "test:js": "ospec", - "cover": "istanbul cover --print both ospec/bin/ospec" + "cover": "istanbul cover --print both ospec" }, "devDependencies": { "@alrra/travis-scripts": "^3.0.1", @@ -51,16 +51,10 @@ "semver": "^6.3.0", "terser": "^4.3.4" }, - "bin": { - "ospec": "./ospec/bin/ospec" - }, "lint-staged": { "*.js": [ "eslint . --fix", "git add" ] - }, - "dependencies": { - "ospec": "4.0.1" } }