Skip to content

Commit

Permalink
Chore: use async/await in tests
Browse files Browse the repository at this point in the history
  • Loading branch information
mysticatea committed Aug 26, 2017
1 parent 66fa8ff commit 64f6479
Show file tree
Hide file tree
Showing 28 changed files with 955 additions and 1,089 deletions.
1 change: 1 addition & 0 deletions .babelrc
@@ -1,5 +1,6 @@
{
"presets": ["power-assert"],
"plugins": ["transform-async-to-generator"],
"only": "/test/*.js",
"sourceMaps": "inline"
}
8 changes: 4 additions & 4 deletions bin/common/parse-cli-args.js
Expand Up @@ -43,12 +43,12 @@ function createPackageConfig() {
return retv
}

Object.keys(process.env).forEach(key => {
for (const key of Object.keys(process.env)) {
const m = PACKAGE_CONFIG_PATTERN.exec(key)
if (m != null) {
overwriteConfig(retv, packageName, m[1], process.env[key])
}
})
}

return retv
}
Expand All @@ -62,7 +62,7 @@ function createPackageConfig() {
*/
function addGroup(groups, initialValues) {
groups.push(Object.assign(
{parallel: false, patterns: []},
{ parallel: false, patterns: [] },
initialValues || {}
))
}
Expand Down Expand Up @@ -183,7 +183,7 @@ function parseCLIArgsCore(set, args) { // eslint-disable-line complexity
if (set.singleMode) {
throw new Error(`Invalid Option: ${arg}`)
}
addGroup(set.groups, {parallel: true})
addGroup(set.groups, { parallel: true })
break

case "--npm-path":
Expand Down
2 changes: 1 addition & 1 deletion bin/run-p/main.js
Expand Up @@ -28,7 +28,7 @@ const parseCLIArgs = require("../common/parse-cli-args")
module.exports = function npmRunAll(args, stdout, stderr) {
try {
const stdin = process.stdin
const argv = parseCLIArgs(args, {parallel: true}, {singleMode: true})
const argv = parseCLIArgs(args, { parallel: true }, { singleMode: true })
const group = argv.lastGroup

if (group.patterns.length === 0) {
Expand Down
2 changes: 1 addition & 1 deletion bin/run-s/main.js
Expand Up @@ -28,7 +28,7 @@ const parseCLIArgs = require("../common/parse-cli-args")
module.exports = function npmRunAll(args, stdout, stderr) {
try {
const stdin = process.stdin
const argv = parseCLIArgs(args, {parallel: false}, {singleMode: true})
const argv = parseCLIArgs(args, { parallel: false }, { singleMode: true })
const group = argv.lastGroup

if (group.patterns.length === 0) {
Expand Down
2 changes: 1 addition & 1 deletion lib/create-header.js
Expand Up @@ -38,7 +38,7 @@ module.exports = function createHeader(nameAndArgs, packageInfo, isTTY) {
const packageVersion = packageInfo.body.version
const scriptBody = packageInfo.body.scripts[name]
const packagePath = packageInfo.path
const color = isTTY ? chalk.styles.gray : {open: "", close: ""}
const color = isTTY ? chalk.styles.gray : { open: "", close: "" }

return `
${color.open}> ${packageName}@${packageVersion} ${name} ${packagePath}${color.close}
Expand Down
4 changes: 2 additions & 2 deletions lib/create-prefix-transform-stream.js
Expand Up @@ -45,11 +45,11 @@ class PrefixTransform extends stream.Transform {
* Transforms the output chunk.
*
* @param {string|Buffer} chunk - A chunk to be transformed.
* @param {string} encoding - The encoding of the chunk.
* @param {string} _encoding - The encoding of the chunk.
* @param {function} callback - A callback function that is called when done.
* @returns {void}
*/
_transform(chunk, encoding, callback) {
_transform(chunk, _encoding, callback) {
const prefix = this.prefix
const nPrefix = `\n${prefix}`
const state = this.state
Expand Down
10 changes: 5 additions & 5 deletions lib/index.js
Expand Up @@ -110,15 +110,15 @@ function parsePatterns(patternOrPatterns, args) {
function toOverwriteOptions(config) {
const options = []

Object.keys(config).forEach(packageName => {
for (const packageName of Object.keys(config)) {
const packageConfig = config[packageName]

Object.keys(packageConfig).forEach(variableName => {
for (const variableName of Object.keys(packageConfig)) {
const value = packageConfig[variableName]

options.push(`--${packageName}:${variableName}=${value}`)
})
})
}
}

return options
}
Expand Down Expand Up @@ -249,7 +249,7 @@ module.exports = function npmRunAll(patternOrPatterns, options) {
return Promise.resolve()
.then(() => {
if (taskList != null) {
return {taskList, packageInfo: null}
return { taskList, packageInfo: null }
}
return readPackageJson()
})
Expand Down
12 changes: 6 additions & 6 deletions lib/match-tasks.js
Expand Up @@ -17,7 +17,7 @@ const Minimatch = require("minimatch").Minimatch
//------------------------------------------------------------------------------

const COLON_OR_SLASH = /[:/]/g
const CONVERT_MAP = {":": "/", "/": ":"}
const CONVERT_MAP = { ":": "/", "/": ":" }

/**
* Swaps ":" and "/", in order to use ":" as the separator in minimatch.
Expand Down Expand Up @@ -46,7 +46,7 @@ function createFilter(pattern) {
const matcher = new Minimatch(swapColonAndSlash(task))
const match = matcher.match.bind(matcher)

return {match, task, args}
return { match, task, args }
}

/**
Expand Down Expand Up @@ -97,18 +97,18 @@ module.exports = function matchTasks(taskList, patterns) {
const unknownSet = Object.create(null)

// Take tasks while keep the order of patterns.
filters.forEach(filter => {
for (const filter of filters) {
let found = false

candidates.forEach(candidate => {
for (const candidate of candidates) {
if (filter.match(candidate)) {
found = true
taskSet.add(
swapColonAndSlash(candidate) + filter.args,
filter.task
)
}
})
}

// Built-in tasks should be allowed.
if (!found && (filter.task === "restart" || filter.task === "env")) {
Expand All @@ -118,7 +118,7 @@ module.exports = function matchTasks(taskList, patterns) {
if (!found) {
unknownSet[filter.task] = true
}
})
}

const unknownTasks = Object.keys(unknownSet)
if (unknownTasks.length > 0) {
Expand Down
2 changes: 1 addition & 1 deletion lib/read-package-json.js
Expand Up @@ -26,6 +26,6 @@ module.exports = function readPackageJson() {
const path = joinPath(process.cwd(), "package.json")
return readPkg(path).then(body => ({
taskList: Object.keys(body.scripts || {}),
packageInfo: {path, body},
packageInfo: { path, body },
}))
}
12 changes: 6 additions & 6 deletions lib/run-task.js
Expand Up @@ -33,8 +33,8 @@ const colors = [chalk.cyan, chalk.green, chalk.magenta, chalk.yellow, chalk.red]
function selectColor(taskName) {
let hash = 0

for (const i in taskName) {
hash = ((hash << 5) - hash) + taskName.charCodeAt(i)
for (const c of taskName) {
hash = ((hash << 5) - hash) + c
hash |= 0
}

Expand Down Expand Up @@ -124,7 +124,7 @@ module.exports = function runTask(task, options) {
const stdinKind = detectStreamKind(stdin, process.stdin)
const stdoutKind = detectStreamKind(stdout, process.stdout)
const stderrKind = detectStreamKind(stderr, process.stderr)
const spawnOptions = {stdio: [stdinKind, stdoutKind, stderrKind]}
const spawnOptions = { stdio: [stdinKind, stdoutKind, stderrKind] }

// Print task name.
if (options.printName && stdout != null) {
Expand Down Expand Up @@ -164,10 +164,10 @@ module.exports = function runTask(task, options) {
stdin.pipe(cp.stdin)
}
if (stdoutKind === "pipe") {
cp.stdout.pipe(stdout, {end: false})
cp.stdout.pipe(stdout, { end: false })
}
if (stderrKind === "pipe") {
cp.stderr.pipe(stderr, {end: false})
cp.stderr.pipe(stderr, { end: false })
}

// Register
Expand All @@ -177,7 +177,7 @@ module.exports = function runTask(task, options) {
})
cp.on("close", (code) => {
cp = null
resolve({task, code})
resolve({ task, code })
})
})

Expand Down
8 changes: 5 additions & 3 deletions lib/run-tasks.js
Expand Up @@ -53,8 +53,8 @@ module.exports = function runTasks(tasks, options) {
return
}

const results = tasks.map(task => ({name: task, code: undefined}))
const queue = tasks.map((task, index) => ({name: task, index}))
const results = tasks.map(task => ({ name: task, code: undefined }))
const queue = tasks.map((task, index) => ({ name: task, index }))
const promises = []
let error = null
let aborted = false
Expand Down Expand Up @@ -86,7 +86,9 @@ module.exports = function runTasks(tasks, options) {
done()
}
else {
promises.forEach(p => p.abort())
for (const p of promises) {
p.abort()
}
Promise.all(promises).then(done, reject)
}
}
Expand Down
4 changes: 2 additions & 2 deletions lib/spawn-posix.js
Expand Up @@ -28,14 +28,14 @@ function kill() {
return
}

descendent.forEach(child => {
for (const child of descendent) {
try {
process.kill(child.PID)
}
catch (_err) {
// ignore.
}
})
}
})
}

Expand Down
5 changes: 3 additions & 2 deletions package.json
Expand Up @@ -40,11 +40,12 @@
},
"devDependencies": {
"@types/node": "^4.2.20",
"babel-plugin-transform-async-to-generator": "^6.24.1",
"babel-preset-power-assert": "^1.0.0",
"babel-register": "^6.26.0",
"codecov": "^2.3.0",
"eslint": "^3.12.2",
"eslint-config-mysticatea": "^7.0.1",
"eslint": "^4.5.0",
"eslint-config-mysticatea": "^12.0.0",
"jsdoc": "^3.5.4",
"mocha": "^3.5.0",
"nyc": "^11.1.0",
Expand Down
7 changes: 6 additions & 1 deletion test/.eslintrc.json
@@ -1,3 +1,8 @@
{
"extends": "mysticatea/mocha"
"extends": "mysticatea/mocha",
"rules": {
"node/no-unsupported-features": ["error", {
"ignores": ["asyncAwait"]
}]
}
}
64 changes: 33 additions & 31 deletions test/aggregate-output.js
Expand Up @@ -54,40 +54,42 @@ describe("[aggregated-output] npm-run-all", () => {
stdout = new BufferStream()
})

it("Node API", () => nodeApi(
["test-task:delayed first 300", "test-task:delayed second 100", "test-task:delayed third 200"],
{stdout, silent: true, aggregateOutput: true}
)
.then(() => {
assert.equal(stdout.value, EXPECTED_SERIALIZED_TEXT)
}))
it("Node API", async () => {
await nodeApi(
["test-task:delayed first 300", "test-task:delayed second 100", "test-task:delayed third 200"],
{ stdout, silent: true, aggregateOutput: true }
)
assert.equal(stdout.value, EXPECTED_SERIALIZED_TEXT)
})

it("npm-run-all command", () => runAll(
["test-task:delayed first 300", "test-task:delayed second 100", "test-task:delayed third 200", "--silent", "--aggregate-output"],
stdout
)
.then(() => {
assert.equal(stdout.value, EXPECTED_SERIALIZED_TEXT)
}))
it("npm-run-all command", async () => {
await runAll(
["test-task:delayed first 300", "test-task:delayed second 100", "test-task:delayed third 200", "--silent", "--aggregate-output"],
stdout
)
assert.equal(stdout.value, EXPECTED_SERIALIZED_TEXT)
})

it("run-s command", () => runSeq(
["test-task:delayed first 300", "test-task:delayed second 100", "test-task:delayed third 200", "--silent", "--aggregate-output"],
stdout
)
.then(() => {
assert.equal(stdout.value, EXPECTED_SERIALIZED_TEXT)
}))
it("run-s command", async () => {
await runSeq(
["test-task:delayed first 300", "test-task:delayed second 100", "test-task:delayed third 200", "--silent", "--aggregate-output"],
stdout
)
assert.equal(stdout.value, EXPECTED_SERIALIZED_TEXT)
})

it("run-p command", () => runPar([
"test-task:delayed first 3000",
"test-task:delayed second 1000",
"test-task:delayed third 2000",
"--silent", "--aggregate-output"],
stdout
)
.then(() => {
assert.equal(stdout.value, EXPECTED_PARALLELIZED_TEXT)
}))
it("run-p command", async () => {
await runPar(
[
"test-task:delayed first 3000",
"test-task:delayed second 1000",
"test-task:delayed third 2000",
"--silent", "--aggregate-output",
],
stdout
)
assert.equal(stdout.value, EXPECTED_PARALLELIZED_TEXT)
})
})
})

10 changes: 5 additions & 5 deletions test/argument-placeholders.js
Expand Up @@ -67,7 +67,7 @@ describe("[argument-placeholders]", () => {

describe("'{1}' should be replaced by the 1st argument preceded by '--':", () => {
it("Node API", () =>
nodeApi("test-task:dump {1}", {arguments: ["1st", "2nd"]})
nodeApi("test-task:dump {1}", { arguments: ["1st", "2nd"] })
.then(() => assert(result() === "[\"1st\"]"))
)

Expand All @@ -89,7 +89,7 @@ describe("[argument-placeholders]", () => {

describe("'{2}' should be replaced by the 2nd argument preceded by '--':", () => {
it("Node API", () =>
nodeApi("test-task:dump {2}", {arguments: ["1st", "2nd"]})
nodeApi("test-task:dump {2}", { arguments: ["1st", "2nd"] })
.then(() => assert(result() === "[\"2nd\"]"))
)

Expand All @@ -111,7 +111,7 @@ describe("[argument-placeholders]", () => {

describe("'{@}' should be replaced by the every argument preceded by '--':", () => {
it("Node API", () =>
nodeApi("test-task:dump {@}", {arguments: ["1st", "2nd"]})
nodeApi("test-task:dump {@}", { arguments: ["1st", "2nd"] })
.then(() => assert(result() === "[\"1st\",\"2nd\"]"))
)

Expand All @@ -133,7 +133,7 @@ describe("[argument-placeholders]", () => {

describe("'{*}' should be replaced by the all arguments preceded by '--':", () => {
it("Node API", () =>
nodeApi("test-task:dump {*}", {arguments: ["1st", "2nd"]})
nodeApi("test-task:dump {*}", { arguments: ["1st", "2nd"] })
.then(() => assert(result() === "[\"1st 2nd\"]"))
)

Expand All @@ -155,7 +155,7 @@ describe("[argument-placeholders]", () => {

describe("Every '{1}', '{2}', '{@}' and '{*}' should be replaced by the arguments preceded by '--':", () => {
it("Node API", () =>
nodeApi("test-task:dump {1} {2} {3} {@} {*}", {arguments: ["1st", "2nd"]})
nodeApi("test-task:dump {1} {2} {3} {@} {*}", { arguments: ["1st", "2nd"] })
.then(() => assert(result() === "[\"1st\",\"2nd\",\"1st\",\"2nd\",\"1st 2nd\"]"))
)

Expand Down

0 comments on commit 64f6479

Please sign in to comment.