Compare commits

...

6 Commits

Author SHA1 Message Date
Frédéric Matte b8d85b036e Move runifmain in test 2025-05-11 16:23:02 -04:00
Frédéric Matte a38c1dd2f1 Show stats and the end of a run 2024-10-11 13:38:34 -04:00
Frédéric Matte 149be7074d Pass the test obj to the test function 2024-10-11 13:18:05 -04:00
Frédéric Matte a71feba251 Extract the log function 2024-10-11 13:08:41 -04:00
Frédéric Matte f60f1b34e9 Remove space seperator to shorten the succes 2024-10-11 12:57:32 -04:00
Frédéric Matte bd3fc65f59 Run suite with npx
In a project terminal run "npx metaltest" to run the suite of test

If you want to wath you can use nodemon like "nodemon --exec npx metaltest"
2024-10-11 12:40:22 -04:00
14 changed files with 122 additions and 36 deletions

10
cli/cli.js Executable file
View File

@ -0,0 +1,10 @@
#!/usr/bin/env node
import { suite } from 'metaltest'
const run = async () => {
await suite(process.cwd())
}
const [, , folder] = process.argv
await run(folder)

View File

@ -1,5 +1,4 @@
export * from './reporter/index.js' export * from './reporter/index.js'
export { runifmain } from './lib/runifmain.js'
export { suite } from './lib/suite.js' export { suite } from './lib/suite.js'
import { metaltest } from './lib/metaltest.js' import { metaltest } from './lib/metaltest.js'

5
lib/log.js Normal file
View File

@ -0,0 +1,5 @@
const log = (...args) => {
process.stdout.write(...args)
}
export { log }

View File

@ -1,3 +1,7 @@
import { fileURLToPath } from 'node:url'
import { stacktrace } from './stacktrace.js'
import { errorreporter, summaryreporter, endreporter } from '../index.js'
const metaltest = (title) => { const metaltest = (title) => {
const suite = [] const suite = []
const only = [] const only = []
@ -27,6 +31,14 @@ const metaltest = (title) => {
return { title, success, fail, skip, total: success + fail, testSuccess, testFail } return { title, success, fail, skip, total: success + fail, testSuccess, testFail }
} }
const getAt = (shiftHowMany = 2) => {
const err = new Error()
const stack = stacktrace(err, { shiftHowMany })
const at = stack.stacktraces[0]
return at
}
const runner = (name, fn) => { const runner = (name, fn) => {
suite.push({ name, fn }) suite.push({ name, fn })
} }
@ -60,7 +72,7 @@ const metaltest = (title) => {
for (const test of tests) { for (const test of tests) {
try { try {
for (const fn of before) await fn() for (const fn of before) await fn()
await test.fn() await test.fn(test)
stats('success', test) stats('success', test)
notify(reporters, 'success', test) notify(reporters, 'success', test)
} }
@ -89,6 +101,16 @@ const metaltest = (title) => {
return r return r
} }
runner.runifmain = async () => {
const at = getAt()
const path = fileURLToPath(at.callsite.getFileName)
const [_, script] = process.argv
if (path !== script) return
await runner.run(summaryreporter(), errorreporter(), endreporter())
}
return runner return runner
} }

View File

@ -24,5 +24,4 @@ test.end('verify', async (stats) => {
assert.equal(stats.testFail.length, 0) assert.equal(stats.testFail.length, 0)
}) })
import { runifmain } from '../index.js' await test.runifmain()
await runifmain(import.meta, test)

View File

@ -1,21 +0,0 @@
import { fileURLToPath } from 'node:url'
const isMain = (meta) => {
const path = fileURLToPath(meta.url)
return path.includes(process.argv[1])
}
import { errorreporter, summaryreporter } from '../index.js'
const runifmain = async (meta, fn, ...args) => {
if (!isMain(meta)) return
if (fn.name === 'runner' && fn.run) {
if (args.length == 0) args.push(summaryreporter(), errorreporter())
await fn.run(...args)
} else {
await fn(...args)
}
}
export { runifmain }

View File

@ -22,5 +22,4 @@ test('Diff', () => {
} }
}) })
import { runifmain } from '../index.js' await test.runifmain()
await runifmain(import.meta, test)

57
lib/stacktrace.js Normal file
View File

