Commit 9d0c457c authored by isaacs's avatar isaacs

use standard for style

parent 6df21056
......@@ -7,9 +7,8 @@ if (args.length === 1) {
var file = path.resolve(args[0])
tap.mochaGlobals()
require(file)
return
}
for (var i = 0; i < args.length; i++) {
tap.spawn(process.execPath, [ __filename, args[i] ])
} else {
for (var i = 0; i < args.length; i++) {
tap.spawn(process.execPath, [__filename, args[i]])
}
}
......@@ -13,8 +13,9 @@ t.test('gun show', function (t) {
t.pass('this is ok')
t.pass('i am ok with how things are proceeding')
}
if (++n === 50)
if (++n === 50) {
return clearInterval(i)
}
}, 100)
})
......@@ -29,7 +30,8 @@ t.test('wondermark', function (t) {
t.pass('excuse me')
t.pass('pardon me')
}
if (++n === 250)
if (++n === 250) {
return clearInterval(j)
}
}, 10)
})
var tap = require("tap")
, test = tap.test
, plan = tap.plan
, math
test("load sut", function (t) {
math = require("../lib/math")
t.ok(math, "object loaded")
t.end()
})
test("validate constants", function (t) {
t.equal(math.LN10, 2.302585092994046, "ln 10")
t.equal(math.PI, 3.141592653589793, "pi")
t.equal(math.E, 2.718281828459045, "e")
t.equal(math.LOG10E, 0.4342944819032518, "log 10 e")
t.equal(math.SQRT2, 1.4142135623730951, "sqrt 2")
t.equal(math.SQRT1_2, 0.7071067811865476, "sqrt 1/2")
t.equal(math.LN2, 0.6931471805599453, "ln2")
t.end()
})
test("using this", function (t) {
// this also works.
this.equal(t, this, "call in scope of test obj")
this.end()
})
// test setTimeout, just a trivial example.
test("setTimeout", function (t) {
var start = Date.now()
setTimeout(function () {
t.ok(Date.now() >= start + 50, "timeout fired after delay")
t.end()
}, 50)
})
// another way to do the same, using a plan.
// this is more robust, but annoying when you have a long list
// of tests for something. For async stuff, it's generally better,
// since there's a higher risk of the control flowing off to lala land.
test("setTimeout planned", function (t) {
t.plan(1)
var start = Date.now()
setTimeout(function () {
t.ok(Date.now() >= start + 50, "timeout fired after delay")
}, 50)
})
// plans also are good for cases where things may fire in a non-deterministic
// order, since it won't be as obvious when everything is done.
test("setTimeout parallel", function (t) {
t.plan(2)
var start = Date.now()
setTimeout(function A () {
t.ok(Date.now() >= start + 50, "timeout A fired after delay")
}, 50)
setTimeout(function B () {
t.ok(Date.now() >= start + 50, "timeout B fired after delay")
}, 50)
})
// something slightly less hello worldy
test("async test", function (t) {
t.plan(4)
var fs = require("fs")
t.ok(fs, "fs library should load")
var rs = fs.createReadStream(__filename)
t.ok(rs, "read stream should start fine.")
rs.on("open", function (fd) {
t.type(fd, "number", "file descriptor should be a number")
t.equal(fd, rs.fd, "fd should match stream fd")
})
})
// you can bail out of the entire everything if something is just
// Not Right (db not installed, etc.)
test("tarp", function (parent) {
if (7 === 5) {
parent.bailout("math is broken")
}
// bailout bubbles up a bit like "error" events
// if unhandled, then the parent will bail, as well.
parent.test("child bailouts", function (child) {
child.on("bailout", function (s) {
parent.fail("children shouldn't bail.")
})
child.bailout("try to bail out, but instead just fail a test")
})
parent.test("child bailout 2", function (child) {
child.bailout("this one will bail out")
})
})
// tests marked "todo" can fail without counting against the overall score
// never ever ever write tests to "verify" incorrect behavior!
test("unfinished test", function (t) {
t.equal(math.cos(math.PI), -1, "cos(PI)")
t.equal(math.sin(math.PI), 0, "sin(PI)")
t.equal(math.face, "your face", "math.face should be your face # TODO")
t.end()
})
// tests can have children.
test("http server", function (t) {
// one test plus 4 children.
t.plan(5)
var http = require("http")
, PORT = 12346
t.ok(http, "http module should load")
var server
t.test("set up server", function (t) {
t.plan(2)
server = http.createServer(function (req, res) {
t.comment("Request: "+req.url)
res.writeHead(200, {})
res.end(req.method + " " + req.url)
})
t.ok(server, "createServer should create a server")
server.listen(PORT, t.cb("listen should fire callback"))
})
// set the "parallel" flag on this one.
// That signals the harness to proceed immediately to the next test,
// and run them in parallel.
// Default behavior is to wait for each test to complete before proceeding
// to the next one.
// The first not-parallel test encountered will cause it to wait for that
// test, as well as all the parallel tests before it.
// A, B', C', D', E (where ' means "parallel")
// Runs A, and then B, C, and D in parallel, and then E.
t.test("testing POST", {parallel: true}, function (t) {
t.plan(1)
http.request("POST", { method: "POST"
, host: "localhost"
, path: "/foo"
, port: PORT }).on("response", function (res) {
t.bufferStream(res, function (s) { t.equal(s, "POST /foo") })
}).end()
})
t.test("testing GET", {parallel: true}, function (t) {
t.plan(1)
http.request("POST", { method: "GET"
, host: "localhost"
, path: "/foo"
, port: PORT }).on("response", function (res) {
t.bufferStream(res, function (s) { t.equal(s, "GET /foo") })
}).end()
})
// wrap in a test so that if this throws, it'll log as a failed test.
t.test("teardown", function (t) {
server.close()
t.end()
})
})
// yo dawg!
test("meta-tests", function (t) {
t.plan(5)
// t.fails() wraps a child test and succeeds if it fails.
t.fails(t.test("this should fail", function (t) {
t.ok(false, "assert false")
t.end()
}))
// t.timesOut() wraps a child test and succeeds if it times out.
// if t.end() is called, or if a plan is completed, then it fails.
// set the timeout really low so that it will not take forever.
t.timesOut(t.test("this should timeout", { timeout: 1 }, function (t) {
t.ok(true, "assert true")
// t.end() never called.
}))
// t.incomplete() wraps a child test and succeeds if it ends before
// the plan is finished.
t.incomplete(t.test("this should be incomplete", function (t) {
t.plan(100)
t.ok(true, "assert true")
// calling end prematurely.
t.end()
}))
// t.bailsOut() wraps a child test and succeeds if it calls bailout()
t.bailsOut(t.test("this should bailout", function (t) {
t.bailout("oh noes, bailing out!")
}))
// low-level analysis of subtests
t.test("verifying test success/failure expectations", function (t) {
t.once("end", function () {
var res = t.results
, is = t.equal
// hijack!
t.clear()
is(res.ok, false, "ok")
is(res.bailedOut, false, "bailed out")
is(res.skip, 2, "skips")
is(res.skipPass, 1, "skip that passed")
is(res.skipFail, 1, "skip that failed")
is(res.todo, 2, "todos")
is(res.todoPass, 1, "todo that passed")
is(res.todoFail, 1, "todo that failed")
is(res.failTotal, 3, "failures total")
is(res.fail, 1, "relevant failure")
is(res.passTotal, 3, "passes total")
is(res.pass, 1, "relevant pass")
is(res.testsTotal, 6, "total tests")
is(res.tests, 2, "should be 2 relevant tests")
t.end()
})
// run the metatest.
// *this* is the actual SUT in this case.
t.ok(false, "failing todo #todo")
// can also set #todo or #skip explicitly
t.ok(true, "succeeding todo", {todo: true})
t.ok(false, "failing skip #skip", {skip: true})
t.ok(true, "suceeding skip #skip")
t.ok(false, "failing test")
t.ok(true, "succeeding test")
t.end()
})
})
......@@ -4,7 +4,7 @@ var shallower = require('only-shallow') // in touch with its feelings
var tmatch = require('tmatch') // ok with partial estimates
// Load Buffer the old way for browserify's sake
var Buffer = require('buffer').Buffer
var Buffer = require('buffer').Buffer // eslint-disable-line
// this is actually the "working half" of the Test class.
// each method figures out if it's a pass or fail, and decorates
......@@ -20,8 +20,9 @@ exports.decorate = decorate
function decorate (t) {
t.addAssert('ok', 1, function (obj, message, extra) {
message = message || 'expect truthy value'
if (obj)
if (obj) {
return this.pass(message, extra)
}
return this.fail(message, extra)
})
......@@ -32,8 +33,9 @@ function decorate (t) {
})
t.addAssert('error', 1, function (er, message, extra) {
if (!er)
if (!er) {
return this.pass(message || 'should not error', extra)
}
if (!(er instanceof Error)) {
extra.found = er
......@@ -47,8 +49,9 @@ function decorate (t) {
t.addAssert('equal', 2, function (f, w, m, e) {
m = m || 'should be equal'
if (f === w)
if (f === w) {
return this.pass(m, e)
}
e.found = f
e.wanted = w
......@@ -58,16 +61,18 @@ function decorate (t) {
typeof w === 'object' &&
f &&
w &&
shallower(f, w))
shallower(f, w)) {
e.note = 'Objects never === one another'
}
return this.fail(m, e)
})
t.addAssert('not', 2, function (f, w, m, e) {
m = m || 'should not be equal'
if (f !== w)
if (f !== w) {
return this.pass(m, e)
}
e.found = f
e.doNotWant = w
......@@ -120,17 +125,20 @@ function decorate (t) {
t.addAssert('type', 2, function (obj, klass, m, e) {
var name = klass
if (typeof name === 'function')
if (typeof name === 'function') {
name = name.name || '(anonymous constructor)'
}
m = m || 'type is ' + name
// simplest case, it literally is the same thing
if (obj === klass)
if (obj === klass) {
return this.pass(m, e)
}
var type = typeof obj
if (!obj && type === 'object')
if (!obj && type === 'object') {
type = 'null'
}
if (type === 'object' && klass !== 'object') {
if (typeof klass === 'function') {
......@@ -146,9 +154,11 @@ function decorate (t) {
var p = obj
do {
var ctor = p.constructor && p.constructor.name
if (p === klass || ctor === name)
if (p === klass || ctor === name) {
return this.pass(m, e)
} while (p = Object.getPrototypeOf(p))
}
p = Object.getPrototypeOf(p)
} while (p)
}
return this.equal(type, name, m, e)
......@@ -158,42 +168,46 @@ function decorate (t) {
var fn, wanted, e
for (var i = 0; i < arguments.length - 1; i++) {
var arg = arguments[i]
if (typeof arg === 'function')
if (typeof arg === 'function') {
fn = arg
else if (typeof arg === 'string' && arg)
} else if (typeof arg === 'string' && arg) {
m = arg
else if (typeof arg === 'object') {
if (!wanted)
} else if (typeof arg === 'object') {
if (!wanted) {
wanted = arg
else
} else {
e = arg
}
}
}
for (var i in e__) {
for (i in e__) {
e[i] = e__[i]
}
if (!m)
if (!m) {
m = fn && fn.name || 'expected to throw'
}
if (wanted) {
if (wanted instanceof Error) {
var w = {
message: wanted.message
}
if (wanted.name)
if (wanted.name) {
w.name = wanted.name
}
for (var i in wanted) {
for (i in wanted) {
w[i] = wanted[i]
}
wanted = w
m += ': ' + (wanted.name || 'Error') + ' ' + wanted.message
e = e || {}
if (e !== wanted)
if (e !== wanted) {
e.wanted = wanted
}
} else if (typeof wanted === 'string') {
wanted = {
message: wanted
......@@ -201,7 +215,6 @@ function decorate (t) {
}
}
if (typeof fn !== 'function') {
e = e || {}
e.todo = true
......@@ -213,16 +226,18 @@ function decorate (t) {
return this.fail(m, e)
} catch (er) {
// 'name' is a getter.
if (er.name)
if (er.name) {
er.name = er.name + ''
}
if (wanted) {
if (Object.prototype.toString.call(wanted) === '[object RegExp]') {
return this.match(er.message, wanted, m, e)
}
return this.has(er, wanted, m, e)
}
else
} else {
return this.pass(m, e)
}
}
})
......@@ -233,8 +248,9 @@ function decorate (t) {
m = x
}
if (!m)
if (!m) {
m = fn && fn.name || 'expected to not throw'
}
if (typeof fn !== 'function') {
e.todo = true
......@@ -249,7 +265,6 @@ function decorate (t) {
}
})
// synonyms are helpful.
Object.keys(synonyms).forEach(function (c) {
if (t[c]) {
......@@ -264,29 +279,3 @@ function decorate (t) {
}
})
}
// TODO: this "partial deep equal" logic should be a module.
function selectFields (a, b) {
// get the values in A of the fields in B
var ret = Array.isArray(b) ? [] : {}
Object.keys(b).forEach(function (k) {
var v = b[k]
, av = a[k]
if (v && av && typeof v === "object" && typeof av === "object"
&& !(Buffer.isBuffer(v))
&& !(v instanceof Date)
&& !(v instanceof RegExp)
&& !(v instanceof String)
&& !(v instanceof Boolean)
&& !(v instanceof Number)
&& !(Array.isArray(v))) {
ret[k] = selectFields(av, v)
} else
ret[k] = av
})
return ret
}
function hasOwn (obj, key) {
return Object.hasOwnProperty.call(obj, key)
}
......@@ -7,8 +7,9 @@ var stack = require('./stack.js')
exports.it = it
exports.describe = describe
exports.global = function () {
for (var g in exports)
for (var g in exports) {
global[g] = exports[g]
}
}
var t = require('./root.js')
......@@ -17,32 +18,34 @@ function it (name, fn) {
var c = t.current()
var at = stack.at(it)
if (fn && fn.length)
if (fn && fn.length) {
c.test(name, { at: at }, function (tt) {
fn(function (err) {
if (err) tt.threw(err)
else tt.end()
})
})
else
} else {
c.doesNotThrow(fn, name || 'unnamed test', { at: at })
}
}
function describe (name, fn) {
var c = t.current()
var at = stack.at(describe)
if (!fn)
if (!fn) {
c.test(name, { at: at })
else if (fn.length)
} else if (fn.length) {
c.test(name, { at: at }, function (tt) {
fn(function (err) {
if (err) tt.threw(err)
else tt.end()
})
})
else
} else {
c.test(name, { at: at }, function (tt) {
fn()
tt.end()
})
}
}
......@@ -3,8 +3,9 @@ var Test = require('./test.js')
var tap = new Test()
module.exports = tap
if (tap._timer && tap._timer.unref)
if (tap._timer && tap._timer.unref) {
tap._timer.unref()
}
tap._name = 'TAP'
......@@ -16,8 +17,9 @@ tap.on('bailout', function () {
process.on('exit', function (code) {
tap.endAll()
if (!tap._ok && code === 0)
if (!tap._ok && code === 0) {
process.exit(1)
}
})
// need to autoend if a teardown is added.
......@@ -46,33 +48,39 @@ process.on('uncaughtException', function onUncaught (er) {
// SIGTERM means being forcibly killed, almost always by timeout
var onExit = require('signal-exit')
onExit(function (code, signal) {
if (signal !== 'SIGTERM')
if (signal !== 'SIGTERM') {
return
}
var handles = process._getActiveHandles().filter(function (h) {
return h !== process.stdout &&
h !== process.stdin &&
h !== process.stderr
h !== process.stdin &&
h !== process.stderr
})
var requests = process._getActiveRequests()
var msg = 'received SIGTERM with pending event queue activity'
tap.fail(msg, {
requests: requests.map(function (r) {
var ret = { type: r.constructor.name }
if (r.context)
if (r.context) {
ret.context = r.context
}
return ret
}),
handles: handles.map(function (h) {
var ret = { type: h.constructor.name }
if (h.msecs)
if (h.msecs) {
ret.msecs = h.msecs
if (h._events)
}
if (h._events) {
ret.events = Object.keys(h._events)
if (h._sockname)
}
if (h._sockname) {
ret.sockname = h._sockname
if (h._connectionKey)
}
if (h._connectionKey) {
ret.connectionKey = h._connectionKey
}
return ret
}),
at: null
......
......@@ -22,8 +22,9 @@ var cwd = process.cwd()
// ]
function clean (stack) {
if (!Array.isArray(stack))
if (!Array.isArray(stack)) {
stack = stack.split('\n')
}
var internals = [
/\(domain.js:[0-9]+:[0-9]+\)$/,
......@@ -36,15 +37,19 @@ function clean (stack) {
]
if (!(/^\s*at /.test(stack[0])) &&
(/^\s*at /.test(stack[1])))
(/^\s*at /.test(stack[1]))) {
stack = stack.slice(1)
}
stack = stack.map(function (st) {
if (internals.some(function (internal) {
var isInternal = internals.some(function (internal) {
return internal.test(st)
})) {
})
if (isInternal) {
return null
}
return st.trim()
.replace(/^\s*at /, '')
.replace(cwd + '/', '')
......@@ -53,10 +58,11 @@ function clean (stack) {
return st
}).join('\n').trim()
if (stack)
if (stack) {
return stack + '\n'
else
} else {
return null
}
}
function captureString (limit, fn) {
......@@ -64,12 +70,14 @@ function captureString (limit, fn) {
fn = limit
limit = Infinity
}
if (!fn)
if (!fn) {
fn = captureString
}
var limitBefore = Error.stackTraceLimit
if (limit)
if (limit) {
Error.stackTraceLimit = limit
}
var obj = {}
......@@ -85,8 +93,9 @@ function capture (limit, fn) {
fn = limit
limit = Infinity
}
if (!fn)
if (!fn) {
fn = capture
}
var prepBefore = Error.prepareStackTrace
var limitBefore = Error.stackTraceLimit
......@@ -94,8 +103,9 @@ function capture (limit, fn) {
return site
}
if (limit)
if (limit) {
Error.stackTraceLimit = limit