Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions bin/reporter.js
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,7 @@ module.exports = function report_on (test,o) {

/**
* Adds handlers to debug test stream events.
* @param {string} events - comma-separated list of events to debug
*/
function debug (events) {
inspect.defaultOptions.depth = 11
Expand Down
61 changes: 61 additions & 0 deletions global.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import type { HookFn, mock } from 'node:test'
import type each_type from './lib/fixtures/test-each.js'

declare global {
var _cds_test_fixture: any;

// when extending global, only var can be used
var describe: {
(message: string, method: Function): void,
each?: typeof each_type;
skip: {
(...xs:any[]): unknown
each?: () => void;
}
};
var xdescribe: typeof describe['skip'];
var it: {
each?: typeof each_type,
skip: () => void
}
var test: typeof it;
var xtest: typeof it['skip'];
function before(method: Function): void;
function before(message: string & Function?, method: Function): void;
function beforeEach(method: Function): void;
function beforeAll(method: Function): void;
function beforeAll(message: string & Function?, method: Function): void;
function after(method: Function): void;
function after(message: string & Function?, method: Function): void;
function afterEach(method: HookFn): void;
function afterAll(method: Function): void;
function afterAll(message: string & Function?, method: Function): void;
function expect(_:any): void;

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

what is the signature for this parameter? I derived it from node-test.js where it is used as expect(this), but no idea what the proper type should be there.


var chai: {
expect: typeof expect,
should?: () => void,
fake?: boolean,
}

var jest: {
fn: () => void;
spyOn: typeof mock.method;
restoreAllMocks: () => void;
resetAllMocks: () => void;
clearAllMocks: () => void;
clearAllTimers: () => void;
mock: (
module: string | unknown,
fn?: Function,
o?: { virtual?: boolean }
) => void;
setTimeout: () => void;
}

// cds-dk types
var cds: {
repl: unknown
}
}
export {};
49 changes: 43 additions & 6 deletions lib/axios.js
Original file line number Diff line number Diff line change
@@ -1,29 +1,49 @@
/** @typedef {import('axios')} axios */
/** @typedef {import('axios').AxiosInstance} Axios */


const { NAXIOS } = process.env //> for early birds, aka canaries
// @ts-ignore
if (NAXIOS) require = id => module.require (id === 'axios' ? './naxios' : id) // eslint-disable-line no-global-assign

class AxiosProvider {
/** @type {Axios} */
// @ts-expect-error - will always be access through getter and thus be defined
#axios
/** @type {string | undefined} */
#url

get axios() {
const http = require('node:http')
/**@type {import('axios').default}*/
// @ts-expect-error - axios is ESM, this would require ugly cast to unknown -> axios.default
const axios = require('axios')
return super.axios = axios.create ({
return this.#axios ??= axios.create ({
httpAgent: new http.Agent({ keepAlive: false}), //> https://github.com/nodejs/node/issues/47130
headers: { 'content-type': 'application/json' },
baseURL: this.url,
baseURL: this.#url,
})
}

/** @param {string} url */
set url (url) { // fill in baseURL when this.url is filled in subsequently on server start
if (Object.hasOwn(this,'axios')) this.axios.defaults.baseURL = url
super.url = url
this.#url = url
}

/** @type {Axios["options"]} */
options (..._) { return this.axios.options (..._args(_)) .catch(_error) }
/** @type {Axios["head"]} */
head (..._) { return this.axios.head (..._args(_)) .catch(_error) }
/** @type {Axios["get"]} */
get (..._) { return this.axios.get (..._args(_)) .catch(_error) }
/** @type {Axios["put"]} */
put (..._) { return this.axios.put (..._args(_)) .catch(_error) }
/** @type {Axios["post"]} */
post (..._) { return this.axios.post (..._args(_)) .catch(_error) }
/** @type {Axios["patch"]} */
patch (..._) { return this.axios.patch (..._args(_)) .catch(_error) }
/** @type {Axios["delete"]} */
delete (..._) { return this.axios.delete (..._args(_)) .catch(_error) }

/** @type typeof self.options */ get OPTIONS() { return this.options .bind (this) }
Expand All @@ -39,17 +59,34 @@ class AxiosProvider {
const self = AxiosProvider.prototype // eslint-disable-line no-unused-vars


/**
* @template {any} T
* @param {T[]} args - args
* @returns {readonly T[]}
*/
const _args = (args) => {
const first = args[0], last = args.at(-1)
if (first.raw) {
if (first.at(-1) === '' && typeof last === 'object')
return [ String.raw(...args.slice(0,-1)).trim(), last ]
return [ String.raw(...args) ]
return (first.at(-1) === '' && typeof last === 'object')
// @ts-expect-error
? [ String.raw(...args.slice(0,-1)).trim(), last ]
// @ts-expect-error
: [ String.raw(...args) ]
}
if (typeof first === 'string') return args
else throw new Error (`Argument path is expected to be a string but got ${typeof first}`)
}

/**
* @typedef { Error & {
* cause: { code: string },
* code: string,
* status: number,
* errors?: ErrorType[],
* response: any
* }} ErrorType
*/
/** @param {ErrorType} err */
const _error = (err) => {

// Node 20 sends AggregationErrors -> REVISIT: is that still the case? Doesn't seem so with Node 22
Expand Down
70 changes: 52 additions & 18 deletions lib/cds-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,21 @@ class Test extends require('./axios') {
* Allows: const { GET, expect, test } = cds.test()
*/
test = this
/** @type {import('node:timers/promises').setTimeout | undefined} */
#sleep
/** @type {import('./data') | undefined} */
#data

/** @returns {import('@sap/cds')} */
get cds() { return require('@sap/cds/lib') }
get sleep() { return super.sleep = require('node:timers/promises').setTimeout }
get data() { return super.data = new (require('./data'))}
get sleep() { return this.#sleep = require('node:timers/promises').setTimeout }
get data() { return this.#data = new (require('./data'))}

/**
* Launches a cds server with arbitrary port and returns a subclass which
* also acts as an axios lookalike, providing methods to send requests.
* @param {string} folder_or_cmd - either a folder to serve or the command 'serve' or 'run'
* @param {...string} args - additional arguments, e.g. '--project', 'myapp'
*/
run (folder_or_cmd, ...args) {

Expand All @@ -29,14 +36,16 @@ class Test extends require('./axios') {
before (async ()=>{
process.env.cds_test_temp = cds.utils.path.resolve (cds.root,'_out',''+process.pid)
if (!args.includes('--port')) args.push ('--port', '0')
// @ts-expect-error - cds.exec is not in types (cds-dk?)
let { server, url } = await cds.exec (...args)
this.server = server
this.url = url
})

// gracefully shutdown cds server...
after (()=> Promise.all([
cds.utils.rimraf (process.env.cds_test_temp),
cds.utils.rimraf (/** @type {string} */(process.env.cds_test_temp)),
// @ts-expect-error - cds.shutdown not in types (cds-dk?)
cds.shutdown(),
]))

Expand All @@ -47,6 +56,8 @@ class Test extends require('./axios') {
* Serving projects from subfolders under the root specified by a sequence
* of path components which are concatenated with path.resolve().
* Checks conflicts with cds.env loaded in other folder before.
* @param {string} folder - folder name
* @param {...string} paths - additional path components
*/
in (folder, ...paths) {
if (!folder) return this
Expand All @@ -63,36 +74,47 @@ class Test extends require('./axios') {
if (process.env.CDS_TEST_ENV_CHECK) {
const env = Reflect.getOwnPropertyDescriptor(cds,'env')?.value
if (env && env._home !== folder && env.stack) {
let filter = line => !line.match(/node_modules\/jest-|node:internal/)
let filter = (/** @type {string} */line) => !line.match(/node_modules\/jest-|node:internal/)
let err = new Error; err.message =
`Detected cds.env loaded before running cds.test in different folder: \n` +
`1. cds.env loaded from: ${local(cds.env._home)||'./'} \n` +
`2. cds.test running in: ${local(folder)} \n\n` +
err.stack.split('\n').filter(filter).slice(1).join('\n')
err.stack?.split('\n').filter(filter).slice(1).join('\n')
err.stack = env.stack.split('\n').filter(filter).slice(1).join('\n')
throw err
}
}
// @ts-expect-error - cds.root is readonly in types
cds.root = folder
return this
}

/**
* Method to spy on a function in an object, similar to jest.spyOn().
* @template {any} T
* @param {T} o - object
* @param {keyof T} f - function name
*/
spy (o,f) {
const origin = o[f]
const origin = /** @type {Function} */(o[f])
/**
* @this {Test}
* @param {...any} args - arguments
*/
const fn = function (...args) {
++fn.called
return origin.apply(this,args)
return origin.apply(this, args)
}
fn.called = 0
// @ts-expect-error -
fn.restore = ()=> o[f] = origin
// @ts-expect-error -
return o[f] = fn
}

/**
* For usage in repl, e.g. var test = await cds.test()
* @param {(args: { server: import('http').Server, url: string }) => void} resolve - see cds.once(..., resolve)
*/
then (resolve) {
if (this.server) {
Expand All @@ -104,18 +126,20 @@ class Test extends require('./axios') {

/**
* Captures console.log output.
* @param {(message?: any, ...optionalParams: any[]) => void} capture
*/
log (_capture) {
log (capture) {

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Renamed, as underscore is generally used for "variables I don't use", "don't care", or "throwaway" (both, in Python, as well as in the ESLint rules no-unused-vars).
If there's a good reason for keeping the underscore, do let me know.

const {console} = global, {format} = require('util')
const log = { output: '' }
const log = { output: '', release: ()=>{}, clear: ()=>{} }
// @ts-expect-error - __proto__ hack
beforeAll(()=> global.console = { __proto__: console,
log: _capture ??= (..._)=> log.output += format(..._)+'\n',
info: _capture,
warn: _capture,
debug: _capture,
trace: _capture,
error: _capture,
timeEnd: _capture, time: ()=>{},
log: capture ??= (..._)=> log.output += format(..._)+'\n',
info: capture,
warn: capture,
debug: capture,
trace: capture,
error: capture,
timeEnd: capture, time: ()=>{},
})
afterAll (log.release = ()=>{ log.output = ''; global.console = console })
afterEach (log.clear = ()=>{ log.output = '' })
Expand All @@ -126,6 +150,7 @@ class Test extends require('./axios') {
* Silences all console log output, e.g.: CDS_TEST_SILENT=y jest/mocha ...
*/
silent(){
// @ts-expect-error - __proto__ hack
global.console = { __proto__: console,
log: ()=>{},
info: ()=>{},
Expand All @@ -152,6 +177,10 @@ class Test extends require('./axios') {
const chaip = require('chai-as-promised')
chai.use (chaip.default/*v8 on ESM*/ ?? chaip/*v7*/)
return chai

/**
* @param {string} mod
*/
function require (mod) { try { return module.require(mod) } catch(e) {
if (e.code === 'MODULE_NOT_FOUND')
throw new Error (`Failed to load required package '${mod}'. Please add it thru:`
Expand All @@ -172,8 +201,13 @@ class Test extends require('./axios') {
}


/** @type Test & ()=>Test */
module.exports = exports = Object.assign ((..._) => (new Test).run(..._), { Test })
/** @type {import('node:module').Module} */(module).exports = exports = Object.assign (
/**
* @param {any[]} _
*/
(..._) => (new Test).run(..._)
, { Test }
)

// Set prototype to allow usages like cds.test.in(), cds.test.log(), ...
Object.setPrototypeOf (exports, Test.prototype)
Expand Down
20 changes: 18 additions & 2 deletions lib/data.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,16 @@
const cds = require('@sap/cds')

class DataUtil {
/** @type {ReturnType<typeof DELETE.from>[] | undefined} */
_deletes

constructor() {
// This is to support simplified usage like that: beforeEach(test.data.reset)
const {reset} = this; this.reset = (x) => {
const {reset} = this
/**
* @param {any} [x]
*/
this.reset = x => {
if (typeof x === 'function') reset.call(this).then(x,x) // x is the done callback of jest -> no return
else if (x?.assert) return reset.call(this) // x is a node --test TestContext object -> ignore
else return reset.call(this,x) // x is a db service instance
Expand All @@ -15,11 +21,18 @@ class DataUtil {
global.beforeEach (() => this.reset())
}

/**
* @param {cds.DatabaseService} db - db
*/
async deploy(db) {
if (!db) db = await cds.connect.to('db')
// @ts-expect-error - dk type
await cds.deploy.data(db)
}

/**
* @param {cds.DatabaseService} db - db
*/
async delete(db) {
if (!db) db = await cds.connect.to('db')
if (!this._deletes) {
Expand All @@ -38,7 +51,10 @@ class DataUtil {
}
}

/* delete + new deploy from csv */
/**
* delete + new deploy from csv
* @param {cds.DatabaseService} db - db
*/
async reset(db) {
if (!db) db = await cds.connect.to('db')
await this.delete(db)
Expand Down
Loading
Loading