@ -0,0 +1,57 @@
const LINE_RE = /(?<=^\s*)at.*/gm
const format = (callsite) => {
return {
getThis: callsite.getThis(),//: Returns the value of this.
getTypeName: callsite.getTypeName(),//: Returns the type of this as a string. This is the name of the function stored in the constructor field of this, if available, otherwise the object's [[Class]] internal property.
getFunction: callsite.getFunction(),//: Returns the current function.
getFunctionName: callsite.getFunctionName(),//: Returns the name of the current function, typically its name property. If a name property is not available an attempt will be made to try to infer a name from the function's context.
getMethodName: callsite.getMethodName(),//: Returns the name of the property of this or one of its prototypes that holds the current function.
getFileName: callsite.getFileName(),//: If this function was defined in a script returns the name of the script.
getLineNumber: callsite.getLineNumber(),//: If this function was defined in a script returns the current line number.
getColumnNumber: callsite.getColumnNumber(),//: If this function was defined in a script returns the current column number
getEvalOrigin: callsite.getEvalOrigin(),//: If this function was created using a call to eval returns a string representing the location where eval was called.
isToplevel: callsite.isToplevel(),//: Returns true if this is a top-level invocation, that is, if it's a global object.
isEval: callsite.isEval(),//: Returns true if this call takes place in code defined by a call to eval.
isNative: callsite.isNative(),//: Returns true if this call is in native V8 code.
isConstructor: callsite.isConstructor(),//: Returns true if this is a constructor call.
isAsync: callsite.isAsync(),//: Returns true if this call is asynchronous (i.e. await, Promise.all(), or Promise.any()).
isPromiseAll: callsite.isPromiseAll(),//: Returns true if this is an asynchronous call to Promise.all().
getPromiseIndex: callsite.getPromiseIndex(),//: Returns the index of the promise element that was followed in Promise.all() or Promise.any() for async stack traces, or null if the CallSite is not an asynchronous Promise.all() or Promise.any() call.
}
}
const getStack = (err, { shiftHowMany = 0 } = {}) => {
const old = Error.prepareStackTrace
Error.prepareStackTrace = (err, callsites) => {
return {
summary: err.stack.split("\n").toSpliced(1, shiftHowMany).join("\n"),
callsites: callsites.toSpliced(0, shiftHowMany).map(format),
}
}
const stack = err.stack
Error.prepareStackTrace = old
return stack
}
const stacktrace = (err, { shiftHowMany = 0 } = {}) => {
// if (position >= Error.stackTraceLimit) {
// throw new TypeError('getCallerFile(position) requires position be less then Error.stackTraceLimit but position was: `' + position + '` and Error.stackTraceLimit was: `' + Error.stackTraceLimit + '`')
// }
const { summary, callsites } = getStack(err, { shiftHowMany })
const lines = summary.match(LINE_RE)
const info = {
summary,
stacktraces: callsites.map((callsite, index) => ({ summary: lines[index], callsite }))
}
return info
}
export { stacktrace }

View File

@ -4,6 +4,7 @@
"description": "Clone of baretest with reporting", "description": "Clone of baretest with reporting",
"type": "module", "type": "module",
"exports": "./index.js", "exports": "./index.js",
"bin": "./cli/cli.js",
"scripts": { "scripts": {
"test": "node suite.js" "test": "node suite.js"
}, },

17
reporter/endreporter.js Normal file
View File

@ -0,0 +1,17 @@
import chalk from 'chalk'
import { log } from '../lib/log.js'
const percentage = (dividend, divisor) => (dividend / divisor * 100).toFixed(0)
const endreporter = () => {
let success = 0, fail = 0, skip = 0
return {
success: (test) => { success++ },
fail: (test, e) => { fail++ },
skip: (test) => { skip++ },
end: (stats) => { log(`${chalk.redBright(`Fail: ${fail}`)} - ${chalk.greenBright(`Sucess: ${success}`)} - ${chalk.blueBright(`Skip: ${skip}`)} - ${chalk.yellowBright(`Ratio: ${percentage(success, success + fail)}%`)}`) },
}
}
export { endreporter }

View File

@ -1,6 +1,5 @@
import chalk from 'chalk' import chalk from 'chalk'
import { log } from '../lib/log.js'
const log = (...args) => process.stdout.write(...args)
const errorreporter = () => { const errorreporter = () => {
const report = { const report = {

View File

@ -1,4 +1,5 @@
export { summaryreporter } from './summaryreporter.js' export { summaryreporter } from './summaryreporter.js'
export { linereporter } from './linereporter.js' export { linereporter } from './linereporter.js'
export { totalreporter } from './totalreporter.js' export { totalreporter } from './totalreporter.js'
export { errorreporter } from './errorreporter.js' export { errorreporter } from './errorreporter.js'
export { endreporter } from './endreporter.js'

View File

@ -1,7 +1,6 @@
import chalk from 'chalk' import chalk from 'chalk'
import { stackParser } from '../lib/stackparser.js' import { stackParser } from '../lib/stackparser.js'
import { log } from '../lib/log.js'
const log = (...args) => console.log(...args)
const linereporter = () => { const linereporter = () => {
const lines = [] const lines = []

View File

@ -1,6 +1,5 @@
import chalk from 'chalk' import chalk from 'chalk'
import { log } from '../lib/log.js'
const log = (...args) => process.stdout.write(...args)
const summaryreporter = () => { const summaryreporter = () => {
@ -9,10 +8,10 @@ const summaryreporter = () => {
log(chalk.cyanBright(title) + ' ') log(chalk.cyanBright(title) + ' ')
}, },
success: (test) => { success: (test) => {
log(chalk.greenBright('✓ ')) log(chalk.greenBright('✓'))
}, },
fail: (test, e) => { fail: (test, e) => {
log(chalk.redBright('✗ ')) log(chalk.redBright(' ✗ '))
}, },
end: (stats) => { end: (stats) => {
log('\n') log('\n')